Automaton.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- Automaton.h - Support for driving TableGen-produced DFAs ----------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file implements class that drive and introspect deterministic finite-
  15. // state automata (DFAs) as generated by TableGen's -gen-automata backend.
  16. //
  17. // For a description of how to define an automaton, see
  18. // include/llvm/TableGen/Automaton.td.
  19. //
  20. // One important detail is that these deterministic automata are created from
  21. // (potentially) nondeterministic definitions. Therefore a unique sequence of
  22. // input symbols will produce one path through the DFA but multiple paths
  23. // through the original NFA. An automaton by default only returns "accepted" or
  24. // "not accepted", but frequently we want to analyze what NFA path was taken.
  25. // Finding a path through the NFA states that results in a DFA state can help
  26. // answer *what* the solution to a problem was, not just that there exists a
  27. // solution.
  28. //
  29. //===----------------------------------------------------------------------===//
  30. #ifndef LLVM_SUPPORT_AUTOMATON_H
  31. #define LLVM_SUPPORT_AUTOMATON_H
  32. #include "llvm/ADT/ArrayRef.h"
  33. #include "llvm/ADT/DenseMap.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/Support/Allocator.h"
  36. #include <deque>
  37. #include <map>
  38. #include <memory>
  39. #include <unordered_map>
  40. #include <vector>
  41. namespace llvm {
  42. using NfaPath = SmallVector<uint64_t, 4>;
  43. /// Forward define the pair type used by the automata transition info tables.
  44. ///
  45. /// Experimental results with large tables have shown a significant (multiple
  46. /// orders of magnitude) parsing speedup by using a custom struct here with a
  47. /// trivial constructor rather than std::pair<uint64_t, uint64_t>.
  48. struct NfaStatePair {
  49. uint64_t FromDfaState, ToDfaState;
  50. bool operator<(const NfaStatePair &Other) const {
  51. return std::make_tuple(FromDfaState, ToDfaState) <
  52. std::make_tuple(Other.FromDfaState, Other.ToDfaState);
  53. }
  54. };
  55. namespace internal {
  56. /// The internal class that maintains all possible paths through an NFA based
  57. /// on a path through the DFA.
  58. class NfaTranscriber {
  59. private:
  60. /// Cached transition table. This is a table of NfaStatePairs that contains
  61. /// zero-terminated sequences pointed to by DFA transitions.
  62. ArrayRef<NfaStatePair> TransitionInfo;
  63. /// A simple linked-list of traversed states that can have a shared tail. The
  64. /// traversed path is stored in reverse order with the latest state as the
  65. /// head.
  66. struct PathSegment {
  67. uint64_t State;
  68. PathSegment *Tail;
  69. };
  70. /// We allocate segment objects frequently. Allocate them upfront and dispose
  71. /// at the end of a traversal rather than hammering the system allocator.
  72. SpecificBumpPtrAllocator<PathSegment> Allocator;
  73. /// Heads of each tracked path. These are not ordered.
  74. std::deque<PathSegment *> Heads;
  75. /// The returned paths. This is populated during getPaths.
  76. SmallVector<NfaPath, 4> Paths;
  77. /// Create a new segment and return it.
  78. PathSegment *makePathSegment(uint64_t State, PathSegment *Tail) {
  79. PathSegment *P = Allocator.Allocate();
  80. *P = {State, Tail};
  81. return P;
  82. }
  83. /// Pairs defines a sequence of possible NFA transitions for a single DFA
  84. /// transition.
  85. void transition(ArrayRef<NfaStatePair> Pairs) {
  86. // Iterate over all existing heads. We will mutate the Heads deque during
  87. // iteration.
  88. unsigned NumHeads = Heads.size();
  89. for (unsigned I = 0; I < NumHeads; ++I) {
  90. PathSegment *Head = Heads[I];
  91. // The sequence of pairs is sorted. Select the set of pairs that
  92. // transition from the current head state.
  93. auto PI = lower_bound(Pairs, NfaStatePair{Head->State, 0ULL});
  94. auto PE = upper_bound(Pairs, NfaStatePair{Head->State, INT64_MAX});
  95. // For every transition from the current head state, add a new path
  96. // segment.
  97. for (; PI != PE; ++PI)
  98. if (PI->FromDfaState == Head->State)
  99. Heads.push_back(makePathSegment(PI->ToDfaState, Head));
  100. }
  101. // Now we've iterated over all the initial heads and added new ones,
  102. // dispose of the original heads.
  103. Heads.erase(Heads.begin(), std::next(Heads.begin(), NumHeads));
  104. }
  105. public:
  106. NfaTranscriber(ArrayRef<NfaStatePair> TransitionInfo)
  107. : TransitionInfo(TransitionInfo) {
  108. reset();
  109. }
  110. ArrayRef<NfaStatePair> getTransitionInfo() const {
  111. return TransitionInfo;
  112. }
  113. void reset() {
  114. Paths.clear();
  115. Heads.clear();
  116. Allocator.DestroyAll();
  117. // The initial NFA state is 0.
  118. Heads.push_back(makePathSegment(0ULL, nullptr));
  119. }
  120. void transition(unsigned TransitionInfoIdx) {
  121. unsigned EndIdx = TransitionInfoIdx;
  122. while (TransitionInfo[EndIdx].ToDfaState != 0)
  123. ++EndIdx;
  124. ArrayRef<NfaStatePair> Pairs(&TransitionInfo[TransitionInfoIdx],
  125. EndIdx - TransitionInfoIdx);
  126. transition(Pairs);
  127. }
  128. ArrayRef<NfaPath> getPaths() {
  129. Paths.clear();
  130. for (auto *Head : Heads) {
  131. NfaPath P;
  132. while (Head->State != 0) {
  133. P.push_back(Head->State);
  134. Head = Head->Tail;
  135. }
  136. std::reverse(P.begin(), P.end());
  137. Paths.push_back(std::move(P));
  138. }
  139. return Paths;
  140. }
  141. };
  142. } // namespace internal
  143. /// A deterministic finite-state automaton. The automaton is defined in
  144. /// TableGen; this object drives an automaton defined by tblgen-emitted tables.
  145. ///
  146. /// An automaton accepts a sequence of input tokens ("actions"). This class is
  147. /// templated on the type of these actions.
  148. template <typename ActionT> class Automaton {
  149. /// Map from {State, Action} to {NewState, TransitionInfoIdx}.
  150. /// TransitionInfoIdx is used by the DfaTranscriber to analyze the transition.
  151. /// FIXME: This uses a std::map because ActionT can be a pair type including
  152. /// an enum. In particular DenseMapInfo<ActionT> must be defined to use
  153. /// DenseMap here.
  154. /// This is a shared_ptr to allow very quick copy-construction of Automata; this
  155. /// state is immutable after construction so this is safe.
  156. using MapTy = std::map<std::pair<uint64_t, ActionT>, std::pair<uint64_t, unsigned>>;
  157. std::shared_ptr<MapTy> M;
  158. /// An optional transcription object. This uses much more state than simply
  159. /// traversing the DFA for acceptance, so is heap allocated.
  160. std::shared_ptr<internal::NfaTranscriber> Transcriber;
  161. /// The initial DFA state is 1.
  162. uint64_t State = 1;
  163. /// True if we should transcribe and false if not (even if Transcriber is defined).
  164. bool Transcribe;
  165. public:
  166. /// Create an automaton.
  167. /// \param Transitions The Transitions table as created by TableGen. Note that
  168. /// because the action type differs per automaton, the
  169. /// table type is templated as ArrayRef<InfoT>.
  170. /// \param TranscriptionTable The TransitionInfo table as created by TableGen.
  171. ///
  172. /// Providing the TranscriptionTable argument as non-empty will enable the
  173. /// use of transcription, which analyzes the possible paths in the original
  174. /// NFA taken by the DFA. NOTE: This is substantially more work than simply
  175. /// driving the DFA, so unless you require the getPaths() method leave this
  176. /// empty.
  177. template <typename InfoT>
  178. Automaton(ArrayRef<InfoT> Transitions,
  179. ArrayRef<NfaStatePair> TranscriptionTable = {}) {
  180. if (!TranscriptionTable.empty())
  181. Transcriber =
  182. std::make_shared<internal::NfaTranscriber>(TranscriptionTable);
  183. Transcribe = Transcriber != nullptr;
  184. M = std::make_shared<MapTy>();
  185. for (const auto &I : Transitions)
  186. // Greedily read and cache the transition table.
  187. M->emplace(std::make_pair(I.FromDfaState, I.Action),
  188. std::make_pair(I.ToDfaState, I.InfoIdx));
  189. }
  190. Automaton(const Automaton &Other)
  191. : M(Other.M), State(Other.State), Transcribe(Other.Transcribe) {
  192. // Transcriber is not thread-safe, so create a new instance on copy.
  193. if (Other.Transcriber)
  194. Transcriber = std::make_shared<internal::NfaTranscriber>(
  195. Other.Transcriber->getTransitionInfo());
  196. }
  197. /// Reset the automaton to its initial state.
  198. void reset() {
  199. State = 1;
  200. if (Transcriber)
  201. Transcriber->reset();
  202. }
  203. /// Enable or disable transcription. Transcription is only available if
  204. /// TranscriptionTable was provided to the constructor.
  205. void enableTranscription(bool Enable = true) {
  206. assert(Transcriber &&
  207. "Transcription is only available if TranscriptionTable was provided "
  208. "to the Automaton constructor");
  209. Transcribe = Enable;
  210. }
  211. /// Transition the automaton based on input symbol A. Return true if the
  212. /// automaton transitioned to a valid state, false if the automaton
  213. /// transitioned to an invalid state.
  214. ///
  215. /// If this function returns false, all methods are undefined until reset() is
  216. /// called.
  217. bool add(const ActionT &A) {
  218. auto I = M->find({State, A});
  219. if (I == M->end())
  220. return false;
  221. if (Transcriber && Transcribe)
  222. Transcriber->transition(I->second.second);
  223. State = I->second.first;
  224. return true;
  225. }
  226. /// Return true if the automaton can be transitioned based on input symbol A.
  227. bool canAdd(const ActionT &A) {
  228. auto I = M->find({State, A});
  229. return I != M->end();
  230. }
  231. /// Obtain a set of possible paths through the input nondeterministic
  232. /// automaton that could be obtained from the sequence of input actions
  233. /// presented to this deterministic automaton.
  234. ArrayRef<NfaPath> getNfaPaths() {
  235. assert(Transcriber && Transcribe &&
  236. "Can only obtain NFA paths if transcribing!");
  237. return Transcriber->getPaths();
  238. }
  239. };
  240. } // namespace llvm
  241. #endif // LLVM_SUPPORT_AUTOMATON_H
  242. #ifdef __GNUC__
  243. #pragma GCC diagnostic pop
  244. #endif