DFAEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. //===- DFAEmitter.cpp - Finite state automaton emitter --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This class can produce a generic deterministic finite state automaton (DFA),
  10. // given a set of possible states and transitions.
  11. //
  12. // The input transitions can be nondeterministic - this class will produce the
  13. // deterministic equivalent state machine.
  14. //
  15. // The generated code can run the DFA and produce an accepted / not accepted
  16. // state and also produce, given a sequence of transitions that results in an
  17. // accepted state, the sequence of intermediate states. This is useful if the
  18. // initial automaton was nondeterministic - it allows mapping back from the DFA
  19. // to the NFA.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "DFAEmitter.h"
  23. #include "SequenceToOffsetTable.h"
  24. #include "TableGenBackends.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/UniqueVector.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/TableGen/Record.h"
  31. #include <cassert>
  32. #include <cstdint>
  33. #include <deque>
  34. #include <map>
  35. #include <set>
  36. #include <string>
  37. #include <variant>
  38. #include <vector>
  39. #define DEBUG_TYPE "dfa-emitter"
  40. using namespace llvm;
  41. //===----------------------------------------------------------------------===//
  42. // DfaEmitter implementation. This is independent of the GenAutomaton backend.
  43. //===----------------------------------------------------------------------===//
  44. void DfaEmitter::addTransition(state_type From, state_type To, action_type A) {
  45. Actions.insert(A);
  46. NfaStates.insert(From);
  47. NfaStates.insert(To);
  48. NfaTransitions[{From, A}].push_back(To);
  49. ++NumNfaTransitions;
  50. }
  51. void DfaEmitter::visitDfaState(const DfaState &DS) {
  52. // For every possible action...
  53. auto FromId = DfaStates.idFor(DS);
  54. for (action_type A : Actions) {
  55. DfaState NewStates;
  56. DfaTransitionInfo TI;
  57. // For every represented state, word pair in the original NFA...
  58. for (state_type FromState : DS) {
  59. // If this action is possible from this state add the transitioned-to
  60. // states to NewStates.
  61. auto I = NfaTransitions.find({FromState, A});
  62. if (I == NfaTransitions.end())
  63. continue;
  64. for (state_type &ToState : I->second) {
  65. NewStates.push_back(ToState);
  66. TI.emplace_back(FromState, ToState);
  67. }
  68. }
  69. if (NewStates.empty())
  70. continue;
  71. // Sort and unique.
  72. sort(NewStates);
  73. NewStates.erase(std::unique(NewStates.begin(), NewStates.end()),
  74. NewStates.end());
  75. sort(TI);
  76. TI.erase(std::unique(TI.begin(), TI.end()), TI.end());
  77. unsigned ToId = DfaStates.insert(NewStates);
  78. DfaTransitions.emplace(std::make_pair(FromId, A), std::make_pair(ToId, TI));
  79. }
  80. }
  81. void DfaEmitter::constructDfa() {
  82. DfaState Initial(1, /*NFA initial state=*/0);
  83. DfaStates.insert(Initial);
  84. // Note that UniqueVector starts indices at 1, not zero.
  85. unsigned DfaStateId = 1;
  86. while (DfaStateId <= DfaStates.size()) {
  87. DfaState S = DfaStates[DfaStateId];
  88. visitDfaState(S);
  89. DfaStateId++;
  90. }
  91. }
  92. void DfaEmitter::emit(StringRef Name, raw_ostream &OS) {
  93. constructDfa();
  94. OS << "// Input NFA has " << NfaStates.size() << " states with "
  95. << NumNfaTransitions << " transitions.\n";
  96. OS << "// Generated DFA has " << DfaStates.size() << " states with "
  97. << DfaTransitions.size() << " transitions.\n\n";
  98. // Implementation note: We don't bake a simple std::pair<> here as it requires
  99. // significantly more effort to parse. A simple test with a large array of
  100. // struct-pairs (N=100000) took clang-10 6s to parse. The same array of
  101. // std::pair<uint64_t, uint64_t> took 242s. Instead we allow the user to
  102. // define the pair type.
  103. //
  104. // FIXME: It may make sense to emit these as ULEB sequences instead of
  105. // pairs of uint64_t.
  106. OS << "// A zero-terminated sequence of NFA state transitions. Every DFA\n";
  107. OS << "// transition implies a set of NFA transitions. These are referred\n";
  108. OS << "// to by index in " << Name << "Transitions[].\n";
  109. SequenceToOffsetTable<DfaTransitionInfo> Table;
  110. std::map<DfaTransitionInfo, unsigned> EmittedIndices;
  111. for (auto &T : DfaTransitions)
  112. Table.add(T.second.second);
  113. Table.layout();
  114. OS << "const std::array<NfaStatePair, " << Table.size() << "> " << Name
  115. << "TransitionInfo = {{\n";
  116. Table.emit(
  117. OS,
  118. [](raw_ostream &OS, std::pair<uint64_t, uint64_t> P) {
  119. OS << "{" << P.first << ", " << P.second << "}";
  120. },
  121. "{0ULL, 0ULL}");
  122. OS << "}};\n\n";
  123. OS << "// A transition in the generated " << Name << " DFA.\n";
  124. OS << "struct " << Name << "Transition {\n";
  125. OS << " unsigned FromDfaState; // The transitioned-from DFA state.\n";
  126. OS << " ";
  127. printActionType(OS);
  128. OS << " Action; // The input symbol that causes this transition.\n";
  129. OS << " unsigned ToDfaState; // The transitioned-to DFA state.\n";
  130. OS << " unsigned InfoIdx; // Start index into " << Name
  131. << "TransitionInfo.\n";
  132. OS << "};\n\n";
  133. OS << "// A table of DFA transitions, ordered by {FromDfaState, Action}.\n";
  134. OS << "// The initial state is 1, not zero.\n";
  135. OS << "const std::array<" << Name << "Transition, "
  136. << DfaTransitions.size() << "> " << Name << "Transitions = {{\n";
  137. for (auto &KV : DfaTransitions) {
  138. dfa_state_type From = KV.first.first;
  139. dfa_state_type To = KV.second.first;
  140. action_type A = KV.first.second;
  141. unsigned InfoIdx = Table.get(KV.second.second);
  142. OS << " {" << From << ", ";
  143. printActionValue(A, OS);
  144. OS << ", " << To << ", " << InfoIdx << "},\n";
  145. }
  146. OS << "\n}};\n\n";
  147. }
  148. void DfaEmitter::printActionType(raw_ostream &OS) { OS << "uint64_t"; }
  149. void DfaEmitter::printActionValue(action_type A, raw_ostream &OS) { OS << A; }
  150. //===----------------------------------------------------------------------===//
  151. // AutomatonEmitter implementation
  152. //===----------------------------------------------------------------------===//
  153. namespace {
  154. using Action = std::variant<Record *, unsigned, std::string>;
  155. using ActionTuple = std::vector<Action>;
  156. class Automaton;
  157. class Transition {
  158. uint64_t NewState;
  159. // The tuple of actions that causes this transition.
  160. ActionTuple Actions;
  161. // The types of the actions; this is the same across all transitions.
  162. SmallVector<std::string, 4> Types;
  163. public:
  164. Transition(Record *R, Automaton *Parent);
  165. const ActionTuple &getActions() { return Actions; }
  166. SmallVector<std::string, 4> getTypes() { return Types; }
  167. bool canTransitionFrom(uint64_t State);
  168. uint64_t transitionFrom(uint64_t State);
  169. };
  170. class Automaton {
  171. RecordKeeper &Records;
  172. Record *R;
  173. std::vector<Transition> Transitions;
  174. /// All possible action tuples, uniqued.
  175. UniqueVector<ActionTuple> Actions;
  176. /// The fields within each Transition object to find the action symbols.
  177. std::vector<StringRef> ActionSymbolFields;
  178. public:
  179. Automaton(RecordKeeper &Records, Record *R);
  180. void emit(raw_ostream &OS);
  181. ArrayRef<StringRef> getActionSymbolFields() { return ActionSymbolFields; }
  182. /// If the type of action A has been overridden (there exists a field
  183. /// "TypeOf_A") return that, otherwise return the empty string.
  184. StringRef getActionSymbolType(StringRef A);
  185. };
  186. class AutomatonEmitter {
  187. RecordKeeper &Records;
  188. public:
  189. AutomatonEmitter(RecordKeeper &R) : Records(R) {}
  190. void run(raw_ostream &OS);
  191. };
  192. /// A DfaEmitter implementation that can print our variant action type.
  193. class CustomDfaEmitter : public DfaEmitter {
  194. const UniqueVector<ActionTuple> &Actions;
  195. std::string TypeName;
  196. public:
  197. CustomDfaEmitter(const UniqueVector<ActionTuple> &Actions, StringRef TypeName)
  198. : Actions(Actions), TypeName(TypeName) {}
  199. void printActionType(raw_ostream &OS) override;
  200. void printActionValue(action_type A, raw_ostream &OS) override;
  201. };
  202. } // namespace
  203. void AutomatonEmitter::run(raw_ostream &OS) {
  204. for (Record *R : Records.getAllDerivedDefinitions("GenericAutomaton")) {
  205. Automaton A(Records, R);
  206. OS << "#ifdef GET_" << R->getName() << "_DECL\n";
  207. A.emit(OS);
  208. OS << "#endif // GET_" << R->getName() << "_DECL\n";
  209. }
  210. }
  211. Automaton::Automaton(RecordKeeper &Records, Record *R)
  212. : Records(Records), R(R) {
  213. LLVM_DEBUG(dbgs() << "Emitting automaton for " << R->getName() << "\n");
  214. ActionSymbolFields = R->getValueAsListOfStrings("SymbolFields");
  215. }
  216. void Automaton::emit(raw_ostream &OS) {
  217. StringRef TransitionClass = R->getValueAsString("TransitionClass");
  218. for (Record *T : Records.getAllDerivedDefinitions(TransitionClass)) {
  219. assert(T->isSubClassOf("Transition"));
  220. Transitions.emplace_back(T, this);
  221. Actions.insert(Transitions.back().getActions());
  222. }
  223. LLVM_DEBUG(dbgs() << " Action alphabet cardinality: " << Actions.size()
  224. << "\n");
  225. LLVM_DEBUG(dbgs() << " Each state has " << Transitions.size()
  226. << " potential transitions.\n");
  227. StringRef Name = R->getName();
  228. CustomDfaEmitter Emitter(Actions, std::string(Name) + "Action");
  229. // Starting from the initial state, build up a list of possible states and
  230. // transitions.
  231. std::deque<uint64_t> Worklist(1, 0);
  232. std::set<uint64_t> SeenStates;
  233. unsigned NumTransitions = 0;
  234. SeenStates.insert(Worklist.front());
  235. while (!Worklist.empty()) {
  236. uint64_t State = Worklist.front();
  237. Worklist.pop_front();
  238. for (Transition &T : Transitions) {
  239. if (!T.canTransitionFrom(State))
  240. continue;
  241. uint64_t NewState = T.transitionFrom(State);
  242. if (SeenStates.emplace(NewState).second)
  243. Worklist.emplace_back(NewState);
  244. ++NumTransitions;
  245. Emitter.addTransition(State, NewState, Actions.idFor(T.getActions()));
  246. }
  247. }
  248. LLVM_DEBUG(dbgs() << " NFA automaton has " << SeenStates.size()
  249. << " states with " << NumTransitions << " transitions.\n");
  250. (void) NumTransitions;
  251. const auto &ActionTypes = Transitions.back().getTypes();
  252. OS << "// The type of an action in the " << Name << " automaton.\n";
  253. if (ActionTypes.size() == 1) {
  254. OS << "using " << Name << "Action = " << ActionTypes[0] << ";\n";
  255. } else {
  256. OS << "using " << Name << "Action = std::tuple<" << join(ActionTypes, ", ")
  257. << ">;\n";
  258. }
  259. OS << "\n";
  260. Emitter.emit(Name, OS);
  261. }
  262. StringRef Automaton::getActionSymbolType(StringRef A) {
  263. Twine Ty = "TypeOf_" + A;
  264. if (!R->getValue(Ty.str()))
  265. return "";
  266. return R->getValueAsString(Ty.str());
  267. }
  268. Transition::Transition(Record *R, Automaton *Parent) {
  269. BitsInit *NewStateInit = R->getValueAsBitsInit("NewState");
  270. NewState = 0;
  271. assert(NewStateInit->getNumBits() <= sizeof(uint64_t) * 8 &&
  272. "State cannot be represented in 64 bits!");
  273. for (unsigned I = 0; I < NewStateInit->getNumBits(); ++I) {
  274. if (auto *Bit = dyn_cast<BitInit>(NewStateInit->getBit(I))) {
  275. if (Bit->getValue())
  276. NewState |= 1ULL << I;
  277. }
  278. }
  279. for (StringRef A : Parent->getActionSymbolFields()) {
  280. RecordVal *SymbolV = R->getValue(A);
  281. if (auto *Ty = dyn_cast<RecordRecTy>(SymbolV->getType())) {
  282. Actions.emplace_back(R->getValueAsDef(A));
  283. Types.emplace_back(Ty->getAsString());
  284. } else if (isa<IntRecTy>(SymbolV->getType())) {
  285. Actions.emplace_back(static_cast<unsigned>(R->getValueAsInt(A)));
  286. Types.emplace_back("unsigned");
  287. } else if (isa<StringRecTy>(SymbolV->getType())) {
  288. Actions.emplace_back(std::string(R->getValueAsString(A)));
  289. Types.emplace_back("std::string");
  290. } else {
  291. report_fatal_error("Unhandled symbol type!");
  292. }
  293. StringRef TypeOverride = Parent->getActionSymbolType(A);
  294. if (!TypeOverride.empty())
  295. Types.back() = std::string(TypeOverride);
  296. }
  297. }
  298. bool Transition::canTransitionFrom(uint64_t State) {
  299. if ((State & NewState) == 0)
  300. // The bits we want to set are not set;
  301. return true;
  302. return false;
  303. }
  304. uint64_t Transition::transitionFrom(uint64_t State) {
  305. return State | NewState;
  306. }
  307. void CustomDfaEmitter::printActionType(raw_ostream &OS) { OS << TypeName; }
  308. void CustomDfaEmitter::printActionValue(action_type A, raw_ostream &OS) {
  309. const ActionTuple &AT = Actions[A];
  310. if (AT.size() > 1)
  311. OS << "std::make_tuple(";
  312. ListSeparator LS;
  313. for (const auto &SingleAction : AT) {
  314. OS << LS;
  315. if (const auto *R = std::get_if<Record *>(&SingleAction))
  316. OS << (*R)->getName();
  317. else if (const auto *S = std::get_if<std::string>(&SingleAction))
  318. OS << '"' << *S << '"';
  319. else
  320. OS << std::get<unsigned>(SingleAction);
  321. }
  322. if (AT.size() > 1)
  323. OS << ")";
  324. }
  325. namespace llvm {
  326. void EmitAutomata(RecordKeeper &RK, raw_ostream &OS) {
  327. AutomatonEmitter(RK).run(OS);
  328. }
  329. } // namespace llvm