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