Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:27

0001 //===-- Automaton.h - Support for driving TableGen-produced DFAs ----------===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file implements class that drive and introspect deterministic finite-
0010 // state automata (DFAs) as generated by TableGen's -gen-automata backend.
0011 //
0012 // For a description of how to define an automaton, see
0013 // include/llvm/TableGen/Automaton.td.
0014 //
0015 // One important detail is that these deterministic automata are created from
0016 // (potentially) nondeterministic definitions. Therefore a unique sequence of
0017 // input symbols will produce one path through the DFA but multiple paths
0018 // through the original NFA. An automaton by default only returns "accepted" or
0019 // "not accepted", but frequently we want to analyze what NFA path was taken.
0020 // Finding a path through the NFA states that results in a DFA state can help
0021 // answer *what* the solution to a problem was, not just that there exists a
0022 // solution.
0023 //
0024 //===----------------------------------------------------------------------===//
0025 
0026 #ifndef LLVM_SUPPORT_AUTOMATON_H
0027 #define LLVM_SUPPORT_AUTOMATON_H
0028 
0029 #include "llvm/ADT/ArrayRef.h"
0030 #include "llvm/ADT/DenseMap.h"
0031 #include "llvm/ADT/SmallVector.h"
0032 #include "llvm/Support/Allocator.h"
0033 #include <deque>
0034 #include <map>
0035 #include <memory>
0036 
0037 namespace llvm {
0038 
0039 using NfaPath = SmallVector<uint64_t, 4>;
0040 
0041 /// Forward define the pair type used by the automata transition info tables.
0042 ///
0043 /// Experimental results with large tables have shown a significant (multiple
0044 /// orders of magnitude) parsing speedup by using a custom struct here with a
0045 /// trivial constructor rather than std::pair<uint64_t, uint64_t>.
0046 struct NfaStatePair {
0047   uint64_t FromDfaState, ToDfaState;
0048 
0049   bool operator<(const NfaStatePair &Other) const {
0050     return std::make_tuple(FromDfaState, ToDfaState) <
0051            std::make_tuple(Other.FromDfaState, Other.ToDfaState);
0052   }
0053 };
0054 
0055 namespace internal {
0056 /// The internal class that maintains all possible paths through an NFA based
0057 /// on a path through the DFA.
0058 class NfaTranscriber {
0059 private:
0060   /// Cached transition table. This is a table of NfaStatePairs that contains
0061   /// zero-terminated sequences pointed to by DFA transitions.
0062   ArrayRef<NfaStatePair> TransitionInfo;
0063 
0064   /// A simple linked-list of traversed states that can have a shared tail. The
0065   /// traversed path is stored in reverse order with the latest state as the
0066   /// head.
0067   struct PathSegment {
0068     uint64_t State;
0069     PathSegment *Tail;
0070   };
0071 
0072   /// We allocate segment objects frequently. Allocate them upfront and dispose
0073   /// at the end of a traversal rather than hammering the system allocator.
0074   SpecificBumpPtrAllocator<PathSegment> Allocator;
0075 
0076   /// Heads of each tracked path. These are not ordered.
0077   std::deque<PathSegment *> Heads;
0078 
0079   /// The returned paths. This is populated during getPaths.
0080   SmallVector<NfaPath, 4> Paths;
0081 
0082   /// Create a new segment and return it.
0083   PathSegment *makePathSegment(uint64_t State, PathSegment *Tail) {
0084     PathSegment *P = Allocator.Allocate();
0085     *P = {State, Tail};
0086     return P;
0087   }
0088 
0089   /// Pairs defines a sequence of possible NFA transitions for a single DFA
0090   /// transition.
0091   void transition(ArrayRef<NfaStatePair> Pairs) {
0092     // Iterate over all existing heads. We will mutate the Heads deque during
0093     // iteration.
0094     unsigned NumHeads = Heads.size();
0095     for (unsigned I = 0; I < NumHeads; ++I) {
0096       PathSegment *Head = Heads[I];
0097       // The sequence of pairs is sorted. Select the set of pairs that
0098       // transition from the current head state.
0099       auto PI = lower_bound(Pairs, NfaStatePair{Head->State, 0ULL});
0100       auto PE = upper_bound(Pairs, NfaStatePair{Head->State, INT64_MAX});
0101       // For every transition from the current head state, add a new path
0102       // segment.
0103       for (; PI != PE; ++PI)
0104         if (PI->FromDfaState == Head->State)
0105           Heads.push_back(makePathSegment(PI->ToDfaState, Head));
0106     }
0107     // Now we've iterated over all the initial heads and added new ones,
0108     // dispose of the original heads.
0109     Heads.erase(Heads.begin(), std::next(Heads.begin(), NumHeads));
0110   }
0111 
0112 public:
0113   NfaTranscriber(ArrayRef<NfaStatePair> TransitionInfo)
0114       : TransitionInfo(TransitionInfo) {
0115     reset();
0116   }
0117 
0118   ArrayRef<NfaStatePair> getTransitionInfo() const {
0119     return TransitionInfo;
0120   }
0121 
0122   void reset() {
0123     Paths.clear();
0124     Heads.clear();
0125     Allocator.DestroyAll();
0126     // The initial NFA state is 0.
0127     Heads.push_back(makePathSegment(0ULL, nullptr));
0128   }
0129 
0130   void transition(unsigned TransitionInfoIdx) {
0131     unsigned EndIdx = TransitionInfoIdx;
0132     while (TransitionInfo[EndIdx].ToDfaState != 0)
0133       ++EndIdx;
0134     ArrayRef<NfaStatePair> Pairs(&TransitionInfo[TransitionInfoIdx],
0135                                  EndIdx - TransitionInfoIdx);
0136     transition(Pairs);
0137   }
0138 
0139   ArrayRef<NfaPath> getPaths() {
0140     Paths.clear();
0141     for (auto *Head : Heads) {
0142       NfaPath P;
0143       while (Head->State != 0) {
0144         P.push_back(Head->State);
0145         Head = Head->Tail;
0146       }
0147       std::reverse(P.begin(), P.end());
0148       Paths.push_back(std::move(P));
0149     }
0150     return Paths;
0151   }
0152 };
0153 } // namespace internal
0154 
0155 /// A deterministic finite-state automaton. The automaton is defined in
0156 /// TableGen; this object drives an automaton defined by tblgen-emitted tables.
0157 ///
0158 /// An automaton accepts a sequence of input tokens ("actions"). This class is
0159 /// templated on the type of these actions.
0160 template <typename ActionT> class Automaton {
0161   /// Map from {State, Action} to {NewState, TransitionInfoIdx}.
0162   /// TransitionInfoIdx is used by the DfaTranscriber to analyze the transition.
0163   /// FIXME: This uses a std::map because ActionT can be a pair type including
0164   /// an enum. In particular DenseMapInfo<ActionT> must be defined to use
0165   /// DenseMap here.
0166   /// This is a shared_ptr to allow very quick copy-construction of Automata; this
0167   /// state is immutable after construction so this is safe.
0168   using MapTy = std::map<std::pair<uint64_t, ActionT>, std::pair<uint64_t, unsigned>>;
0169   std::shared_ptr<MapTy> M;
0170   /// An optional transcription object. This uses much more state than simply
0171   /// traversing the DFA for acceptance, so is heap allocated.
0172   std::shared_ptr<internal::NfaTranscriber> Transcriber;
0173   /// The initial DFA state is 1.
0174   uint64_t State = 1;
0175   /// True if we should transcribe and false if not (even if Transcriber is defined).
0176   bool Transcribe;
0177 
0178 public:
0179   /// Create an automaton.
0180   /// \param Transitions The Transitions table as created by TableGen. Note that
0181   ///                    because the action type differs per automaton, the
0182   ///                    table type is templated as ArrayRef<InfoT>.
0183   /// \param TranscriptionTable The TransitionInfo table as created by TableGen.
0184   ///
0185   /// Providing the TranscriptionTable argument as non-empty will enable the
0186   /// use of transcription, which analyzes the possible paths in the original
0187   /// NFA taken by the DFA. NOTE: This is substantially more work than simply
0188   /// driving the DFA, so unless you require the getPaths() method leave this
0189   /// empty.
0190   template <typename InfoT>
0191   Automaton(ArrayRef<InfoT> Transitions,
0192             ArrayRef<NfaStatePair> TranscriptionTable = {}) {
0193     if (!TranscriptionTable.empty())
0194       Transcriber =
0195           std::make_shared<internal::NfaTranscriber>(TranscriptionTable);
0196     Transcribe = Transcriber != nullptr;
0197     M = std::make_shared<MapTy>();
0198     for (const auto &I : Transitions)
0199       // Greedily read and cache the transition table.
0200       M->emplace(std::make_pair(I.FromDfaState, I.Action),
0201                  std::make_pair(I.ToDfaState, I.InfoIdx));
0202   }
0203   Automaton(const Automaton &Other)
0204       : M(Other.M), State(Other.State), Transcribe(Other.Transcribe) {
0205     // Transcriber is not thread-safe, so create a new instance on copy.
0206     if (Other.Transcriber)
0207       Transcriber = std::make_shared<internal::NfaTranscriber>(
0208           Other.Transcriber->getTransitionInfo());
0209   }
0210 
0211   /// Reset the automaton to its initial state.
0212   void reset() {
0213     State = 1;
0214     if (Transcriber)
0215       Transcriber->reset();
0216   }
0217 
0218   /// Enable or disable transcription. Transcription is only available if
0219   /// TranscriptionTable was provided to the constructor.
0220   void enableTranscription(bool Enable = true) {
0221     assert(Transcriber &&
0222            "Transcription is only available if TranscriptionTable was provided "
0223            "to the Automaton constructor");
0224     Transcribe = Enable;
0225   }
0226 
0227   /// Transition the automaton based on input symbol A. Return true if the
0228   /// automaton transitioned to a valid state, false if the automaton
0229   /// transitioned to an invalid state.
0230   ///
0231   /// If this function returns false, all methods are undefined until reset() is
0232   /// called.
0233   bool add(const ActionT &A) {
0234     auto I = M->find({State, A});
0235     if (I == M->end())
0236       return false;
0237     if (Transcriber && Transcribe)
0238       Transcriber->transition(I->second.second);
0239     State = I->second.first;
0240     return true;
0241   }
0242 
0243   /// Return true if the automaton can be transitioned based on input symbol A.
0244   bool canAdd(const ActionT &A) {
0245     auto I = M->find({State, A});
0246     return I != M->end();
0247   }
0248 
0249   /// Obtain a set of possible paths through the input nondeterministic
0250   /// automaton that could be obtained from the sequence of input actions
0251   /// presented to this deterministic automaton.
0252   ArrayRef<NfaPath> getNfaPaths() {
0253     assert(Transcriber && Transcribe &&
0254            "Can only obtain NFA paths if transcribing!");
0255     return Transcriber->getPaths();
0256   }
0257 };
0258 
0259 } // namespace llvm
0260 
0261 #endif // LLVM_SUPPORT_AUTOMATON_H