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