DFAPacketizerEmitter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //===- DFAPacketizerEmitter.cpp - Packetization DFA for a VLIW machine ----===//
  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 parses the Schedule.td file and produces an API that can be used
  10. // to reason about whether an instruction can be added to a packet on a VLIW
  11. // architecture. The class internally generates a deterministic finite
  12. // automaton (DFA) that models all possible mappings of machine instructions
  13. // to functional units as instructions are added to a packet.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "CodeGenSchedule.h"
  17. #include "CodeGenTarget.h"
  18. #include "DFAEmitter.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/Support/Debug.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "llvm/TableGen/Record.h"
  23. #include "llvm/TableGen/TableGenBackend.h"
  24. #include <cassert>
  25. #include <cstdint>
  26. #include <map>
  27. #include <set>
  28. #include <string>
  29. #include <unordered_map>
  30. #include <vector>
  31. #define DEBUG_TYPE "dfa-emitter"
  32. using namespace llvm;
  33. // We use a uint64_t to represent a resource bitmask.
  34. #define DFA_MAX_RESOURCES 64
  35. namespace {
  36. using ResourceVector = SmallVector<uint64_t, 4>;
  37. struct ScheduleClass {
  38. /// The parent itinerary index (processor model ID).
  39. unsigned ItineraryID;
  40. /// Index within this itinerary of the schedule class.
  41. unsigned Idx;
  42. /// The index within the uniqued set of required resources of Resources.
  43. unsigned ResourcesIdx;
  44. /// Conjunctive list of resource requirements:
  45. /// {a|b, b|c} => (a OR b) AND (b or c).
  46. /// Resources are unique across all itineraries.
  47. ResourceVector Resources;
  48. };
  49. // Generates and prints out the DFA for resource tracking.
  50. class DFAPacketizerEmitter {
  51. private:
  52. std::string TargetName;
  53. RecordKeeper &Records;
  54. UniqueVector<ResourceVector> UniqueResources;
  55. std::vector<ScheduleClass> ScheduleClasses;
  56. std::map<std::string, uint64_t> FUNameToBitsMap;
  57. std::map<unsigned, uint64_t> ComboBitToBitsMap;
  58. public:
  59. DFAPacketizerEmitter(RecordKeeper &R);
  60. // Construct a map of function unit names to bits.
  61. int collectAllFuncUnits(
  62. ArrayRef<const CodeGenProcModel *> ProcModels);
  63. // Construct a map from a combo function unit bit to the bits of all included
  64. // functional units.
  65. int collectAllComboFuncs(ArrayRef<Record *> ComboFuncList);
  66. ResourceVector getResourcesForItinerary(Record *Itinerary);
  67. void createScheduleClasses(unsigned ItineraryIdx, const RecVec &Itineraries);
  68. // Emit code for a subset of itineraries.
  69. void emitForItineraries(raw_ostream &OS,
  70. std::vector<const CodeGenProcModel *> &ProcItinList,
  71. std::string DFAName);
  72. void run(raw_ostream &OS);
  73. };
  74. } // end anonymous namespace
  75. DFAPacketizerEmitter::DFAPacketizerEmitter(RecordKeeper &R)
  76. : TargetName(std::string(CodeGenTarget(R).getName())), Records(R) {}
  77. int DFAPacketizerEmitter::collectAllFuncUnits(
  78. ArrayRef<const CodeGenProcModel *> ProcModels) {
  79. LLVM_DEBUG(dbgs() << "-------------------------------------------------------"
  80. "----------------------\n");
  81. LLVM_DEBUG(dbgs() << "collectAllFuncUnits");
  82. LLVM_DEBUG(dbgs() << " (" << ProcModels.size() << " itineraries)\n");
  83. std::set<Record *> ProcItinList;
  84. for (const CodeGenProcModel *Model : ProcModels)
  85. ProcItinList.insert(Model->ItinsDef);
  86. int totalFUs = 0;
  87. // Parse functional units for all the itineraries.
  88. for (Record *Proc : ProcItinList) {
  89. std::vector<Record *> FUs = Proc->getValueAsListOfDefs("FU");
  90. LLVM_DEBUG(dbgs() << " FU:"
  91. << " (" << FUs.size() << " FUs) " << Proc->getName());
  92. // Convert macros to bits for each stage.
  93. unsigned numFUs = FUs.size();
  94. for (unsigned j = 0; j < numFUs; ++j) {
  95. assert((j < DFA_MAX_RESOURCES) &&
  96. "Exceeded maximum number of representable resources");
  97. uint64_t FuncResources = 1ULL << j;
  98. FUNameToBitsMap[std::string(FUs[j]->getName())] = FuncResources;
  99. LLVM_DEBUG(dbgs() << " " << FUs[j]->getName() << ":0x"
  100. << Twine::utohexstr(FuncResources));
  101. }
  102. totalFUs += numFUs;
  103. LLVM_DEBUG(dbgs() << "\n");
  104. }
  105. return totalFUs;
  106. }
  107. int DFAPacketizerEmitter::collectAllComboFuncs(ArrayRef<Record *> ComboFuncList) {
  108. LLVM_DEBUG(dbgs() << "-------------------------------------------------------"
  109. "----------------------\n");
  110. LLVM_DEBUG(dbgs() << "collectAllComboFuncs");
  111. LLVM_DEBUG(dbgs() << " (" << ComboFuncList.size() << " sets)\n");
  112. int numCombos = 0;
  113. for (unsigned i = 0, N = ComboFuncList.size(); i < N; ++i) {
  114. Record *Func = ComboFuncList[i];
  115. std::vector<Record *> FUs = Func->getValueAsListOfDefs("CFD");
  116. LLVM_DEBUG(dbgs() << " CFD:" << i << " (" << FUs.size() << " combo FUs) "
  117. << Func->getName() << "\n");
  118. // Convert macros to bits for each stage.
  119. for (unsigned j = 0, N = FUs.size(); j < N; ++j) {
  120. assert((j < DFA_MAX_RESOURCES) &&
  121. "Exceeded maximum number of DFA resources");
  122. Record *FuncData = FUs[j];
  123. Record *ComboFunc = FuncData->getValueAsDef("TheComboFunc");
  124. const std::vector<Record *> &FuncList =
  125. FuncData->getValueAsListOfDefs("FuncList");
  126. const std::string &ComboFuncName = std::string(ComboFunc->getName());
  127. uint64_t ComboBit = FUNameToBitsMap[ComboFuncName];
  128. uint64_t ComboResources = ComboBit;
  129. LLVM_DEBUG(dbgs() << " combo: " << ComboFuncName << ":0x"
  130. << Twine::utohexstr(ComboResources) << "\n");
  131. for (auto *K : FuncList) {
  132. std::string FuncName = std::string(K->getName());
  133. uint64_t FuncResources = FUNameToBitsMap[FuncName];
  134. LLVM_DEBUG(dbgs() << " " << FuncName << ":0x"
  135. << Twine::utohexstr(FuncResources) << "\n");
  136. ComboResources |= FuncResources;
  137. }
  138. ComboBitToBitsMap[ComboBit] = ComboResources;
  139. numCombos++;
  140. LLVM_DEBUG(dbgs() << " => combo bits: " << ComboFuncName << ":0x"
  141. << Twine::utohexstr(ComboBit) << " = 0x"
  142. << Twine::utohexstr(ComboResources) << "\n");
  143. }
  144. }
  145. return numCombos;
  146. }
  147. ResourceVector
  148. DFAPacketizerEmitter::getResourcesForItinerary(Record *Itinerary) {
  149. ResourceVector Resources;
  150. assert(Itinerary);
  151. for (Record *StageDef : Itinerary->getValueAsListOfDefs("Stages")) {
  152. uint64_t StageResources = 0;
  153. for (Record *Unit : StageDef->getValueAsListOfDefs("Units")) {
  154. StageResources |= FUNameToBitsMap[std::string(Unit->getName())];
  155. }
  156. if (StageResources != 0)
  157. Resources.push_back(StageResources);
  158. }
  159. return Resources;
  160. }
  161. void DFAPacketizerEmitter::createScheduleClasses(unsigned ItineraryIdx,
  162. const RecVec &Itineraries) {
  163. unsigned Idx = 0;
  164. for (Record *Itinerary : Itineraries) {
  165. if (!Itinerary) {
  166. ScheduleClasses.push_back({ItineraryIdx, Idx++, 0, ResourceVector{}});
  167. continue;
  168. }
  169. ResourceVector Resources = getResourcesForItinerary(Itinerary);
  170. ScheduleClasses.push_back(
  171. {ItineraryIdx, Idx++, UniqueResources.insert(Resources), Resources});
  172. }
  173. }
  174. //
  175. // Run the worklist algorithm to generate the DFA.
  176. //
  177. void DFAPacketizerEmitter::run(raw_ostream &OS) {
  178. OS << "\n"
  179. << "#include \"llvm/CodeGen/DFAPacketizer.h\"\n";
  180. OS << "namespace llvm {\n";
  181. CodeGenTarget CGT(Records);
  182. CodeGenSchedModels CGS(Records, CGT);
  183. std::unordered_map<std::string, std::vector<const CodeGenProcModel *>>
  184. ItinsByNamespace;
  185. for (const CodeGenProcModel &ProcModel : CGS.procModels()) {
  186. if (ProcModel.hasItineraries()) {
  187. auto NS = ProcModel.ItinsDef->getValueAsString("PacketizerNamespace");
  188. ItinsByNamespace[std::string(NS)].push_back(&ProcModel);
  189. }
  190. }
  191. for (auto &KV : ItinsByNamespace)
  192. emitForItineraries(OS, KV.second, KV.first);
  193. OS << "} // end namespace llvm\n";
  194. }
  195. void DFAPacketizerEmitter::emitForItineraries(
  196. raw_ostream &OS, std::vector<const CodeGenProcModel *> &ProcModels,
  197. std::string DFAName) {
  198. OS << "} // end namespace llvm\n\n";
  199. OS << "namespace {\n";
  200. collectAllFuncUnits(ProcModels);
  201. collectAllComboFuncs(Records.getAllDerivedDefinitions("ComboFuncUnits"));
  202. // Collect the itineraries.
  203. DenseMap<const CodeGenProcModel *, unsigned> ProcModelStartIdx;
  204. for (const CodeGenProcModel *Model : ProcModels) {
  205. assert(Model->hasItineraries());
  206. ProcModelStartIdx[Model] = ScheduleClasses.size();
  207. createScheduleClasses(Model->Index, Model->ItinDefList);
  208. }
  209. // Output the mapping from ScheduleClass to ResourcesIdx.
  210. unsigned Idx = 0;
  211. OS << "constexpr unsigned " << TargetName << DFAName
  212. << "ResourceIndices[] = {";
  213. for (const ScheduleClass &SC : ScheduleClasses) {
  214. if (Idx++ % 32 == 0)
  215. OS << "\n ";
  216. OS << SC.ResourcesIdx << ", ";
  217. }
  218. OS << "\n};\n\n";
  219. // And the mapping from Itinerary index into the previous table.
  220. OS << "constexpr unsigned " << TargetName << DFAName
  221. << "ProcResourceIndexStart[] = {\n";
  222. OS << " 0, // NoSchedModel\n";
  223. for (const CodeGenProcModel *Model : ProcModels) {
  224. OS << " " << ProcModelStartIdx[Model] << ", // " << Model->ModelName
  225. << "\n";
  226. }
  227. OS << " " << ScheduleClasses.size() << "\n};\n\n";
  228. // The type of a state in the nondeterministic automaton we're defining.
  229. using NfaStateTy = uint64_t;
  230. // Given a resource state, return all resource states by applying
  231. // InsnClass.
  232. auto applyInsnClass = [&](const ResourceVector &InsnClass,
  233. NfaStateTy State) -> std::deque<NfaStateTy> {
  234. std::deque<NfaStateTy> V(1, State);
  235. // Apply every stage in the class individually.
  236. for (NfaStateTy Stage : InsnClass) {
  237. // Apply this stage to every existing member of V in turn.
  238. size_t Sz = V.size();
  239. for (unsigned I = 0; I < Sz; ++I) {
  240. NfaStateTy S = V.front();
  241. V.pop_front();
  242. // For this stage, state combination, try all possible resources.
  243. for (unsigned J = 0; J < DFA_MAX_RESOURCES; ++J) {
  244. NfaStateTy ResourceMask = 1ULL << J;
  245. if ((ResourceMask & Stage) == 0)
  246. // This resource isn't required by this stage.
  247. continue;
  248. NfaStateTy Combo = ComboBitToBitsMap[ResourceMask];
  249. if (Combo && ((~S & Combo) != Combo))
  250. // This combo units bits are not available.
  251. continue;
  252. NfaStateTy ResultingResourceState = S | ResourceMask | Combo;
  253. if (ResultingResourceState == S)
  254. continue;
  255. V.push_back(ResultingResourceState);
  256. }
  257. }
  258. }
  259. return V;
  260. };
  261. // Given a resource state, return a quick (conservative) guess as to whether
  262. // InsnClass can be applied. This is a filter for the more heavyweight
  263. // applyInsnClass.
  264. auto canApplyInsnClass = [](const ResourceVector &InsnClass,
  265. NfaStateTy State) -> bool {
  266. for (NfaStateTy Resources : InsnClass) {
  267. if ((State | Resources) == State)
  268. return false;
  269. }
  270. return true;
  271. };
  272. DfaEmitter Emitter;
  273. std::deque<NfaStateTy> Worklist(1, 0);
  274. std::set<NfaStateTy> SeenStates;
  275. SeenStates.insert(Worklist.front());
  276. while (!Worklist.empty()) {
  277. NfaStateTy State = Worklist.front();
  278. Worklist.pop_front();
  279. for (const ResourceVector &Resources : UniqueResources) {
  280. if (!canApplyInsnClass(Resources, State))
  281. continue;
  282. unsigned ResourcesID = UniqueResources.idFor(Resources);
  283. for (uint64_t NewState : applyInsnClass(Resources, State)) {
  284. if (SeenStates.emplace(NewState).second)
  285. Worklist.emplace_back(NewState);
  286. Emitter.addTransition(State, NewState, ResourcesID);
  287. }
  288. }
  289. }
  290. std::string TargetAndDFAName = TargetName + DFAName;
  291. Emitter.emit(TargetAndDFAName, OS);
  292. OS << "} // end anonymous namespace\n\n";
  293. std::string SubTargetClassName = TargetName + "GenSubtargetInfo";
  294. OS << "namespace llvm {\n";
  295. OS << "DFAPacketizer *" << SubTargetClassName << "::"
  296. << "create" << DFAName
  297. << "DFAPacketizer(const InstrItineraryData *IID) const {\n"
  298. << " static Automaton<uint64_t> A(ArrayRef<" << TargetAndDFAName
  299. << "Transition>(" << TargetAndDFAName << "Transitions), "
  300. << TargetAndDFAName << "TransitionInfo);\n"
  301. << " unsigned ProcResIdxStart = " << TargetAndDFAName
  302. << "ProcResourceIndexStart[IID->SchedModel.ProcID];\n"
  303. << " unsigned ProcResIdxNum = " << TargetAndDFAName
  304. << "ProcResourceIndexStart[IID->SchedModel.ProcID + 1] - "
  305. "ProcResIdxStart;\n"
  306. << " return new DFAPacketizer(IID, A, {&" << TargetAndDFAName
  307. << "ResourceIndices[ProcResIdxStart], ProcResIdxNum});\n"
  308. << "\n}\n\n";
  309. }
  310. namespace llvm {
  311. void EmitDFAPacketizer(RecordKeeper &RK, raw_ostream &OS) {
  312. emitSourceFileHeader("Target DFA Packetizer Tables", OS);
  313. DFAPacketizerEmitter(RK).run(OS);
  314. }
  315. } // end namespace llvm