SubtargetEmitter.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  1. //===- SubtargetEmitter.cpp - Generate subtarget enumerations -------------===//
  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 tablegen backend emits subtarget enumerations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenSchedule.h"
  13. #include "CodeGenTarget.h"
  14. #include "PredicateExpander.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/MC/MCInstrItineraries.h"
  20. #include "llvm/MC/MCSchedule.h"
  21. #include "llvm/MC/SubtargetFeature.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/Format.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/TableGen/Error.h"
  26. #include "llvm/TableGen/Record.h"
  27. #include "llvm/TableGen/TableGenBackend.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cstdint>
  31. #include <iterator>
  32. #include <map>
  33. #include <string>
  34. #include <vector>
  35. using namespace llvm;
  36. #define DEBUG_TYPE "subtarget-emitter"
  37. namespace {
  38. class SubtargetEmitter {
  39. // Each processor has a SchedClassDesc table with an entry for each SchedClass.
  40. // The SchedClassDesc table indexes into a global write resource table, write
  41. // latency table, and read advance table.
  42. struct SchedClassTables {
  43. std::vector<std::vector<MCSchedClassDesc>> ProcSchedClasses;
  44. std::vector<MCWriteProcResEntry> WriteProcResources;
  45. std::vector<MCWriteLatencyEntry> WriteLatencies;
  46. std::vector<std::string> WriterNames;
  47. std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
  48. // Reserve an invalid entry at index 0
  49. SchedClassTables() {
  50. ProcSchedClasses.resize(1);
  51. WriteProcResources.resize(1);
  52. WriteLatencies.resize(1);
  53. WriterNames.push_back("InvalidWrite");
  54. ReadAdvanceEntries.resize(1);
  55. }
  56. };
  57. struct LessWriteProcResources {
  58. bool operator()(const MCWriteProcResEntry &LHS,
  59. const MCWriteProcResEntry &RHS) {
  60. return LHS.ProcResourceIdx < RHS.ProcResourceIdx;
  61. }
  62. };
  63. const CodeGenTarget &TGT;
  64. RecordKeeper &Records;
  65. CodeGenSchedModels &SchedModels;
  66. std::string Target;
  67. void Enumeration(raw_ostream &OS, DenseMap<Record *, unsigned> &FeatureMap);
  68. void EmitSubtargetInfoMacroCalls(raw_ostream &OS);
  69. unsigned FeatureKeyValues(raw_ostream &OS,
  70. const DenseMap<Record *, unsigned> &FeatureMap);
  71. unsigned CPUKeyValues(raw_ostream &OS,
  72. const DenseMap<Record *, unsigned> &FeatureMap);
  73. void FormItineraryStageString(const std::string &Names,
  74. Record *ItinData, std::string &ItinString,
  75. unsigned &NStages);
  76. void FormItineraryOperandCycleString(Record *ItinData, std::string &ItinString,
  77. unsigned &NOperandCycles);
  78. void FormItineraryBypassString(const std::string &Names,
  79. Record *ItinData,
  80. std::string &ItinString, unsigned NOperandCycles);
  81. void EmitStageAndOperandCycleData(raw_ostream &OS,
  82. std::vector<std::vector<InstrItinerary>>
  83. &ProcItinLists);
  84. void EmitItineraries(raw_ostream &OS,
  85. std::vector<std::vector<InstrItinerary>>
  86. &ProcItinLists);
  87. unsigned EmitRegisterFileTables(const CodeGenProcModel &ProcModel,
  88. raw_ostream &OS);
  89. void EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel,
  90. raw_ostream &OS);
  91. void EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel,
  92. raw_ostream &OS);
  93. void EmitProcessorProp(raw_ostream &OS, const Record *R, StringRef Name,
  94. char Separator);
  95. void EmitProcessorResourceSubUnits(const CodeGenProcModel &ProcModel,
  96. raw_ostream &OS);
  97. void EmitProcessorResources(const CodeGenProcModel &ProcModel,
  98. raw_ostream &OS);
  99. Record *FindWriteResources(const CodeGenSchedRW &SchedWrite,
  100. const CodeGenProcModel &ProcModel);
  101. Record *FindReadAdvance(const CodeGenSchedRW &SchedRead,
  102. const CodeGenProcModel &ProcModel);
  103. void ExpandProcResources(RecVec &PRVec, std::vector<int64_t> &Cycles,
  104. const CodeGenProcModel &ProcModel);
  105. void GenSchedClassTables(const CodeGenProcModel &ProcModel,
  106. SchedClassTables &SchedTables);
  107. void EmitSchedClassTables(SchedClassTables &SchedTables, raw_ostream &OS);
  108. void EmitProcessorModels(raw_ostream &OS);
  109. void EmitSchedModelHelpers(const std::string &ClassName, raw_ostream &OS);
  110. void emitSchedModelHelpersImpl(raw_ostream &OS,
  111. bool OnlyExpandMCInstPredicates = false);
  112. void emitGenMCSubtargetInfo(raw_ostream &OS);
  113. void EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS);
  114. void EmitSchedModel(raw_ostream &OS);
  115. void EmitHwModeCheck(const std::string &ClassName, raw_ostream &OS);
  116. void ParseFeaturesFunction(raw_ostream &OS);
  117. public:
  118. SubtargetEmitter(RecordKeeper &R, CodeGenTarget &TGT)
  119. : TGT(TGT), Records(R), SchedModels(TGT.getSchedModels()),
  120. Target(TGT.getName()) {}
  121. void run(raw_ostream &o);
  122. };
  123. } // end anonymous namespace
  124. //
  125. // Enumeration - Emit the specified class as an enumeration.
  126. //
  127. void SubtargetEmitter::Enumeration(raw_ostream &OS,
  128. DenseMap<Record *, unsigned> &FeatureMap) {
  129. // Get all records of class and sort
  130. std::vector<Record*> DefList =
  131. Records.getAllDerivedDefinitions("SubtargetFeature");
  132. llvm::sort(DefList, LessRecord());
  133. unsigned N = DefList.size();
  134. if (N == 0)
  135. return;
  136. if (N + 1 > MAX_SUBTARGET_FEATURES)
  137. PrintFatalError("Too many subtarget features! Bump MAX_SUBTARGET_FEATURES.");
  138. OS << "namespace " << Target << " {\n";
  139. // Open enumeration.
  140. OS << "enum {\n";
  141. // For each record
  142. for (unsigned i = 0; i < N; ++i) {
  143. // Next record
  144. Record *Def = DefList[i];
  145. // Get and emit name
  146. OS << " " << Def->getName() << " = " << i << ",\n";
  147. // Save the index for this feature.
  148. FeatureMap[Def] = i;
  149. }
  150. OS << " "
  151. << "NumSubtargetFeatures = " << N << "\n";
  152. // Close enumeration and namespace
  153. OS << "};\n";
  154. OS << "} // end namespace " << Target << "\n";
  155. }
  156. static void printFeatureMask(raw_ostream &OS, RecVec &FeatureList,
  157. const DenseMap<Record *, unsigned> &FeatureMap) {
  158. std::array<uint64_t, MAX_SUBTARGET_WORDS> Mask = {};
  159. for (const Record *Feature : FeatureList) {
  160. unsigned Bit = FeatureMap.lookup(Feature);
  161. Mask[Bit / 64] |= 1ULL << (Bit % 64);
  162. }
  163. OS << "{ { { ";
  164. for (unsigned i = 0; i != Mask.size(); ++i) {
  165. OS << "0x";
  166. OS.write_hex(Mask[i]);
  167. OS << "ULL, ";
  168. }
  169. OS << "} } }";
  170. }
  171. /// Emit some information about the SubtargetFeature as calls to a macro so
  172. /// that they can be used from C++.
  173. void SubtargetEmitter::EmitSubtargetInfoMacroCalls(raw_ostream &OS) {
  174. OS << "\n#ifdef GET_SUBTARGETINFO_MACRO\n";
  175. std::vector<Record *> FeatureList =
  176. Records.getAllDerivedDefinitions("SubtargetFeature");
  177. llvm::sort(FeatureList, LessRecordFieldName());
  178. for (const Record *Feature : FeatureList) {
  179. const StringRef Attribute = Feature->getValueAsString("Attribute");
  180. const StringRef Value = Feature->getValueAsString("Value");
  181. // Only handle boolean features for now, excluding BitVectors and enums.
  182. const bool IsBool = (Value == "false" || Value == "true") &&
  183. !StringRef(Attribute).contains('[');
  184. if (!IsBool)
  185. continue;
  186. // Some features default to true, with values set to false if enabled.
  187. const char *Default = Value == "false" ? "true" : "false";
  188. // Define the getter with lowercased first char: xxxYyy() { return XxxYyy; }
  189. const std::string Getter =
  190. Attribute.substr(0, 1).lower() + Attribute.substr(1).str();
  191. OS << "GET_SUBTARGETINFO_MACRO(" << Attribute << ", " << Default << ", "
  192. << Getter << ")\n";
  193. }
  194. OS << "#undef GET_SUBTARGETINFO_MACRO\n";
  195. OS << "#endif // GET_SUBTARGETINFO_MACRO\n\n";
  196. OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
  197. OS << "#undef GET_SUBTARGETINFO_MC_DESC\n\n";
  198. }
  199. //
  200. // FeatureKeyValues - Emit data of all the subtarget features. Used by the
  201. // command line.
  202. //
  203. unsigned SubtargetEmitter::FeatureKeyValues(
  204. raw_ostream &OS, const DenseMap<Record *, unsigned> &FeatureMap) {
  205. // Gather and sort all the features
  206. std::vector<Record*> FeatureList =
  207. Records.getAllDerivedDefinitions("SubtargetFeature");
  208. if (FeatureList.empty())
  209. return 0;
  210. llvm::sort(FeatureList, LessRecordFieldName());
  211. // Begin feature table
  212. OS << "// Sorted (by key) array of values for CPU features.\n"
  213. << "extern const llvm::SubtargetFeatureKV " << Target
  214. << "FeatureKV[] = {\n";
  215. // For each feature
  216. unsigned NumFeatures = 0;
  217. for (const Record *Feature : FeatureList) {
  218. // Next feature
  219. StringRef Name = Feature->getName();
  220. StringRef CommandLineName = Feature->getValueAsString("Name");
  221. StringRef Desc = Feature->getValueAsString("Desc");
  222. if (CommandLineName.empty()) continue;
  223. // Emit as { "feature", "description", { featureEnum }, { i1 , i2 , ... , in } }
  224. OS << " { "
  225. << "\"" << CommandLineName << "\", "
  226. << "\"" << Desc << "\", "
  227. << Target << "::" << Name << ", ";
  228. RecVec ImpliesList = Feature->getValueAsListOfDefs("Implies");
  229. printFeatureMask(OS, ImpliesList, FeatureMap);
  230. OS << " },\n";
  231. ++NumFeatures;
  232. }
  233. // End feature table
  234. OS << "};\n";
  235. return NumFeatures;
  236. }
  237. //
  238. // CPUKeyValues - Emit data of all the subtarget processors. Used by command
  239. // line.
  240. //
  241. unsigned
  242. SubtargetEmitter::CPUKeyValues(raw_ostream &OS,
  243. const DenseMap<Record *, unsigned> &FeatureMap) {
  244. // Gather and sort processor information
  245. std::vector<Record*> ProcessorList =
  246. Records.getAllDerivedDefinitions("Processor");
  247. llvm::sort(ProcessorList, LessRecordFieldName());
  248. // Begin processor table
  249. OS << "// Sorted (by key) array of values for CPU subtype.\n"
  250. << "extern const llvm::SubtargetSubTypeKV " << Target
  251. << "SubTypeKV[] = {\n";
  252. // For each processor
  253. for (Record *Processor : ProcessorList) {
  254. StringRef Name = Processor->getValueAsString("Name");
  255. RecVec FeatureList = Processor->getValueAsListOfDefs("Features");
  256. RecVec TuneFeatureList = Processor->getValueAsListOfDefs("TuneFeatures");
  257. // Emit as { "cpu", "description", 0, { f1 , f2 , ... fn } },
  258. OS << " { "
  259. << "\"" << Name << "\", ";
  260. printFeatureMask(OS, FeatureList, FeatureMap);
  261. OS << ", ";
  262. printFeatureMask(OS, TuneFeatureList, FeatureMap);
  263. // Emit the scheduler model pointer.
  264. const std::string &ProcModelName =
  265. SchedModels.getModelForProc(Processor).ModelName;
  266. OS << ", &" << ProcModelName << " },\n";
  267. }
  268. // End processor table
  269. OS << "};\n";
  270. return ProcessorList.size();
  271. }
  272. //
  273. // FormItineraryStageString - Compose a string containing the stage
  274. // data initialization for the specified itinerary. N is the number
  275. // of stages.
  276. //
  277. void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
  278. Record *ItinData,
  279. std::string &ItinString,
  280. unsigned &NStages) {
  281. // Get states list
  282. RecVec StageList = ItinData->getValueAsListOfDefs("Stages");
  283. // For each stage
  284. unsigned N = NStages = StageList.size();
  285. for (unsigned i = 0; i < N;) {
  286. // Next stage
  287. const Record *Stage = StageList[i];
  288. // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
  289. int Cycles = Stage->getValueAsInt("Cycles");
  290. ItinString += " { " + itostr(Cycles) + ", ";
  291. // Get unit list
  292. RecVec UnitList = Stage->getValueAsListOfDefs("Units");
  293. // For each unit
  294. for (unsigned j = 0, M = UnitList.size(); j < M;) {
  295. // Add name and bitwise or
  296. ItinString += Name + "FU::" + UnitList[j]->getName().str();
  297. if (++j < M) ItinString += " | ";
  298. }
  299. int TimeInc = Stage->getValueAsInt("TimeInc");
  300. ItinString += ", " + itostr(TimeInc);
  301. int Kind = Stage->getValueAsInt("Kind");
  302. ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);
  303. // Close off stage
  304. ItinString += " }";
  305. if (++i < N) ItinString += ", ";
  306. }
  307. }
  308. //
  309. // FormItineraryOperandCycleString - Compose a string containing the
  310. // operand cycle initialization for the specified itinerary. N is the
  311. // number of operands that has cycles specified.
  312. //
  313. void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
  314. std::string &ItinString, unsigned &NOperandCycles) {
  315. // Get operand cycle list
  316. std::vector<int64_t> OperandCycleList =
  317. ItinData->getValueAsListOfInts("OperandCycles");
  318. // For each operand cycle
  319. NOperandCycles = OperandCycleList.size();
  320. ListSeparator LS;
  321. for (int OCycle : OperandCycleList) {
  322. // Next operand cycle
  323. ItinString += LS;
  324. ItinString += " " + itostr(OCycle);
  325. }
  326. }
  327. void SubtargetEmitter::FormItineraryBypassString(const std::string &Name,
  328. Record *ItinData,
  329. std::string &ItinString,
  330. unsigned NOperandCycles) {
  331. RecVec BypassList = ItinData->getValueAsListOfDefs("Bypasses");
  332. unsigned N = BypassList.size();
  333. unsigned i = 0;
  334. ListSeparator LS;
  335. for (; i < N; ++i) {
  336. ItinString += LS;
  337. ItinString += Name + "Bypass::" + BypassList[i]->getName().str();
  338. }
  339. for (; i < NOperandCycles; ++i) {
  340. ItinString += LS;
  341. ItinString += " 0";
  342. }
  343. }
  344. //
  345. // EmitStageAndOperandCycleData - Generate unique itinerary stages and operand
  346. // cycle tables. Create a list of InstrItinerary objects (ProcItinLists) indexed
  347. // by CodeGenSchedClass::Index.
  348. //
  349. void SubtargetEmitter::
  350. EmitStageAndOperandCycleData(raw_ostream &OS,
  351. std::vector<std::vector<InstrItinerary>>
  352. &ProcItinLists) {
  353. // Multiple processor models may share an itinerary record. Emit it once.
  354. SmallPtrSet<Record*, 8> ItinsDefSet;
  355. // Emit functional units for all the itineraries.
  356. for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
  357. if (!ItinsDefSet.insert(ProcModel.ItinsDef).second)
  358. continue;
  359. RecVec FUs = ProcModel.ItinsDef->getValueAsListOfDefs("FU");
  360. if (FUs.empty())
  361. continue;
  362. StringRef Name = ProcModel.ItinsDef->getName();
  363. OS << "\n// Functional units for \"" << Name << "\"\n"
  364. << "namespace " << Name << "FU {\n";
  365. for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
  366. OS << " const InstrStage::FuncUnits " << FUs[j]->getName()
  367. << " = 1ULL << " << j << ";\n";
  368. OS << "} // end namespace " << Name << "FU\n";
  369. RecVec BPs = ProcModel.ItinsDef->getValueAsListOfDefs("BP");
  370. if (!BPs.empty()) {
  371. OS << "\n// Pipeline forwarding paths for itineraries \"" << Name
  372. << "\"\n" << "namespace " << Name << "Bypass {\n";
  373. OS << " const unsigned NoBypass = 0;\n";
  374. for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
  375. OS << " const unsigned " << BPs[j]->getName()
  376. << " = 1 << " << j << ";\n";
  377. OS << "} // end namespace " << Name << "Bypass\n";
  378. }
  379. }
  380. // Begin stages table
  381. std::string StageTable = "\nextern const llvm::InstrStage " + Target +
  382. "Stages[] = {\n";
  383. StageTable += " { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";
  384. // Begin operand cycle table
  385. std::string OperandCycleTable = "extern const unsigned " + Target +
  386. "OperandCycles[] = {\n";
  387. OperandCycleTable += " 0, // No itinerary\n";
  388. // Begin pipeline bypass table
  389. std::string BypassTable = "extern const unsigned " + Target +
  390. "ForwardingPaths[] = {\n";
  391. BypassTable += " 0, // No itinerary\n";
  392. // For each Itinerary across all processors, add a unique entry to the stages,
  393. // operand cycles, and pipeline bypass tables. Then add the new Itinerary
  394. // object with computed offsets to the ProcItinLists result.
  395. unsigned StageCount = 1, OperandCycleCount = 1;
  396. std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
  397. for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
  398. // Add process itinerary to the list.
  399. ProcItinLists.resize(ProcItinLists.size()+1);
  400. // If this processor defines no itineraries, then leave the itinerary list
  401. // empty.
  402. std::vector<InstrItinerary> &ItinList = ProcItinLists.back();
  403. if (!ProcModel.hasItineraries())
  404. continue;
  405. StringRef Name = ProcModel.ItinsDef->getName();
  406. ItinList.resize(SchedModels.numInstrSchedClasses());
  407. assert(ProcModel.ItinDefList.size() == ItinList.size() && "bad Itins");
  408. for (unsigned SchedClassIdx = 0, SchedClassEnd = ItinList.size();
  409. SchedClassIdx < SchedClassEnd; ++SchedClassIdx) {
  410. // Next itinerary data
  411. Record *ItinData = ProcModel.ItinDefList[SchedClassIdx];
  412. // Get string and stage count
  413. std::string ItinStageString;
  414. unsigned NStages = 0;
  415. if (ItinData)
  416. FormItineraryStageString(std::string(Name), ItinData, ItinStageString,
  417. NStages);
  418. // Get string and operand cycle count
  419. std::string ItinOperandCycleString;
  420. unsigned NOperandCycles = 0;
  421. std::string ItinBypassString;
  422. if (ItinData) {
  423. FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
  424. NOperandCycles);
  425. FormItineraryBypassString(std::string(Name), ItinData, ItinBypassString,
  426. NOperandCycles);
  427. }
  428. // Check to see if stage already exists and create if it doesn't
  429. uint16_t FindStage = 0;
  430. if (NStages > 0) {
  431. FindStage = ItinStageMap[ItinStageString];
  432. if (FindStage == 0) {
  433. // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
  434. StageTable += ItinStageString + ", // " + itostr(StageCount);
  435. if (NStages > 1)
  436. StageTable += "-" + itostr(StageCount + NStages - 1);
  437. StageTable += "\n";
  438. // Record Itin class number.
  439. ItinStageMap[ItinStageString] = FindStage = StageCount;
  440. StageCount += NStages;
  441. }
  442. }
  443. // Check to see if operand cycle already exists and create if it doesn't
  444. uint16_t FindOperandCycle = 0;
  445. if (NOperandCycles > 0) {
  446. std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
  447. FindOperandCycle = ItinOperandMap[ItinOperandString];
  448. if (FindOperandCycle == 0) {
  449. // Emit as cycle, // index
  450. OperandCycleTable += ItinOperandCycleString + ", // ";
  451. std::string OperandIdxComment = itostr(OperandCycleCount);
  452. if (NOperandCycles > 1)
  453. OperandIdxComment += "-"
  454. + itostr(OperandCycleCount + NOperandCycles - 1);
  455. OperandCycleTable += OperandIdxComment + "\n";
  456. // Record Itin class number.
  457. ItinOperandMap[ItinOperandCycleString] =
  458. FindOperandCycle = OperandCycleCount;
  459. // Emit as bypass, // index
  460. BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
  461. OperandCycleCount += NOperandCycles;
  462. }
  463. }
  464. // Set up itinerary as location and location + stage count
  465. int16_t NumUOps = ItinData ? ItinData->getValueAsInt("NumMicroOps") : 0;
  466. InstrItinerary Intinerary = {
  467. NumUOps,
  468. FindStage,
  469. uint16_t(FindStage + NStages),
  470. FindOperandCycle,
  471. uint16_t(FindOperandCycle + NOperandCycles),
  472. };
  473. // Inject - empty slots will be 0, 0
  474. ItinList[SchedClassIdx] = Intinerary;
  475. }
  476. }
  477. // Closing stage
  478. StageTable += " { 0, 0, 0, llvm::InstrStage::Required } // End stages\n";
  479. StageTable += "};\n";
  480. // Closing operand cycles
  481. OperandCycleTable += " 0 // End operand cycles\n";
  482. OperandCycleTable += "};\n";
  483. BypassTable += " 0 // End bypass tables\n";
  484. BypassTable += "};\n";
  485. // Emit tables.
  486. OS << StageTable;
  487. OS << OperandCycleTable;
  488. OS << BypassTable;
  489. }
  490. //
  491. // EmitProcessorData - Generate data for processor itineraries that were
  492. // computed during EmitStageAndOperandCycleData(). ProcItinLists lists all
  493. // Itineraries for each processor. The Itinerary lists are indexed on
  494. // CodeGenSchedClass::Index.
  495. //
  496. void SubtargetEmitter::
  497. EmitItineraries(raw_ostream &OS,
  498. std::vector<std::vector<InstrItinerary>> &ProcItinLists) {
  499. // Multiple processor models may share an itinerary record. Emit it once.
  500. SmallPtrSet<Record*, 8> ItinsDefSet;
  501. // For each processor's machine model
  502. std::vector<std::vector<InstrItinerary>>::iterator
  503. ProcItinListsIter = ProcItinLists.begin();
  504. for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
  505. PE = SchedModels.procModelEnd(); PI != PE; ++PI, ++ProcItinListsIter) {
  506. Record *ItinsDef = PI->ItinsDef;
  507. if (!ItinsDefSet.insert(ItinsDef).second)
  508. continue;
  509. // Get the itinerary list for the processor.
  510. assert(ProcItinListsIter != ProcItinLists.end() && "bad iterator");
  511. std::vector<InstrItinerary> &ItinList = *ProcItinListsIter;
  512. // Empty itineraries aren't referenced anywhere in the tablegen output
  513. // so don't emit them.
  514. if (ItinList.empty())
  515. continue;
  516. OS << "\n";
  517. OS << "static const llvm::InstrItinerary ";
  518. // Begin processor itinerary table
  519. OS << ItinsDef->getName() << "[] = {\n";
  520. // For each itinerary class in CodeGenSchedClass::Index order.
  521. for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
  522. InstrItinerary &Intinerary = ItinList[j];
  523. // Emit Itinerary in the form of
  524. // { firstStage, lastStage, firstCycle, lastCycle } // index
  525. OS << " { " <<
  526. Intinerary.NumMicroOps << ", " <<
  527. Intinerary.FirstStage << ", " <<
  528. Intinerary.LastStage << ", " <<
  529. Intinerary.FirstOperandCycle << ", " <<
  530. Intinerary.LastOperandCycle << " }" <<
  531. ", // " << j << " " << SchedModels.getSchedClass(j).Name << "\n";
  532. }
  533. // End processor itinerary table
  534. OS << " { 0, uint16_t(~0U), uint16_t(~0U), uint16_t(~0U), uint16_t(~0U) }"
  535. "// end marker\n";
  536. OS << "};\n";
  537. }
  538. }
  539. // Emit either the value defined in the TableGen Record, or the default
  540. // value defined in the C++ header. The Record is null if the processor does not
  541. // define a model.
  542. void SubtargetEmitter::EmitProcessorProp(raw_ostream &OS, const Record *R,
  543. StringRef Name, char Separator) {
  544. OS << " ";
  545. int V = R ? R->getValueAsInt(Name) : -1;
  546. if (V >= 0)
  547. OS << V << Separator << " // " << Name;
  548. else
  549. OS << "MCSchedModel::Default" << Name << Separator;
  550. OS << '\n';
  551. }
  552. void SubtargetEmitter::EmitProcessorResourceSubUnits(
  553. const CodeGenProcModel &ProcModel, raw_ostream &OS) {
  554. OS << "\nstatic const unsigned " << ProcModel.ModelName
  555. << "ProcResourceSubUnits[] = {\n"
  556. << " 0, // Invalid\n";
  557. for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
  558. Record *PRDef = ProcModel.ProcResourceDefs[i];
  559. if (!PRDef->isSubClassOf("ProcResGroup"))
  560. continue;
  561. RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
  562. for (Record *RUDef : ResUnits) {
  563. Record *const RU =
  564. SchedModels.findProcResUnits(RUDef, ProcModel, PRDef->getLoc());
  565. for (unsigned J = 0; J < RU->getValueAsInt("NumUnits"); ++J) {
  566. OS << " " << ProcModel.getProcResourceIdx(RU) << ", ";
  567. }
  568. }
  569. OS << " // " << PRDef->getName() << "\n";
  570. }
  571. OS << "};\n";
  572. }
  573. static void EmitRetireControlUnitInfo(const CodeGenProcModel &ProcModel,
  574. raw_ostream &OS) {
  575. int64_t ReorderBufferSize = 0, MaxRetirePerCycle = 0;
  576. if (Record *RCU = ProcModel.RetireControlUnit) {
  577. ReorderBufferSize =
  578. std::max(ReorderBufferSize, RCU->getValueAsInt("ReorderBufferSize"));
  579. MaxRetirePerCycle =
  580. std::max(MaxRetirePerCycle, RCU->getValueAsInt("MaxRetirePerCycle"));
  581. }
  582. OS << ReorderBufferSize << ", // ReorderBufferSize\n ";
  583. OS << MaxRetirePerCycle << ", // MaxRetirePerCycle\n ";
  584. }
  585. static void EmitRegisterFileInfo(const CodeGenProcModel &ProcModel,
  586. unsigned NumRegisterFiles,
  587. unsigned NumCostEntries, raw_ostream &OS) {
  588. if (NumRegisterFiles)
  589. OS << ProcModel.ModelName << "RegisterFiles,\n " << (1 + NumRegisterFiles);
  590. else
  591. OS << "nullptr,\n 0";
  592. OS << ", // Number of register files.\n ";
  593. if (NumCostEntries)
  594. OS << ProcModel.ModelName << "RegisterCosts,\n ";
  595. else
  596. OS << "nullptr,\n ";
  597. OS << NumCostEntries << ", // Number of register cost entries.\n";
  598. }
  599. unsigned
  600. SubtargetEmitter::EmitRegisterFileTables(const CodeGenProcModel &ProcModel,
  601. raw_ostream &OS) {
  602. if (llvm::all_of(ProcModel.RegisterFiles, [](const CodeGenRegisterFile &RF) {
  603. return RF.hasDefaultCosts();
  604. }))
  605. return 0;
  606. // Print the RegisterCost table first.
  607. OS << "\n// {RegisterClassID, Register Cost, AllowMoveElimination }\n";
  608. OS << "static const llvm::MCRegisterCostEntry " << ProcModel.ModelName
  609. << "RegisterCosts"
  610. << "[] = {\n";
  611. for (const CodeGenRegisterFile &RF : ProcModel.RegisterFiles) {
  612. // Skip register files with a default cost table.
  613. if (RF.hasDefaultCosts())
  614. continue;
  615. // Add entries to the cost table.
  616. for (const CodeGenRegisterCost &RC : RF.Costs) {
  617. OS << " { ";
  618. Record *Rec = RC.RCDef;
  619. if (Rec->getValue("Namespace"))
  620. OS << Rec->getValueAsString("Namespace") << "::";
  621. OS << Rec->getName() << "RegClassID, " << RC.Cost << ", "
  622. << RC.AllowMoveElimination << "},\n";
  623. }
  624. }
  625. OS << "};\n";
  626. // Now generate a table with register file info.
  627. OS << "\n // {Name, #PhysRegs, #CostEntries, IndexToCostTbl, "
  628. << "MaxMovesEliminatedPerCycle, AllowZeroMoveEliminationOnly }\n";
  629. OS << "static const llvm::MCRegisterFileDesc " << ProcModel.ModelName
  630. << "RegisterFiles"
  631. << "[] = {\n"
  632. << " { \"InvalidRegisterFile\", 0, 0, 0, 0, 0 },\n";
  633. unsigned CostTblIndex = 0;
  634. for (const CodeGenRegisterFile &RD : ProcModel.RegisterFiles) {
  635. OS << " { ";
  636. OS << '"' << RD.Name << '"' << ", " << RD.NumPhysRegs << ", ";
  637. unsigned NumCostEntries = RD.Costs.size();
  638. OS << NumCostEntries << ", " << CostTblIndex << ", "
  639. << RD.MaxMovesEliminatedPerCycle << ", "
  640. << RD.AllowZeroMoveEliminationOnly << "},\n";
  641. CostTblIndex += NumCostEntries;
  642. }
  643. OS << "};\n";
  644. return CostTblIndex;
  645. }
  646. void SubtargetEmitter::EmitLoadStoreQueueInfo(const CodeGenProcModel &ProcModel,
  647. raw_ostream &OS) {
  648. unsigned QueueID = 0;
  649. if (ProcModel.LoadQueue) {
  650. const Record *Queue = ProcModel.LoadQueue->getValueAsDef("QueueDescriptor");
  651. QueueID = 1 + std::distance(ProcModel.ProcResourceDefs.begin(),
  652. find(ProcModel.ProcResourceDefs, Queue));
  653. }
  654. OS << " " << QueueID << ", // Resource Descriptor for the Load Queue\n";
  655. QueueID = 0;
  656. if (ProcModel.StoreQueue) {
  657. const Record *Queue =
  658. ProcModel.StoreQueue->getValueAsDef("QueueDescriptor");
  659. QueueID = 1 + std::distance(ProcModel.ProcResourceDefs.begin(),
  660. find(ProcModel.ProcResourceDefs, Queue));
  661. }
  662. OS << " " << QueueID << ", // Resource Descriptor for the Store Queue\n";
  663. }
  664. void SubtargetEmitter::EmitExtraProcessorInfo(const CodeGenProcModel &ProcModel,
  665. raw_ostream &OS) {
  666. // Generate a table of register file descriptors (one entry per each user
  667. // defined register file), and a table of register costs.
  668. unsigned NumCostEntries = EmitRegisterFileTables(ProcModel, OS);
  669. // Now generate a table for the extra processor info.
  670. OS << "\nstatic const llvm::MCExtraProcessorInfo " << ProcModel.ModelName
  671. << "ExtraInfo = {\n ";
  672. // Add information related to the retire control unit.
  673. EmitRetireControlUnitInfo(ProcModel, OS);
  674. // Add information related to the register files (i.e. where to find register
  675. // file descriptors and register costs).
  676. EmitRegisterFileInfo(ProcModel, ProcModel.RegisterFiles.size(),
  677. NumCostEntries, OS);
  678. // Add information about load/store queues.
  679. EmitLoadStoreQueueInfo(ProcModel, OS);
  680. OS << "};\n";
  681. }
  682. void SubtargetEmitter::EmitProcessorResources(const CodeGenProcModel &ProcModel,
  683. raw_ostream &OS) {
  684. EmitProcessorResourceSubUnits(ProcModel, OS);
  685. OS << "\n// {Name, NumUnits, SuperIdx, BufferSize, SubUnitsIdxBegin}\n";
  686. OS << "static const llvm::MCProcResourceDesc " << ProcModel.ModelName
  687. << "ProcResources"
  688. << "[] = {\n"
  689. << " {\"InvalidUnit\", 0, 0, 0, 0},\n";
  690. unsigned SubUnitsOffset = 1;
  691. for (unsigned i = 0, e = ProcModel.ProcResourceDefs.size(); i < e; ++i) {
  692. Record *PRDef = ProcModel.ProcResourceDefs[i];
  693. Record *SuperDef = nullptr;
  694. unsigned SuperIdx = 0;
  695. unsigned NumUnits = 0;
  696. const unsigned SubUnitsBeginOffset = SubUnitsOffset;
  697. int BufferSize = PRDef->getValueAsInt("BufferSize");
  698. if (PRDef->isSubClassOf("ProcResGroup")) {
  699. RecVec ResUnits = PRDef->getValueAsListOfDefs("Resources");
  700. for (Record *RU : ResUnits) {
  701. NumUnits += RU->getValueAsInt("NumUnits");
  702. SubUnitsOffset += RU->getValueAsInt("NumUnits");
  703. }
  704. }
  705. else {
  706. // Find the SuperIdx
  707. if (PRDef->getValueInit("Super")->isComplete()) {
  708. SuperDef =
  709. SchedModels.findProcResUnits(PRDef->getValueAsDef("Super"),
  710. ProcModel, PRDef->getLoc());
  711. SuperIdx = ProcModel.getProcResourceIdx(SuperDef);
  712. }
  713. NumUnits = PRDef->getValueAsInt("NumUnits");
  714. }
  715. // Emit the ProcResourceDesc
  716. OS << " {\"" << PRDef->getName() << "\", ";
  717. if (PRDef->getName().size() < 15)
  718. OS.indent(15 - PRDef->getName().size());
  719. OS << NumUnits << ", " << SuperIdx << ", " << BufferSize << ", ";
  720. if (SubUnitsBeginOffset != SubUnitsOffset) {
  721. OS << ProcModel.ModelName << "ProcResourceSubUnits + "
  722. << SubUnitsBeginOffset;
  723. } else {
  724. OS << "nullptr";
  725. }
  726. OS << "}, // #" << i+1;
  727. if (SuperDef)
  728. OS << ", Super=" << SuperDef->getName();
  729. OS << "\n";
  730. }
  731. OS << "};\n";
  732. }
  733. // Find the WriteRes Record that defines processor resources for this
  734. // SchedWrite.
  735. Record *SubtargetEmitter::FindWriteResources(
  736. const CodeGenSchedRW &SchedWrite, const CodeGenProcModel &ProcModel) {
  737. // Check if the SchedWrite is already subtarget-specific and directly
  738. // specifies a set of processor resources.
  739. if (SchedWrite.TheDef->isSubClassOf("SchedWriteRes"))
  740. return SchedWrite.TheDef;
  741. Record *AliasDef = nullptr;
  742. for (Record *A : SchedWrite.Aliases) {
  743. const CodeGenSchedRW &AliasRW =
  744. SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
  745. if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
  746. Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
  747. if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
  748. continue;
  749. }
  750. if (AliasDef)
  751. PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
  752. "defined for processor " + ProcModel.ModelName +
  753. " Ensure only one SchedAlias exists per RW.");
  754. AliasDef = AliasRW.TheDef;
  755. }
  756. if (AliasDef && AliasDef->isSubClassOf("SchedWriteRes"))
  757. return AliasDef;
  758. // Check this processor's list of write resources.
  759. Record *ResDef = nullptr;
  760. for (Record *WR : ProcModel.WriteResDefs) {
  761. if (!WR->isSubClassOf("WriteRes"))
  762. continue;
  763. if (AliasDef == WR->getValueAsDef("WriteType")
  764. || SchedWrite.TheDef == WR->getValueAsDef("WriteType")) {
  765. if (ResDef) {
  766. PrintFatalError(WR->getLoc(), "Resources are defined for both "
  767. "SchedWrite and its alias on processor " +
  768. ProcModel.ModelName);
  769. }
  770. ResDef = WR;
  771. }
  772. }
  773. // TODO: If ProcModel has a base model (previous generation processor),
  774. // then call FindWriteResources recursively with that model here.
  775. if (!ResDef) {
  776. PrintFatalError(ProcModel.ModelDef->getLoc(),
  777. Twine("Processor does not define resources for ") +
  778. SchedWrite.TheDef->getName());
  779. }
  780. return ResDef;
  781. }
  782. /// Find the ReadAdvance record for the given SchedRead on this processor or
  783. /// return NULL.
  784. Record *SubtargetEmitter::FindReadAdvance(const CodeGenSchedRW &SchedRead,
  785. const CodeGenProcModel &ProcModel) {
  786. // Check for SchedReads that directly specify a ReadAdvance.
  787. if (SchedRead.TheDef->isSubClassOf("SchedReadAdvance"))
  788. return SchedRead.TheDef;
  789. // Check this processor's list of aliases for SchedRead.
  790. Record *AliasDef = nullptr;
  791. for (Record *A : SchedRead.Aliases) {
  792. const CodeGenSchedRW &AliasRW =
  793. SchedModels.getSchedRW(A->getValueAsDef("AliasRW"));
  794. if (AliasRW.TheDef->getValueInit("SchedModel")->isComplete()) {
  795. Record *ModelDef = AliasRW.TheDef->getValueAsDef("SchedModel");
  796. if (&SchedModels.getProcModel(ModelDef) != &ProcModel)
  797. continue;
  798. }
  799. if (AliasDef)
  800. PrintFatalError(AliasRW.TheDef->getLoc(), "Multiple aliases "
  801. "defined for processor " + ProcModel.ModelName +
  802. " Ensure only one SchedAlias exists per RW.");
  803. AliasDef = AliasRW.TheDef;
  804. }
  805. if (AliasDef && AliasDef->isSubClassOf("SchedReadAdvance"))
  806. return AliasDef;
  807. // Check this processor's ReadAdvanceList.
  808. Record *ResDef = nullptr;
  809. for (Record *RA : ProcModel.ReadAdvanceDefs) {
  810. if (!RA->isSubClassOf("ReadAdvance"))
  811. continue;
  812. if (AliasDef == RA->getValueAsDef("ReadType")
  813. || SchedRead.TheDef == RA->getValueAsDef("ReadType")) {
  814. if (ResDef) {
  815. PrintFatalError(RA->getLoc(), "Resources are defined for both "
  816. "SchedRead and its alias on processor " +
  817. ProcModel.ModelName);
  818. }
  819. ResDef = RA;
  820. }
  821. }
  822. // TODO: If ProcModel has a base model (previous generation processor),
  823. // then call FindReadAdvance recursively with that model here.
  824. if (!ResDef && SchedRead.TheDef->getName() != "ReadDefault") {
  825. PrintFatalError(ProcModel.ModelDef->getLoc(),
  826. Twine("Processor does not define resources for ") +
  827. SchedRead.TheDef->getName());
  828. }
  829. return ResDef;
  830. }
  831. // Expand an explicit list of processor resources into a full list of implied
  832. // resource groups and super resources that cover them.
  833. void SubtargetEmitter::ExpandProcResources(RecVec &PRVec,
  834. std::vector<int64_t> &Cycles,
  835. const CodeGenProcModel &PM) {
  836. assert(PRVec.size() == Cycles.size() && "failed precondition");
  837. for (unsigned i = 0, e = PRVec.size(); i != e; ++i) {
  838. Record *PRDef = PRVec[i];
  839. RecVec SubResources;
  840. if (PRDef->isSubClassOf("ProcResGroup"))
  841. SubResources = PRDef->getValueAsListOfDefs("Resources");
  842. else {
  843. SubResources.push_back(PRDef);
  844. PRDef = SchedModels.findProcResUnits(PRDef, PM, PRDef->getLoc());
  845. for (Record *SubDef = PRDef;
  846. SubDef->getValueInit("Super")->isComplete();) {
  847. if (SubDef->isSubClassOf("ProcResGroup")) {
  848. // Disallow this for simplicitly.
  849. PrintFatalError(SubDef->getLoc(), "Processor resource group "
  850. " cannot be a super resources.");
  851. }
  852. Record *SuperDef =
  853. SchedModels.findProcResUnits(SubDef->getValueAsDef("Super"), PM,
  854. SubDef->getLoc());
  855. PRVec.push_back(SuperDef);
  856. Cycles.push_back(Cycles[i]);
  857. SubDef = SuperDef;
  858. }
  859. }
  860. for (Record *PR : PM.ProcResourceDefs) {
  861. if (PR == PRDef || !PR->isSubClassOf("ProcResGroup"))
  862. continue;
  863. RecVec SuperResources = PR->getValueAsListOfDefs("Resources");
  864. RecIter SubI = SubResources.begin(), SubE = SubResources.end();
  865. for( ; SubI != SubE; ++SubI) {
  866. if (!is_contained(SuperResources, *SubI)) {
  867. break;
  868. }
  869. }
  870. if (SubI == SubE) {
  871. PRVec.push_back(PR);
  872. Cycles.push_back(Cycles[i]);
  873. }
  874. }
  875. }
  876. }
  877. // Generate the SchedClass table for this processor and update global
  878. // tables. Must be called for each processor in order.
  879. void SubtargetEmitter::GenSchedClassTables(const CodeGenProcModel &ProcModel,
  880. SchedClassTables &SchedTables) {
  881. SchedTables.ProcSchedClasses.resize(SchedTables.ProcSchedClasses.size() + 1);
  882. if (!ProcModel.hasInstrSchedModel())
  883. return;
  884. std::vector<MCSchedClassDesc> &SCTab = SchedTables.ProcSchedClasses.back();
  885. LLVM_DEBUG(dbgs() << "\n+++ SCHED CLASSES (GenSchedClassTables) +++\n");
  886. for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
  887. LLVM_DEBUG(SC.dump(&SchedModels));
  888. SCTab.resize(SCTab.size() + 1);
  889. MCSchedClassDesc &SCDesc = SCTab.back();
  890. // SCDesc.Name is guarded by NDEBUG
  891. SCDesc.NumMicroOps = 0;
  892. SCDesc.BeginGroup = false;
  893. SCDesc.EndGroup = false;
  894. SCDesc.RetireOOO = false;
  895. SCDesc.WriteProcResIdx = 0;
  896. SCDesc.WriteLatencyIdx = 0;
  897. SCDesc.ReadAdvanceIdx = 0;
  898. // A Variant SchedClass has no resources of its own.
  899. bool HasVariants = false;
  900. for (const CodeGenSchedTransition &CGT :
  901. make_range(SC.Transitions.begin(), SC.Transitions.end())) {
  902. if (CGT.ProcIndex == ProcModel.Index) {
  903. HasVariants = true;
  904. break;
  905. }
  906. }
  907. if (HasVariants) {
  908. SCDesc.NumMicroOps = MCSchedClassDesc::VariantNumMicroOps;
  909. continue;
  910. }
  911. // Determine if the SchedClass is actually reachable on this processor. If
  912. // not don't try to locate the processor resources, it will fail.
  913. // If ProcIndices contains 0, this class applies to all processors.
  914. assert(!SC.ProcIndices.empty() && "expect at least one procidx");
  915. if (SC.ProcIndices[0] != 0) {
  916. if (!is_contained(SC.ProcIndices, ProcModel.Index))
  917. continue;
  918. }
  919. IdxVec Writes = SC.Writes;
  920. IdxVec Reads = SC.Reads;
  921. if (!SC.InstRWs.empty()) {
  922. // This class has a default ReadWrite list which can be overridden by
  923. // InstRW definitions.
  924. Record *RWDef = nullptr;
  925. for (Record *RW : SC.InstRWs) {
  926. Record *RWModelDef = RW->getValueAsDef("SchedModel");
  927. if (&ProcModel == &SchedModels.getProcModel(RWModelDef)) {
  928. RWDef = RW;
  929. break;
  930. }
  931. }
  932. if (RWDef) {
  933. Writes.clear();
  934. Reads.clear();
  935. SchedModels.findRWs(RWDef->getValueAsListOfDefs("OperandReadWrites"),
  936. Writes, Reads);
  937. }
  938. }
  939. if (Writes.empty()) {
  940. // Check this processor's itinerary class resources.
  941. for (Record *I : ProcModel.ItinRWDefs) {
  942. RecVec Matched = I->getValueAsListOfDefs("MatchedItinClasses");
  943. if (is_contained(Matched, SC.ItinClassDef)) {
  944. SchedModels.findRWs(I->getValueAsListOfDefs("OperandReadWrites"),
  945. Writes, Reads);
  946. break;
  947. }
  948. }
  949. if (Writes.empty()) {
  950. LLVM_DEBUG(dbgs() << ProcModel.ModelName
  951. << " does not have resources for class " << SC.Name
  952. << '\n');
  953. SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
  954. }
  955. }
  956. // Sum resources across all operand writes.
  957. std::vector<MCWriteProcResEntry> WriteProcResources;
  958. std::vector<MCWriteLatencyEntry> WriteLatencies;
  959. std::vector<std::string> WriterNames;
  960. std::vector<MCReadAdvanceEntry> ReadAdvanceEntries;
  961. for (unsigned W : Writes) {
  962. IdxVec WriteSeq;
  963. SchedModels.expandRWSeqForProc(W, WriteSeq, /*IsRead=*/false,
  964. ProcModel);
  965. // For each operand, create a latency entry.
  966. MCWriteLatencyEntry WLEntry;
  967. WLEntry.Cycles = 0;
  968. unsigned WriteID = WriteSeq.back();
  969. WriterNames.push_back(SchedModels.getSchedWrite(WriteID).Name);
  970. // If this Write is not referenced by a ReadAdvance, don't distinguish it
  971. // from other WriteLatency entries.
  972. if (!SchedModels.hasReadOfWrite(
  973. SchedModels.getSchedWrite(WriteID).TheDef)) {
  974. WriteID = 0;
  975. }
  976. WLEntry.WriteResourceID = WriteID;
  977. for (unsigned WS : WriteSeq) {
  978. Record *WriteRes =
  979. FindWriteResources(SchedModels.getSchedWrite(WS), ProcModel);
  980. // Mark the parent class as invalid for unsupported write types.
  981. if (WriteRes->getValueAsBit("Unsupported")) {
  982. SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
  983. break;
  984. }
  985. WLEntry.Cycles += WriteRes->getValueAsInt("Latency");
  986. SCDesc.NumMicroOps += WriteRes->getValueAsInt("NumMicroOps");
  987. SCDesc.BeginGroup |= WriteRes->getValueAsBit("BeginGroup");
  988. SCDesc.EndGroup |= WriteRes->getValueAsBit("EndGroup");
  989. SCDesc.BeginGroup |= WriteRes->getValueAsBit("SingleIssue");
  990. SCDesc.EndGroup |= WriteRes->getValueAsBit("SingleIssue");
  991. SCDesc.RetireOOO |= WriteRes->getValueAsBit("RetireOOO");
  992. // Create an entry for each ProcResource listed in WriteRes.
  993. RecVec PRVec = WriteRes->getValueAsListOfDefs("ProcResources");
  994. std::vector<int64_t> Cycles =
  995. WriteRes->getValueAsListOfInts("ResourceCycles");
  996. if (Cycles.empty()) {
  997. // If ResourceCycles is not provided, default to one cycle per
  998. // resource.
  999. Cycles.resize(PRVec.size(), 1);
  1000. } else if (Cycles.size() != PRVec.size()) {
  1001. // If ResourceCycles is provided, check consistency.
  1002. PrintFatalError(
  1003. WriteRes->getLoc(),
  1004. Twine("Inconsistent resource cycles: !size(ResourceCycles) != "
  1005. "!size(ProcResources): ")
  1006. .concat(Twine(PRVec.size()))
  1007. .concat(" vs ")
  1008. .concat(Twine(Cycles.size())));
  1009. }
  1010. ExpandProcResources(PRVec, Cycles, ProcModel);
  1011. for (unsigned PRIdx = 0, PREnd = PRVec.size();
  1012. PRIdx != PREnd; ++PRIdx) {
  1013. MCWriteProcResEntry WPREntry;
  1014. WPREntry.ProcResourceIdx = ProcModel.getProcResourceIdx(PRVec[PRIdx]);
  1015. assert(WPREntry.ProcResourceIdx && "Bad ProcResourceIdx");
  1016. WPREntry.Cycles = Cycles[PRIdx];
  1017. // If this resource is already used in this sequence, add the current
  1018. // entry's cycles so that the same resource appears to be used
  1019. // serially, rather than multiple parallel uses. This is important for
  1020. // in-order machine where the resource consumption is a hazard.
  1021. unsigned WPRIdx = 0, WPREnd = WriteProcResources.size();
  1022. for( ; WPRIdx != WPREnd; ++WPRIdx) {
  1023. if (WriteProcResources[WPRIdx].ProcResourceIdx
  1024. == WPREntry.ProcResourceIdx) {
  1025. WriteProcResources[WPRIdx].Cycles += WPREntry.Cycles;
  1026. break;
  1027. }
  1028. }
  1029. if (WPRIdx == WPREnd)
  1030. WriteProcResources.push_back(WPREntry);
  1031. }
  1032. }
  1033. WriteLatencies.push_back(WLEntry);
  1034. }
  1035. // Create an entry for each operand Read in this SchedClass.
  1036. // Entries must be sorted first by UseIdx then by WriteResourceID.
  1037. for (unsigned UseIdx = 0, EndIdx = Reads.size();
  1038. UseIdx != EndIdx; ++UseIdx) {
  1039. Record *ReadAdvance =
  1040. FindReadAdvance(SchedModels.getSchedRead(Reads[UseIdx]), ProcModel);
  1041. if (!ReadAdvance)
  1042. continue;
  1043. // Mark the parent class as invalid for unsupported write types.
  1044. if (ReadAdvance->getValueAsBit("Unsupported")) {
  1045. SCDesc.NumMicroOps = MCSchedClassDesc::InvalidNumMicroOps;
  1046. break;
  1047. }
  1048. RecVec ValidWrites = ReadAdvance->getValueAsListOfDefs("ValidWrites");
  1049. IdxVec WriteIDs;
  1050. if (ValidWrites.empty())
  1051. WriteIDs.push_back(0);
  1052. else {
  1053. for (Record *VW : ValidWrites) {
  1054. WriteIDs.push_back(SchedModels.getSchedRWIdx(VW, /*IsRead=*/false));
  1055. }
  1056. }
  1057. llvm::sort(WriteIDs);
  1058. for(unsigned W : WriteIDs) {
  1059. MCReadAdvanceEntry RAEntry;
  1060. RAEntry.UseIdx = UseIdx;
  1061. RAEntry.WriteResourceID = W;
  1062. RAEntry.Cycles = ReadAdvance->getValueAsInt("Cycles");
  1063. ReadAdvanceEntries.push_back(RAEntry);
  1064. }
  1065. }
  1066. if (SCDesc.NumMicroOps == MCSchedClassDesc::InvalidNumMicroOps) {
  1067. WriteProcResources.clear();
  1068. WriteLatencies.clear();
  1069. ReadAdvanceEntries.clear();
  1070. }
  1071. // Add the information for this SchedClass to the global tables using basic
  1072. // compression.
  1073. //
  1074. // WritePrecRes entries are sorted by ProcResIdx.
  1075. llvm::sort(WriteProcResources, LessWriteProcResources());
  1076. SCDesc.NumWriteProcResEntries = WriteProcResources.size();
  1077. std::vector<MCWriteProcResEntry>::iterator WPRPos =
  1078. std::search(SchedTables.WriteProcResources.begin(),
  1079. SchedTables.WriteProcResources.end(),
  1080. WriteProcResources.begin(), WriteProcResources.end());
  1081. if (WPRPos != SchedTables.WriteProcResources.end())
  1082. SCDesc.WriteProcResIdx = WPRPos - SchedTables.WriteProcResources.begin();
  1083. else {
  1084. SCDesc.WriteProcResIdx = SchedTables.WriteProcResources.size();
  1085. SchedTables.WriteProcResources.insert(WPRPos, WriteProcResources.begin(),
  1086. WriteProcResources.end());
  1087. }
  1088. // Latency entries must remain in operand order.
  1089. SCDesc.NumWriteLatencyEntries = WriteLatencies.size();
  1090. std::vector<MCWriteLatencyEntry>::iterator WLPos =
  1091. std::search(SchedTables.WriteLatencies.begin(),
  1092. SchedTables.WriteLatencies.end(),
  1093. WriteLatencies.begin(), WriteLatencies.end());
  1094. if (WLPos != SchedTables.WriteLatencies.end()) {
  1095. unsigned idx = WLPos - SchedTables.WriteLatencies.begin();
  1096. SCDesc.WriteLatencyIdx = idx;
  1097. for (unsigned i = 0, e = WriteLatencies.size(); i < e; ++i)
  1098. if (SchedTables.WriterNames[idx + i].find(WriterNames[i]) ==
  1099. std::string::npos) {
  1100. SchedTables.WriterNames[idx + i] += std::string("_") + WriterNames[i];
  1101. }
  1102. }
  1103. else {
  1104. SCDesc.WriteLatencyIdx = SchedTables.WriteLatencies.size();
  1105. llvm::append_range(SchedTables.WriteLatencies, WriteLatencies);
  1106. llvm::append_range(SchedTables.WriterNames, WriterNames);
  1107. }
  1108. // ReadAdvanceEntries must remain in operand order.
  1109. SCDesc.NumReadAdvanceEntries = ReadAdvanceEntries.size();
  1110. std::vector<MCReadAdvanceEntry>::iterator RAPos =
  1111. std::search(SchedTables.ReadAdvanceEntries.begin(),
  1112. SchedTables.ReadAdvanceEntries.end(),
  1113. ReadAdvanceEntries.begin(), ReadAdvanceEntries.end());
  1114. if (RAPos != SchedTables.ReadAdvanceEntries.end())
  1115. SCDesc.ReadAdvanceIdx = RAPos - SchedTables.ReadAdvanceEntries.begin();
  1116. else {
  1117. SCDesc.ReadAdvanceIdx = SchedTables.ReadAdvanceEntries.size();
  1118. llvm::append_range(SchedTables.ReadAdvanceEntries, ReadAdvanceEntries);
  1119. }
  1120. }
  1121. }
  1122. // Emit SchedClass tables for all processors and associated global tables.
  1123. void SubtargetEmitter::EmitSchedClassTables(SchedClassTables &SchedTables,
  1124. raw_ostream &OS) {
  1125. // Emit global WriteProcResTable.
  1126. OS << "\n// {ProcResourceIdx, Cycles}\n"
  1127. << "extern const llvm::MCWriteProcResEntry "
  1128. << Target << "WriteProcResTable[] = {\n"
  1129. << " { 0, 0}, // Invalid\n";
  1130. for (unsigned WPRIdx = 1, WPREnd = SchedTables.WriteProcResources.size();
  1131. WPRIdx != WPREnd; ++WPRIdx) {
  1132. MCWriteProcResEntry &WPREntry = SchedTables.WriteProcResources[WPRIdx];
  1133. OS << " {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
  1134. << format("%2d", WPREntry.Cycles) << "}";
  1135. if (WPRIdx + 1 < WPREnd)
  1136. OS << ',';
  1137. OS << " // #" << WPRIdx << '\n';
  1138. }
  1139. OS << "}; // " << Target << "WriteProcResTable\n";
  1140. // Emit global WriteLatencyTable.
  1141. OS << "\n// {Cycles, WriteResourceID}\n"
  1142. << "extern const llvm::MCWriteLatencyEntry "
  1143. << Target << "WriteLatencyTable[] = {\n"
  1144. << " { 0, 0}, // Invalid\n";
  1145. for (unsigned WLIdx = 1, WLEnd = SchedTables.WriteLatencies.size();
  1146. WLIdx != WLEnd; ++WLIdx) {
  1147. MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
  1148. OS << " {" << format("%2d", WLEntry.Cycles) << ", "
  1149. << format("%2d", WLEntry.WriteResourceID) << "}";
  1150. if (WLIdx + 1 < WLEnd)
  1151. OS << ',';
  1152. OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
  1153. }
  1154. OS << "}; // " << Target << "WriteLatencyTable\n";
  1155. // Emit global ReadAdvanceTable.
  1156. OS << "\n// {UseIdx, WriteResourceID, Cycles}\n"
  1157. << "extern const llvm::MCReadAdvanceEntry "
  1158. << Target << "ReadAdvanceTable[] = {\n"
  1159. << " {0, 0, 0}, // Invalid\n";
  1160. for (unsigned RAIdx = 1, RAEnd = SchedTables.ReadAdvanceEntries.size();
  1161. RAIdx != RAEnd; ++RAIdx) {
  1162. MCReadAdvanceEntry &RAEntry = SchedTables.ReadAdvanceEntries[RAIdx];
  1163. OS << " {" << RAEntry.UseIdx << ", "
  1164. << format("%2d", RAEntry.WriteResourceID) << ", "
  1165. << format("%2d", RAEntry.Cycles) << "}";
  1166. if (RAIdx + 1 < RAEnd)
  1167. OS << ',';
  1168. OS << " // #" << RAIdx << '\n';
  1169. }
  1170. OS << "}; // " << Target << "ReadAdvanceTable\n";
  1171. // Emit a SchedClass table for each processor.
  1172. for (CodeGenSchedModels::ProcIter PI = SchedModels.procModelBegin(),
  1173. PE = SchedModels.procModelEnd(); PI != PE; ++PI) {
  1174. if (!PI->hasInstrSchedModel())
  1175. continue;
  1176. std::vector<MCSchedClassDesc> &SCTab =
  1177. SchedTables.ProcSchedClasses[1 + (PI - SchedModels.procModelBegin())];
  1178. OS << "\n// {Name, NumMicroOps, BeginGroup, EndGroup, RetireOOO,"
  1179. << " WriteProcResIdx,#, WriteLatencyIdx,#, ReadAdvanceIdx,#}\n";
  1180. OS << "static const llvm::MCSchedClassDesc "
  1181. << PI->ModelName << "SchedClasses[] = {\n";
  1182. // The first class is always invalid. We no way to distinguish it except by
  1183. // name and position.
  1184. assert(SchedModels.getSchedClass(0).Name == "NoInstrModel"
  1185. && "invalid class not first");
  1186. OS << " {DBGFIELD(\"InvalidSchedClass\") "
  1187. << MCSchedClassDesc::InvalidNumMicroOps
  1188. << ", false, false, false, 0, 0, 0, 0, 0, 0},\n";
  1189. for (unsigned SCIdx = 1, SCEnd = SCTab.size(); SCIdx != SCEnd; ++SCIdx) {
  1190. MCSchedClassDesc &MCDesc = SCTab[SCIdx];
  1191. const CodeGenSchedClass &SchedClass = SchedModels.getSchedClass(SCIdx);
  1192. OS << " {DBGFIELD(\"" << SchedClass.Name << "\") ";
  1193. if (SchedClass.Name.size() < 18)
  1194. OS.indent(18 - SchedClass.Name.size());
  1195. OS << MCDesc.NumMicroOps
  1196. << ", " << ( MCDesc.BeginGroup ? "true" : "false" )
  1197. << ", " << ( MCDesc.EndGroup ? "true" : "false" )
  1198. << ", " << ( MCDesc.RetireOOO ? "true" : "false" )
  1199. << ", " << format("%2d", MCDesc.WriteProcResIdx)
  1200. << ", " << MCDesc.NumWriteProcResEntries
  1201. << ", " << format("%2d", MCDesc.WriteLatencyIdx)
  1202. << ", " << MCDesc.NumWriteLatencyEntries
  1203. << ", " << format("%2d", MCDesc.ReadAdvanceIdx)
  1204. << ", " << MCDesc.NumReadAdvanceEntries
  1205. << "}, // #" << SCIdx << '\n';
  1206. }
  1207. OS << "}; // " << PI->ModelName << "SchedClasses\n";
  1208. }
  1209. }
  1210. void SubtargetEmitter::EmitProcessorModels(raw_ostream &OS) {
  1211. // For each processor model.
  1212. for (const CodeGenProcModel &PM : SchedModels.procModels()) {
  1213. // Emit extra processor info if available.
  1214. if (PM.hasExtraProcessorInfo())
  1215. EmitExtraProcessorInfo(PM, OS);
  1216. // Emit processor resource table.
  1217. if (PM.hasInstrSchedModel())
  1218. EmitProcessorResources(PM, OS);
  1219. else if(!PM.ProcResourceDefs.empty())
  1220. PrintFatalError(PM.ModelDef->getLoc(), "SchedMachineModel defines "
  1221. "ProcResources without defining WriteRes SchedWriteRes");
  1222. // Begin processor itinerary properties
  1223. OS << "\n";
  1224. OS << "static const llvm::MCSchedModel " << PM.ModelName << " = {\n";
  1225. EmitProcessorProp(OS, PM.ModelDef, "IssueWidth", ',');
  1226. EmitProcessorProp(OS, PM.ModelDef, "MicroOpBufferSize", ',');
  1227. EmitProcessorProp(OS, PM.ModelDef, "LoopMicroOpBufferSize", ',');
  1228. EmitProcessorProp(OS, PM.ModelDef, "LoadLatency", ',');
  1229. EmitProcessorProp(OS, PM.ModelDef, "HighLatency", ',');
  1230. EmitProcessorProp(OS, PM.ModelDef, "MispredictPenalty", ',');
  1231. bool PostRAScheduler =
  1232. (PM.ModelDef ? PM.ModelDef->getValueAsBit("PostRAScheduler") : false);
  1233. OS << " " << (PostRAScheduler ? "true" : "false") << ", // "
  1234. << "PostRAScheduler\n";
  1235. bool CompleteModel =
  1236. (PM.ModelDef ? PM.ModelDef->getValueAsBit("CompleteModel") : false);
  1237. OS << " " << (CompleteModel ? "true" : "false") << ", // "
  1238. << "CompleteModel\n";
  1239. OS << " " << PM.Index << ", // Processor ID\n";
  1240. if (PM.hasInstrSchedModel())
  1241. OS << " " << PM.ModelName << "ProcResources" << ",\n"
  1242. << " " << PM.ModelName << "SchedClasses" << ",\n"
  1243. << " " << PM.ProcResourceDefs.size()+1 << ",\n"
  1244. << " " << (SchedModels.schedClassEnd()
  1245. - SchedModels.schedClassBegin()) << ",\n";
  1246. else
  1247. OS << " nullptr, nullptr, 0, 0,"
  1248. << " // No instruction-level machine model.\n";
  1249. if (PM.hasItineraries())
  1250. OS << " " << PM.ItinsDef->getName() << ",\n";
  1251. else
  1252. OS << " nullptr, // No Itinerary\n";
  1253. if (PM.hasExtraProcessorInfo())
  1254. OS << " &" << PM.ModelName << "ExtraInfo,\n";
  1255. else
  1256. OS << " nullptr // No extra processor descriptor\n";
  1257. OS << "};\n";
  1258. }
  1259. }
  1260. //
  1261. // EmitSchedModel - Emits all scheduling model tables, folding common patterns.
  1262. //
  1263. void SubtargetEmitter::EmitSchedModel(raw_ostream &OS) {
  1264. OS << "#ifdef DBGFIELD\n"
  1265. << "#error \"<target>GenSubtargetInfo.inc requires a DBGFIELD macro\"\n"
  1266. << "#endif\n"
  1267. << "#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)\n"
  1268. << "#define DBGFIELD(x) x,\n"
  1269. << "#else\n"
  1270. << "#define DBGFIELD(x)\n"
  1271. << "#endif\n";
  1272. if (SchedModels.hasItineraries()) {
  1273. std::vector<std::vector<InstrItinerary>> ProcItinLists;
  1274. // Emit the stage data
  1275. EmitStageAndOperandCycleData(OS, ProcItinLists);
  1276. EmitItineraries(OS, ProcItinLists);
  1277. }
  1278. OS << "\n// ===============================================================\n"
  1279. << "// Data tables for the new per-operand machine model.\n";
  1280. SchedClassTables SchedTables;
  1281. for (const CodeGenProcModel &ProcModel : SchedModels.procModels()) {
  1282. GenSchedClassTables(ProcModel, SchedTables);
  1283. }
  1284. EmitSchedClassTables(SchedTables, OS);
  1285. OS << "\n#undef DBGFIELD\n";
  1286. // Emit the processor machine model
  1287. EmitProcessorModels(OS);
  1288. }
  1289. static void emitPredicateProlog(const RecordKeeper &Records, raw_ostream &OS) {
  1290. std::string Buffer;
  1291. raw_string_ostream Stream(Buffer);
  1292. // Collect all the PredicateProlog records and print them to the output
  1293. // stream.
  1294. std::vector<Record *> Prologs =
  1295. Records.getAllDerivedDefinitions("PredicateProlog");
  1296. llvm::sort(Prologs, LessRecord());
  1297. for (Record *P : Prologs)
  1298. Stream << P->getValueAsString("Code") << '\n';
  1299. OS << Buffer;
  1300. }
  1301. static bool isTruePredicate(const Record *Rec) {
  1302. return Rec->isSubClassOf("MCSchedPredicate") &&
  1303. Rec->getValueAsDef("Pred")->isSubClassOf("MCTrue");
  1304. }
  1305. static void emitPredicates(const CodeGenSchedTransition &T,
  1306. const CodeGenSchedClass &SC, PredicateExpander &PE,
  1307. raw_ostream &OS) {
  1308. std::string Buffer;
  1309. raw_string_ostream SS(Buffer);
  1310. // If not all predicates are MCTrue, then we need an if-stmt.
  1311. unsigned NumNonTruePreds =
  1312. T.PredTerm.size() - count_if(T.PredTerm, isTruePredicate);
  1313. SS.indent(PE.getIndentLevel() * 2);
  1314. if (NumNonTruePreds) {
  1315. bool FirstNonTruePredicate = true;
  1316. SS << "if (";
  1317. PE.setIndentLevel(PE.getIndentLevel() + 2);
  1318. for (const Record *Rec : T.PredTerm) {
  1319. // Skip predicates that evaluate to "true".
  1320. if (isTruePredicate(Rec))
  1321. continue;
  1322. if (FirstNonTruePredicate) {
  1323. FirstNonTruePredicate = false;
  1324. } else {
  1325. SS << "\n";
  1326. SS.indent(PE.getIndentLevel() * 2);
  1327. SS << "&& ";
  1328. }
  1329. if (Rec->isSubClassOf("MCSchedPredicate")) {
  1330. PE.expandPredicate(SS, Rec->getValueAsDef("Pred"));
  1331. continue;
  1332. }
  1333. // Expand this legacy predicate and wrap it around braces if there is more
  1334. // than one predicate to expand.
  1335. SS << ((NumNonTruePreds > 1) ? "(" : "")
  1336. << Rec->getValueAsString("Predicate")
  1337. << ((NumNonTruePreds > 1) ? ")" : "");
  1338. }
  1339. SS << ")\n"; // end of if-stmt
  1340. PE.decreaseIndentLevel();
  1341. SS.indent(PE.getIndentLevel() * 2);
  1342. PE.decreaseIndentLevel();
  1343. }
  1344. SS << "return " << T.ToClassIdx << "; // " << SC.Name << '\n';
  1345. OS << Buffer;
  1346. }
  1347. // Used by method `SubtargetEmitter::emitSchedModelHelpersImpl()` to generate
  1348. // epilogue code for the auto-generated helper.
  1349. static void emitSchedModelHelperEpilogue(raw_ostream &OS,
  1350. bool ShouldReturnZero) {
  1351. if (ShouldReturnZero) {
  1352. OS << " // Don't know how to resolve this scheduling class.\n"
  1353. << " return 0;\n";
  1354. return;
  1355. }
  1356. OS << " report_fatal_error(\"Expected a variant SchedClass\");\n";
  1357. }
  1358. static bool hasMCSchedPredicates(const CodeGenSchedTransition &T) {
  1359. return all_of(T.PredTerm, [](const Record *Rec) {
  1360. return Rec->isSubClassOf("MCSchedPredicate");
  1361. });
  1362. }
  1363. static void collectVariantClasses(const CodeGenSchedModels &SchedModels,
  1364. IdxVec &VariantClasses,
  1365. bool OnlyExpandMCInstPredicates) {
  1366. for (const CodeGenSchedClass &SC : SchedModels.schedClasses()) {
  1367. // Ignore non-variant scheduling classes.
  1368. if (SC.Transitions.empty())
  1369. continue;
  1370. if (OnlyExpandMCInstPredicates) {
  1371. // Ignore this variant scheduling class no transitions use any meaningful
  1372. // MCSchedPredicate definitions.
  1373. if (llvm::none_of(SC.Transitions, hasMCSchedPredicates))
  1374. continue;
  1375. }
  1376. VariantClasses.push_back(SC.Index);
  1377. }
  1378. }
  1379. static void collectProcessorIndices(const CodeGenSchedClass &SC,
  1380. IdxVec &ProcIndices) {
  1381. // A variant scheduling class may define transitions for multiple
  1382. // processors. This function identifies wich processors are associated with
  1383. // transition rules specified by variant class `SC`.
  1384. for (const CodeGenSchedTransition &T : SC.Transitions) {
  1385. IdxVec PI;
  1386. std::set_union(&T.ProcIndex, &T.ProcIndex + 1, ProcIndices.begin(),
  1387. ProcIndices.end(), std::back_inserter(PI));
  1388. ProcIndices.swap(PI);
  1389. }
  1390. }
  1391. static bool isAlwaysTrue(const CodeGenSchedTransition &T) {
  1392. return llvm::all_of(T.PredTerm, isTruePredicate);
  1393. }
  1394. void SubtargetEmitter::emitSchedModelHelpersImpl(
  1395. raw_ostream &OS, bool OnlyExpandMCInstPredicates) {
  1396. IdxVec VariantClasses;
  1397. collectVariantClasses(SchedModels, VariantClasses,
  1398. OnlyExpandMCInstPredicates);
  1399. if (VariantClasses.empty()) {
  1400. emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates);
  1401. return;
  1402. }
  1403. // Construct a switch statement where the condition is a check on the
  1404. // scheduling class identifier. There is a `case` for every variant class
  1405. // defined by the processor models of this target.
  1406. // Each `case` implements a number of rules to resolve (i.e. to transition from)
  1407. // a variant scheduling class to another scheduling class. Rules are
  1408. // described by instances of CodeGenSchedTransition. Note that transitions may
  1409. // not be valid for all processors.
  1410. OS << " switch (SchedClass) {\n";
  1411. for (unsigned VC : VariantClasses) {
  1412. IdxVec ProcIndices;
  1413. const CodeGenSchedClass &SC = SchedModels.getSchedClass(VC);
  1414. collectProcessorIndices(SC, ProcIndices);
  1415. OS << " case " << VC << ": // " << SC.Name << '\n';
  1416. PredicateExpander PE(Target);
  1417. PE.setByRef(false);
  1418. PE.setExpandForMC(OnlyExpandMCInstPredicates);
  1419. for (unsigned PI : ProcIndices) {
  1420. OS << " ";
  1421. // Emit a guard on the processor ID.
  1422. if (PI != 0) {
  1423. OS << (OnlyExpandMCInstPredicates
  1424. ? "if (CPUID == "
  1425. : "if (SchedModel->getProcessorID() == ");
  1426. OS << PI << ") ";
  1427. OS << "{ // " << (SchedModels.procModelBegin() + PI)->ModelName << '\n';
  1428. }
  1429. // Now emit transitions associated with processor PI.
  1430. const CodeGenSchedTransition *FinalT = nullptr;
  1431. for (const CodeGenSchedTransition &T : SC.Transitions) {
  1432. if (PI != 0 && T.ProcIndex != PI)
  1433. continue;
  1434. // Emit only transitions based on MCSchedPredicate, if it's the case.
  1435. // At least the transition specified by NoSchedPred is emitted,
  1436. // which becomes the default transition for those variants otherwise
  1437. // not based on MCSchedPredicate.
  1438. // FIXME: preferably, llvm-mca should instead assume a reasonable
  1439. // default when a variant transition is not based on MCSchedPredicate
  1440. // for a given processor.
  1441. if (OnlyExpandMCInstPredicates && !hasMCSchedPredicates(T))
  1442. continue;
  1443. // If transition is folded to 'return X' it should be the last one.
  1444. if (isAlwaysTrue(T)) {
  1445. FinalT = &T;
  1446. continue;
  1447. }
  1448. PE.setIndentLevel(3);
  1449. emitPredicates(T, SchedModels.getSchedClass(T.ToClassIdx), PE, OS);
  1450. }
  1451. if (FinalT)
  1452. emitPredicates(*FinalT, SchedModels.getSchedClass(FinalT->ToClassIdx),
  1453. PE, OS);
  1454. OS << " }\n";
  1455. if (PI == 0)
  1456. break;
  1457. }
  1458. if (SC.isInferred())
  1459. OS << " return " << SC.Index << ";\n";
  1460. OS << " break;\n";
  1461. }
  1462. OS << " };\n";
  1463. emitSchedModelHelperEpilogue(OS, OnlyExpandMCInstPredicates);
  1464. }
  1465. void SubtargetEmitter::EmitSchedModelHelpers(const std::string &ClassName,
  1466. raw_ostream &OS) {
  1467. OS << "unsigned " << ClassName
  1468. << "\n::resolveSchedClass(unsigned SchedClass, const MachineInstr *MI,"
  1469. << " const TargetSchedModel *SchedModel) const {\n";
  1470. // Emit the predicate prolog code.
  1471. emitPredicateProlog(Records, OS);
  1472. // Emit target predicates.
  1473. emitSchedModelHelpersImpl(OS);
  1474. OS << "} // " << ClassName << "::resolveSchedClass\n\n";
  1475. OS << "unsigned " << ClassName
  1476. << "\n::resolveVariantSchedClass(unsigned SchedClass, const MCInst *MI,"
  1477. << " const MCInstrInfo *MCII, unsigned CPUID) const {\n"
  1478. << " return " << Target << "_MC"
  1479. << "::resolveVariantSchedClassImpl(SchedClass, MI, MCII, CPUID);\n"
  1480. << "} // " << ClassName << "::resolveVariantSchedClass\n\n";
  1481. STIPredicateExpander PE(Target);
  1482. PE.setClassPrefix(ClassName);
  1483. PE.setExpandDefinition(true);
  1484. PE.setByRef(false);
  1485. PE.setIndentLevel(0);
  1486. for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates())
  1487. PE.expandSTIPredicate(OS, Fn);
  1488. }
  1489. void SubtargetEmitter::EmitHwModeCheck(const std::string &ClassName,
  1490. raw_ostream &OS) {
  1491. const CodeGenHwModes &CGH = TGT.getHwModes();
  1492. assert(CGH.getNumModeIds() > 0);
  1493. if (CGH.getNumModeIds() == 1)
  1494. return;
  1495. OS << "unsigned " << ClassName << "::getHwMode() const {\n";
  1496. for (unsigned M = 1, NumModes = CGH.getNumModeIds(); M != NumModes; ++M) {
  1497. const HwMode &HM = CGH.getMode(M);
  1498. OS << " if (checkFeatures(\"" << HM.Features
  1499. << "\")) return " << M << ";\n";
  1500. }
  1501. OS << " return 0;\n}\n";
  1502. }
  1503. // Produces a subtarget specific function for parsing
  1504. // the subtarget features string.
  1505. void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS) {
  1506. std::vector<Record*> Features =
  1507. Records.getAllDerivedDefinitions("SubtargetFeature");
  1508. llvm::sort(Features, LessRecord());
  1509. OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
  1510. << "// subtarget options.\n"
  1511. << "void llvm::";
  1512. OS << Target;
  1513. OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef TuneCPU, "
  1514. << "StringRef FS) {\n"
  1515. << " LLVM_DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
  1516. << " LLVM_DEBUG(dbgs() << \"\\nCPU:\" << CPU);\n"
  1517. << " LLVM_DEBUG(dbgs() << \"\\nTuneCPU:\" << TuneCPU << \"\\n\\n\");\n";
  1518. if (Features.empty()) {
  1519. OS << "}\n";
  1520. return;
  1521. }
  1522. OS << " InitMCProcessorInfo(CPU, TuneCPU, FS);\n"
  1523. << " const FeatureBitset &Bits = getFeatureBits();\n";
  1524. for (Record *R : Features) {
  1525. // Next record
  1526. StringRef Instance = R->getName();
  1527. StringRef Value = R->getValueAsString("Value");
  1528. StringRef Attribute = R->getValueAsString("Attribute");
  1529. if (Value=="true" || Value=="false")
  1530. OS << " if (Bits[" << Target << "::"
  1531. << Instance << "]) "
  1532. << Attribute << " = " << Value << ";\n";
  1533. else
  1534. OS << " if (Bits[" << Target << "::"
  1535. << Instance << "] && "
  1536. << Attribute << " < " << Value << ") "
  1537. << Attribute << " = " << Value << ";\n";
  1538. }
  1539. OS << "}\n";
  1540. }
  1541. void SubtargetEmitter::emitGenMCSubtargetInfo(raw_ostream &OS) {
  1542. OS << "namespace " << Target << "_MC {\n"
  1543. << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass,\n"
  1544. << " const MCInst *MI, const MCInstrInfo *MCII, unsigned CPUID) {\n";
  1545. emitSchedModelHelpersImpl(OS, /* OnlyExpandMCPredicates */ true);
  1546. OS << "}\n";
  1547. OS << "} // end namespace " << Target << "_MC\n\n";
  1548. OS << "struct " << Target
  1549. << "GenMCSubtargetInfo : public MCSubtargetInfo {\n";
  1550. OS << " " << Target << "GenMCSubtargetInfo(const Triple &TT,\n"
  1551. << " StringRef CPU, StringRef TuneCPU, StringRef FS,\n"
  1552. << " ArrayRef<SubtargetFeatureKV> PF,\n"
  1553. << " ArrayRef<SubtargetSubTypeKV> PD,\n"
  1554. << " const MCWriteProcResEntry *WPR,\n"
  1555. << " const MCWriteLatencyEntry *WL,\n"
  1556. << " const MCReadAdvanceEntry *RA, const InstrStage *IS,\n"
  1557. << " const unsigned *OC, const unsigned *FP) :\n"
  1558. << " MCSubtargetInfo(TT, CPU, TuneCPU, FS, PF, PD,\n"
  1559. << " WPR, WL, RA, IS, OC, FP) { }\n\n"
  1560. << " unsigned resolveVariantSchedClass(unsigned SchedClass,\n"
  1561. << " const MCInst *MI, const MCInstrInfo *MCII,\n"
  1562. << " unsigned CPUID) const override {\n"
  1563. << " return " << Target << "_MC"
  1564. << "::resolveVariantSchedClassImpl(SchedClass, MI, MCII, CPUID);\n";
  1565. OS << " }\n";
  1566. if (TGT.getHwModes().getNumModeIds() > 1)
  1567. OS << " unsigned getHwMode() const override;\n";
  1568. OS << "};\n";
  1569. EmitHwModeCheck(Target + "GenMCSubtargetInfo", OS);
  1570. }
  1571. void SubtargetEmitter::EmitMCInstrAnalysisPredicateFunctions(raw_ostream &OS) {
  1572. OS << "\n#ifdef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n";
  1573. OS << "#undef GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n";
  1574. STIPredicateExpander PE(Target);
  1575. PE.setExpandForMC(true);
  1576. PE.setByRef(true);
  1577. for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates())
  1578. PE.expandSTIPredicate(OS, Fn);
  1579. OS << "#endif // GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS\n\n";
  1580. OS << "\n#ifdef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n";
  1581. OS << "#undef GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n";
  1582. std::string ClassPrefix = Target + "MCInstrAnalysis";
  1583. PE.setExpandDefinition(true);
  1584. PE.setClassPrefix(ClassPrefix);
  1585. PE.setIndentLevel(0);
  1586. for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates())
  1587. PE.expandSTIPredicate(OS, Fn);
  1588. OS << "#endif // GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS\n\n";
  1589. }
  1590. //
  1591. // SubtargetEmitter::run - Main subtarget enumeration emitter.
  1592. //
  1593. void SubtargetEmitter::run(raw_ostream &OS) {
  1594. emitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);
  1595. OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
  1596. OS << "#undef GET_SUBTARGETINFO_ENUM\n\n";
  1597. DenseMap<Record *, unsigned> FeatureMap;
  1598. OS << "namespace llvm {\n";
  1599. Enumeration(OS, FeatureMap);
  1600. OS << "} // end namespace llvm\n\n";
  1601. OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";
  1602. EmitSubtargetInfoMacroCalls(OS);
  1603. OS << "namespace llvm {\n";
  1604. #if 0
  1605. OS << "namespace {\n";
  1606. #endif
  1607. unsigned NumFeatures = FeatureKeyValues(OS, FeatureMap);
  1608. OS << "\n";
  1609. EmitSchedModel(OS);
  1610. OS << "\n";
  1611. unsigned NumProcs = CPUKeyValues(OS, FeatureMap);
  1612. OS << "\n";
  1613. #if 0
  1614. OS << "} // end anonymous namespace\n\n";
  1615. #endif
  1616. // MCInstrInfo initialization routine.
  1617. emitGenMCSubtargetInfo(OS);
  1618. OS << "\nstatic inline MCSubtargetInfo *create" << Target
  1619. << "MCSubtargetInfoImpl("
  1620. << "const Triple &TT, StringRef CPU, StringRef TuneCPU, StringRef FS) {\n";
  1621. OS << " return new " << Target
  1622. << "GenMCSubtargetInfo(TT, CPU, TuneCPU, FS, ";
  1623. if (NumFeatures)
  1624. OS << Target << "FeatureKV, ";
  1625. else
  1626. OS << "std::nullopt, ";
  1627. if (NumProcs)
  1628. OS << Target << "SubTypeKV, ";
  1629. else
  1630. OS << "None, ";
  1631. OS << '\n'; OS.indent(22);
  1632. OS << Target << "WriteProcResTable, "
  1633. << Target << "WriteLatencyTable, "
  1634. << Target << "ReadAdvanceTable, ";
  1635. OS << '\n'; OS.indent(22);
  1636. if (SchedModels.hasItineraries()) {
  1637. OS << Target << "Stages, "
  1638. << Target << "OperandCycles, "
  1639. << Target << "ForwardingPaths";
  1640. } else
  1641. OS << "nullptr, nullptr, nullptr";
  1642. OS << ");\n}\n\n";
  1643. OS << "} // end namespace llvm\n\n";
  1644. OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";
  1645. OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
  1646. OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n\n";
  1647. OS << "#include \"llvm/Support/Debug.h\"\n";
  1648. OS << "#include \"llvm/Support/raw_ostream.h\"\n\n";
  1649. ParseFeaturesFunction(OS);
  1650. OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";
  1651. // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
  1652. OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
  1653. OS << "#undef GET_SUBTARGETINFO_HEADER\n\n";
  1654. std::string ClassName = Target + "GenSubtargetInfo";
  1655. OS << "namespace llvm {\n";
  1656. OS << "class DFAPacketizer;\n";
  1657. OS << "namespace " << Target << "_MC {\n"
  1658. << "unsigned resolveVariantSchedClassImpl(unsigned SchedClass,"
  1659. << " const MCInst *MI, const MCInstrInfo *MCII, unsigned CPUID);\n"
  1660. << "} // end namespace " << Target << "_MC\n\n";
  1661. OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
  1662. << " explicit " << ClassName << "(const Triple &TT, StringRef CPU, "
  1663. << "StringRef TuneCPU, StringRef FS);\n"
  1664. << "public:\n"
  1665. << " unsigned resolveSchedClass(unsigned SchedClass, "
  1666. << " const MachineInstr *DefMI,"
  1667. << " const TargetSchedModel *SchedModel) const override;\n"
  1668. << " unsigned resolveVariantSchedClass(unsigned SchedClass,"
  1669. << " const MCInst *MI, const MCInstrInfo *MCII,"
  1670. << " unsigned CPUID) const override;\n"
  1671. << " DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
  1672. << " const;\n";
  1673. if (TGT.getHwModes().getNumModeIds() > 1)
  1674. OS << " unsigned getHwMode() const override;\n";
  1675. STIPredicateExpander PE(Target);
  1676. PE.setByRef(false);
  1677. for (const STIPredicateFunction &Fn : SchedModels.getSTIPredicates())
  1678. PE.expandSTIPredicate(OS, Fn);
  1679. OS << "};\n"
  1680. << "} // end namespace llvm\n\n";
  1681. OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";
  1682. OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
  1683. OS << "#undef GET_SUBTARGETINFO_CTOR\n\n";
  1684. OS << "#include \"llvm/CodeGen/TargetSchedule.h\"\n\n";
  1685. OS << "namespace llvm {\n";
  1686. OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
  1687. OS << "extern const llvm::SubtargetSubTypeKV " << Target << "SubTypeKV[];\n";
  1688. OS << "extern const llvm::MCWriteProcResEntry "
  1689. << Target << "WriteProcResTable[];\n";
  1690. OS << "extern const llvm::MCWriteLatencyEntry "
  1691. << Target << "WriteLatencyTable[];\n";
  1692. OS << "extern const llvm::MCReadAdvanceEntry "
  1693. << Target << "ReadAdvanceTable[];\n";
  1694. if (SchedModels.hasItineraries()) {
  1695. OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
  1696. OS << "extern const unsigned " << Target << "OperandCycles[];\n";
  1697. OS << "extern const unsigned " << Target << "ForwardingPaths[];\n";
  1698. }
  1699. OS << ClassName << "::" << ClassName << "(const Triple &TT, StringRef CPU, "
  1700. << "StringRef TuneCPU, StringRef FS)\n"
  1701. << " : TargetSubtargetInfo(TT, CPU, TuneCPU, FS, ";
  1702. if (NumFeatures)
  1703. OS << "ArrayRef(" << Target << "FeatureKV, " << NumFeatures << "), ";
  1704. else
  1705. OS << "std::nullopt, ";
  1706. if (NumProcs)
  1707. OS << "ArrayRef(" << Target << "SubTypeKV, " << NumProcs << "), ";
  1708. else
  1709. OS << "None, ";
  1710. OS << '\n'; OS.indent(24);
  1711. OS << Target << "WriteProcResTable, "
  1712. << Target << "WriteLatencyTable, "
  1713. << Target << "ReadAdvanceTable, ";
  1714. OS << '\n'; OS.indent(24);
  1715. if (SchedModels.hasItineraries()) {
  1716. OS << Target << "Stages, "
  1717. << Target << "OperandCycles, "
  1718. << Target << "ForwardingPaths";
  1719. } else
  1720. OS << "nullptr, nullptr, nullptr";
  1721. OS << ") {}\n\n";
  1722. EmitSchedModelHelpers(ClassName, OS);
  1723. EmitHwModeCheck(ClassName, OS);
  1724. OS << "} // end namespace llvm\n\n";
  1725. OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
  1726. EmitMCInstrAnalysisPredicateFunctions(OS);
  1727. }
  1728. namespace llvm {
  1729. void EmitSubtarget(RecordKeeper &RK, raw_ostream &OS) {
  1730. CodeGenTarget CGTarget(RK);
  1731. SubtargetEmitter(RK, CGTarget).run(OS);
  1732. }
  1733. } // end namespace llvm