InstrInfoEmitter.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. --*- C++ -*-===//
  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 is responsible for emitting a description of the target
  10. // instruction set for the code generator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenDAGPatterns.h"
  14. #include "CodeGenInstruction.h"
  15. #include "CodeGenSchedule.h"
  16. #include "CodeGenTarget.h"
  17. #include "PredicateExpander.h"
  18. #include "SequenceToOffsetTable.h"
  19. #include "SubtargetFeatureInfo.h"
  20. #include "TableGenBackends.h"
  21. #include "Types.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/TableGen/Error.h"
  28. #include "llvm/TableGen/Record.h"
  29. #include "llvm/TableGen/TableGenBackend.h"
  30. #include <cassert>
  31. #include <cstdint>
  32. #include <iterator>
  33. #include <map>
  34. #include <string>
  35. #include <utility>
  36. #include <vector>
  37. using namespace llvm;
  38. cl::OptionCategory InstrInfoEmitterCat("Options for -gen-instr-info");
  39. static cl::opt<bool> ExpandMIOperandInfo(
  40. "instr-info-expand-mi-operand-info",
  41. cl::desc("Expand operand's MIOperandInfo DAG into suboperands"),
  42. cl::cat(InstrInfoEmitterCat), cl::init(true));
  43. namespace {
  44. class InstrInfoEmitter {
  45. RecordKeeper &Records;
  46. CodeGenDAGPatterns CDP;
  47. const CodeGenSchedModels &SchedModels;
  48. public:
  49. InstrInfoEmitter(RecordKeeper &R):
  50. Records(R), CDP(R), SchedModels(CDP.getTargetInfo().getSchedModels()) {}
  51. // run - Output the instruction set description.
  52. void run(raw_ostream &OS);
  53. private:
  54. void emitEnums(raw_ostream &OS);
  55. typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
  56. /// The keys of this map are maps which have OpName enum values as their keys
  57. /// and instruction operand indices as their values. The values of this map
  58. /// are lists of instruction names.
  59. typedef std::map<std::map<unsigned, unsigned>,
  60. std::vector<std::string>> OpNameMapTy;
  61. typedef std::map<std::string, unsigned>::iterator StrUintMapIter;
  62. /// Generate member functions in the target-specific GenInstrInfo class.
  63. ///
  64. /// This method is used to custom expand TIIPredicate definitions.
  65. /// See file llvm/Target/TargetInstPredicates.td for a description of what is
  66. /// a TIIPredicate and how to use it.
  67. void emitTIIHelperMethods(raw_ostream &OS, StringRef TargetName,
  68. bool ExpandDefinition = true);
  69. /// Expand TIIPredicate definitions to functions that accept a const MCInst
  70. /// reference.
  71. void emitMCIIHelperMethods(raw_ostream &OS, StringRef TargetName);
  72. /// Write verifyInstructionPredicates methods.
  73. void emitFeatureVerifier(raw_ostream &OS, const CodeGenTarget &Target);
  74. void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
  75. Record *InstrInfo,
  76. std::map<std::vector<Record*>, unsigned> &EL,
  77. const OperandInfoMapTy &OpInfo,
  78. raw_ostream &OS);
  79. void emitOperandTypeMappings(
  80. raw_ostream &OS, const CodeGenTarget &Target,
  81. ArrayRef<const CodeGenInstruction *> NumberedInstructions);
  82. void initOperandMapData(
  83. ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  84. StringRef Namespace,
  85. std::map<std::string, unsigned> &Operands,
  86. OpNameMapTy &OperandMap);
  87. void emitOperandNameMappings(raw_ostream &OS, const CodeGenTarget &Target,
  88. ArrayRef<const CodeGenInstruction*> NumberedInstructions);
  89. void emitLogicalOperandSizeMappings(
  90. raw_ostream &OS, StringRef Namespace,
  91. ArrayRef<const CodeGenInstruction *> NumberedInstructions);
  92. void emitLogicalOperandTypeMappings(
  93. raw_ostream &OS, StringRef Namespace,
  94. ArrayRef<const CodeGenInstruction *> NumberedInstructions);
  95. // Operand information.
  96. void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
  97. std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
  98. };
  99. } // end anonymous namespace
  100. static void PrintDefList(const std::vector<Record*> &Uses,
  101. unsigned Num, raw_ostream &OS) {
  102. OS << "static const MCPhysReg ImplicitList" << Num << "[] = { ";
  103. for (auto [Idx, U] : enumerate(Uses))
  104. OS << (Idx ? ", " : "") << getQualifiedName(U);
  105. OS << " };\n";
  106. }
  107. //===----------------------------------------------------------------------===//
  108. // Operand Info Emission.
  109. //===----------------------------------------------------------------------===//
  110. std::vector<std::string>
  111. InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
  112. std::vector<std::string> Result;
  113. for (auto &Op : Inst.Operands) {
  114. // Handle aggregate operands and normal operands the same way by expanding
  115. // either case into a list of operands for this op.
  116. std::vector<CGIOperandList::OperandInfo> OperandList;
  117. // This might be a multiple operand thing. Targets like X86 have
  118. // registers in their multi-operand operands. It may also be an anonymous
  119. // operand, which has a single operand, but no declared class for the
  120. // operand.
  121. DagInit *MIOI = Op.MIOperandInfo;
  122. if (!MIOI || MIOI->getNumArgs() == 0) {
  123. // Single, anonymous, operand.
  124. OperandList.push_back(Op);
  125. } else {
  126. for (unsigned j = 0, e = Op.MINumOperands; j != e; ++j) {
  127. OperandList.push_back(Op);
  128. auto *OpR = cast<DefInit>(MIOI->getArg(j))->getDef();
  129. OperandList.back().Rec = OpR;
  130. }
  131. }
  132. for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
  133. Record *OpR = OperandList[j].Rec;
  134. std::string Res;
  135. if (OpR->isSubClassOf("RegisterOperand"))
  136. OpR = OpR->getValueAsDef("RegClass");
  137. if (OpR->isSubClassOf("RegisterClass"))
  138. Res += getQualifiedName(OpR) + "RegClassID, ";
  139. else if (OpR->isSubClassOf("PointerLikeRegClass"))
  140. Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
  141. else
  142. // -1 means the operand does not have a fixed register class.
  143. Res += "-1, ";
  144. // Fill in applicable flags.
  145. Res += "0";
  146. // Ptr value whose register class is resolved via callback.
  147. if (OpR->isSubClassOf("PointerLikeRegClass"))
  148. Res += "|(1<<MCOI::LookupPtrRegClass)";
  149. // Predicate operands. Check to see if the original unexpanded operand
  150. // was of type PredicateOp.
  151. if (Op.Rec->isSubClassOf("PredicateOp"))
  152. Res += "|(1<<MCOI::Predicate)";
  153. // Optional def operands. Check to see if the original unexpanded operand
  154. // was of type OptionalDefOperand.
  155. if (Op.Rec->isSubClassOf("OptionalDefOperand"))
  156. Res += "|(1<<MCOI::OptionalDef)";
  157. // Branch target operands. Check to see if the original unexpanded
  158. // operand was of type BranchTargetOperand.
  159. if (Op.Rec->isSubClassOf("BranchTargetOperand"))
  160. Res += "|(1<<MCOI::BranchTarget)";
  161. // Fill in operand type.
  162. Res += ", ";
  163. assert(!Op.OperandType.empty() && "Invalid operand type.");
  164. Res += Op.OperandType;
  165. // Fill in constraint info.
  166. Res += ", ";
  167. const CGIOperandList::ConstraintInfo &Constraint =
  168. Op.Constraints[j];
  169. if (Constraint.isNone())
  170. Res += "0";
  171. else if (Constraint.isEarlyClobber())
  172. Res += "MCOI_EARLY_CLOBBER";
  173. else {
  174. assert(Constraint.isTied());
  175. Res += "MCOI_TIED_TO(" + utostr(Constraint.getTiedOperand()) + ")";
  176. }
  177. Result.push_back(Res);
  178. }
  179. }
  180. return Result;
  181. }
  182. void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
  183. OperandInfoMapTy &OperandInfoIDs) {
  184. // ID #0 is for no operand info.
  185. unsigned OperandListNum = 0;
  186. OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
  187. OS << "\n";
  188. const CodeGenTarget &Target = CDP.getTargetInfo();
  189. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  190. std::vector<std::string> OperandInfo = GetOperandInfo(*Inst);
  191. unsigned &N = OperandInfoIDs[OperandInfo];
  192. if (N != 0) continue;
  193. N = ++OperandListNum;
  194. OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
  195. for (const std::string &Info : OperandInfo)
  196. OS << "{ " << Info << " }, ";
  197. OS << "};\n";
  198. }
  199. }
  200. /// Initialize data structures for generating operand name mappings.
  201. ///
  202. /// \param Operands [out] A map used to generate the OpName enum with operand
  203. /// names as its keys and operand enum values as its values.
  204. /// \param OperandMap [out] A map for representing the operand name mappings for
  205. /// each instructions. This is used to generate the OperandMap table as
  206. /// well as the getNamedOperandIdx() function.
  207. void InstrInfoEmitter::initOperandMapData(
  208. ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  209. StringRef Namespace,
  210. std::map<std::string, unsigned> &Operands,
  211. OpNameMapTy &OperandMap) {
  212. unsigned NumOperands = 0;
  213. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  214. if (!Inst->TheDef->getValueAsBit("UseNamedOperandTable"))
  215. continue;
  216. std::map<unsigned, unsigned> OpList;
  217. for (const auto &Info : Inst->Operands) {
  218. StrUintMapIter I = Operands.find(Info.Name);
  219. if (I == Operands.end()) {
  220. I = Operands.insert(Operands.begin(),
  221. std::pair<std::string, unsigned>(Info.Name, NumOperands++));
  222. }
  223. OpList[I->second] = Info.MIOperandNo;
  224. }
  225. OperandMap[OpList].push_back(Namespace.str() + "::" +
  226. Inst->TheDef->getName().str());
  227. }
  228. }
  229. /// Generate a table and function for looking up the indices of operands by
  230. /// name.
  231. ///
  232. /// This code generates:
  233. /// - An enum in the llvm::TargetNamespace::OpName namespace, with one entry
  234. /// for each operand name.
  235. /// - A 2-dimensional table called OperandMap for mapping OpName enum values to
  236. /// operand indices.
  237. /// - A function called getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
  238. /// for looking up the operand index for an instruction, given a value from
  239. /// OpName enum
  240. void InstrInfoEmitter::emitOperandNameMappings(raw_ostream &OS,
  241. const CodeGenTarget &Target,
  242. ArrayRef<const CodeGenInstruction*> NumberedInstructions) {
  243. StringRef Namespace = Target.getInstNamespace();
  244. std::string OpNameNS = "OpName";
  245. // Map of operand names to their enumeration value. This will be used to
  246. // generate the OpName enum.
  247. std::map<std::string, unsigned> Operands;
  248. OpNameMapTy OperandMap;
  249. initOperandMapData(NumberedInstructions, Namespace, Operands, OperandMap);
  250. OS << "#ifdef GET_INSTRINFO_OPERAND_ENUM\n";
  251. OS << "#undef GET_INSTRINFO_OPERAND_ENUM\n";
  252. OS << "namespace llvm {\n";
  253. OS << "namespace " << Namespace << " {\n";
  254. OS << "namespace " << OpNameNS << " {\n";
  255. OS << "enum {\n";
  256. for (const auto &Op : Operands)
  257. OS << " " << Op.first << " = " << Op.second << ",\n";
  258. OS << " OPERAND_LAST";
  259. OS << "\n};\n";
  260. OS << "} // end namespace OpName\n";
  261. OS << "} // end namespace " << Namespace << "\n";
  262. OS << "} // end namespace llvm\n";
  263. OS << "#endif //GET_INSTRINFO_OPERAND_ENUM\n\n";
  264. OS << "#ifdef GET_INSTRINFO_NAMED_OPS\n";
  265. OS << "#undef GET_INSTRINFO_NAMED_OPS\n";
  266. OS << "namespace llvm {\n";
  267. OS << "namespace " << Namespace << " {\n";
  268. OS << "LLVM_READONLY\n";
  269. OS << "int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx) {\n";
  270. if (!Operands.empty()) {
  271. OS << " static const int16_t OperandMap [][" << Operands.size()
  272. << "] = {\n";
  273. for (const auto &Entry : OperandMap) {
  274. const std::map<unsigned, unsigned> &OpList = Entry.first;
  275. OS << "{";
  276. // Emit a row of the OperandMap table
  277. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  278. OS << (OpList.count(i) == 0 ? -1 : (int)OpList.find(i)->second) << ", ";
  279. OS << "},\n";
  280. }
  281. OS << "};\n";
  282. OS << " switch(Opcode) {\n";
  283. unsigned TableIndex = 0;
  284. for (const auto &Entry : OperandMap) {
  285. for (const std::string &Name : Entry.second)
  286. OS << " case " << Name << ":\n";
  287. OS << " return OperandMap[" << TableIndex++ << "][NamedIdx];\n";
  288. }
  289. OS << " default: return -1;\n";
  290. OS << " }\n";
  291. } else {
  292. // There are no operands, so no need to emit anything
  293. OS << " return -1;\n";
  294. }
  295. OS << "}\n";
  296. OS << "} // end namespace " << Namespace << "\n";
  297. OS << "} // end namespace llvm\n";
  298. OS << "#endif //GET_INSTRINFO_NAMED_OPS\n\n";
  299. }
  300. /// Generate an enum for all the operand types for this target, under the
  301. /// llvm::TargetNamespace::OpTypes namespace.
  302. /// Operand types are all definitions derived of the Operand Target.td class.
  303. void InstrInfoEmitter::emitOperandTypeMappings(
  304. raw_ostream &OS, const CodeGenTarget &Target,
  305. ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
  306. StringRef Namespace = Target.getInstNamespace();
  307. std::vector<Record *> Operands = Records.getAllDerivedDefinitions("Operand");
  308. std::vector<Record *> RegisterOperands =
  309. Records.getAllDerivedDefinitions("RegisterOperand");
  310. std::vector<Record *> RegisterClasses =
  311. Records.getAllDerivedDefinitions("RegisterClass");
  312. OS << "#ifdef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  313. OS << "#undef GET_INSTRINFO_OPERAND_TYPES_ENUM\n";
  314. OS << "namespace llvm {\n";
  315. OS << "namespace " << Namespace << " {\n";
  316. OS << "namespace OpTypes {\n";
  317. OS << "enum OperandType {\n";
  318. unsigned EnumVal = 0;
  319. for (const std::vector<Record *> *RecordsToAdd :
  320. {&Operands, &RegisterOperands, &RegisterClasses}) {
  321. for (const Record *Op : *RecordsToAdd) {
  322. if (!Op->isAnonymous())
  323. OS << " " << Op->getName() << " = " << EnumVal << ",\n";
  324. ++EnumVal;
  325. }
  326. }
  327. OS << " OPERAND_TYPE_LIST_END" << "\n};\n";
  328. OS << "} // end namespace OpTypes\n";
  329. OS << "} // end namespace " << Namespace << "\n";
  330. OS << "} // end namespace llvm\n";
  331. OS << "#endif // GET_INSTRINFO_OPERAND_TYPES_ENUM\n\n";
  332. OS << "#ifdef GET_INSTRINFO_OPERAND_TYPE\n";
  333. OS << "#undef GET_INSTRINFO_OPERAND_TYPE\n";
  334. OS << "namespace llvm {\n";
  335. OS << "namespace " << Namespace << " {\n";
  336. OS << "LLVM_READONLY\n";
  337. OS << "static int getOperandType(uint16_t Opcode, uint16_t OpIdx) {\n";
  338. auto getInstrName = [&](int I) -> StringRef {
  339. return NumberedInstructions[I]->TheDef->getName();
  340. };
  341. // TODO: Factor out duplicate operand lists to compress the tables.
  342. if (!NumberedInstructions.empty()) {
  343. std::vector<int> OperandOffsets;
  344. std::vector<Record *> OperandRecords;
  345. int CurrentOffset = 0;
  346. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  347. OperandOffsets.push_back(CurrentOffset);
  348. for (const auto &Op : Inst->Operands) {
  349. const DagInit *MIOI = Op.MIOperandInfo;
  350. if (!ExpandMIOperandInfo || !MIOI || MIOI->getNumArgs() == 0) {
  351. // Single, anonymous, operand.
  352. OperandRecords.push_back(Op.Rec);
  353. ++CurrentOffset;
  354. } else {
  355. for (Init *Arg : MIOI->getArgs()) {
  356. OperandRecords.push_back(cast<DefInit>(Arg)->getDef());
  357. ++CurrentOffset;
  358. }
  359. }
  360. }
  361. }
  362. // Emit the table of offsets (indexes) into the operand type table.
  363. // Size the unsigned integer offset to save space.
  364. assert(OperandRecords.size() <= UINT32_MAX &&
  365. "Too many operands for offset table");
  366. OS << ((OperandRecords.size() <= UINT16_MAX) ? " const uint16_t"
  367. : " const uint32_t");
  368. OS << " Offsets[] = {\n";
  369. for (int I = 0, E = OperandOffsets.size(); I != E; ++I) {
  370. OS << " /* " << getInstrName(I) << " */\n";
  371. OS << " " << OperandOffsets[I] << ",\n";
  372. }
  373. OS << " };\n";
  374. // Add an entry for the end so that we don't need to special case it below.
  375. OperandOffsets.push_back(OperandRecords.size());
  376. // Emit the actual operand types in a flat table.
  377. // Size the signed integer operand type to save space.
  378. assert(EnumVal <= INT16_MAX &&
  379. "Too many operand types for operand types table");
  380. OS << "\n using namespace OpTypes;\n";
  381. OS << ((EnumVal <= INT8_MAX) ? " const int8_t" : " const int16_t");
  382. OS << " OpcodeOperandTypes[] = {\n ";
  383. for (int I = 0, E = OperandRecords.size(), CurOffset = 0; I != E; ++I) {
  384. // We print each Opcode's operands in its own row.
  385. if (I == OperandOffsets[CurOffset]) {
  386. OS << "\n /* " << getInstrName(CurOffset) << " */\n ";
  387. while (OperandOffsets[++CurOffset] == I)
  388. OS << "/* " << getInstrName(CurOffset) << " */\n ";
  389. }
  390. Record *OpR = OperandRecords[I];
  391. if ((OpR->isSubClassOf("Operand") ||
  392. OpR->isSubClassOf("RegisterOperand") ||
  393. OpR->isSubClassOf("RegisterClass")) &&
  394. !OpR->isAnonymous())
  395. OS << OpR->getName();
  396. else
  397. OS << -1;
  398. OS << ", ";
  399. }
  400. OS << "\n };\n";
  401. OS << " return OpcodeOperandTypes[Offsets[Opcode] + OpIdx];\n";
  402. } else {
  403. OS << " llvm_unreachable(\"No instructions defined\");\n";
  404. }
  405. OS << "}\n";
  406. OS << "} // end namespace " << Namespace << "\n";
  407. OS << "} // end namespace llvm\n";
  408. OS << "#endif // GET_INSTRINFO_OPERAND_TYPE\n\n";
  409. OS << "#ifdef GET_INSTRINFO_MEM_OPERAND_SIZE\n";
  410. OS << "#undef GET_INSTRINFO_MEM_OPERAND_SIZE\n";
  411. OS << "namespace llvm {\n";
  412. OS << "namespace " << Namespace << " {\n";
  413. OS << "LLVM_READONLY\n";
  414. OS << "static int getMemOperandSize(int OpType) {\n";
  415. OS << " switch (OpType) {\n";
  416. std::map<int, std::vector<StringRef>> SizeToOperandName;
  417. for (const Record *Op : Operands) {
  418. if (!Op->isSubClassOf("X86MemOperand"))
  419. continue;
  420. if (int Size = Op->getValueAsInt("Size"))
  421. SizeToOperandName[Size].push_back(Op->getName());
  422. }
  423. OS << " default: return 0;\n";
  424. for (auto KV : SizeToOperandName) {
  425. for (const StringRef &OperandName : KV.second)
  426. OS << " case OpTypes::" << OperandName << ":\n";
  427. OS << " return " << KV.first << ";\n\n";
  428. }
  429. OS << " }\n}\n";
  430. OS << "} // end namespace " << Namespace << "\n";
  431. OS << "} // end namespace llvm\n";
  432. OS << "#endif // GET_INSTRINFO_MEM_OPERAND_SIZE\n\n";
  433. }
  434. void InstrInfoEmitter::emitLogicalOperandSizeMappings(
  435. raw_ostream &OS, StringRef Namespace,
  436. ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
  437. std::map<std::vector<unsigned>, unsigned> LogicalOpSizeMap;
  438. std::map<unsigned, std::vector<std::string>> InstMap;
  439. size_t LogicalOpListSize = 0U;
  440. std::vector<unsigned> LogicalOpList;
  441. for (const auto *Inst : NumberedInstructions) {
  442. if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings"))
  443. continue;
  444. LogicalOpList.clear();
  445. llvm::transform(Inst->Operands, std::back_inserter(LogicalOpList),
  446. [](const CGIOperandList::OperandInfo &Op) -> unsigned {
  447. auto *MIOI = Op.MIOperandInfo;
  448. if (!MIOI || MIOI->getNumArgs() == 0)
  449. return 1;
  450. return MIOI->getNumArgs();
  451. });
  452. LogicalOpListSize = std::max(LogicalOpList.size(), LogicalOpListSize);
  453. auto I =
  454. LogicalOpSizeMap.insert({LogicalOpList, LogicalOpSizeMap.size()}).first;
  455. InstMap[I->second].push_back(
  456. (Namespace + "::" + Inst->TheDef->getName()).str());
  457. }
  458. OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n";
  459. OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n";
  460. OS << "namespace llvm {\n";
  461. OS << "namespace " << Namespace << " {\n";
  462. OS << "LLVM_READONLY static unsigned\n";
  463. OS << "getLogicalOperandSize(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
  464. if (!InstMap.empty()) {
  465. std::vector<const std::vector<unsigned> *> LogicalOpSizeList(
  466. LogicalOpSizeMap.size());
  467. for (auto &P : LogicalOpSizeMap) {
  468. LogicalOpSizeList[P.second] = &P.first;
  469. }
  470. OS << " static const unsigned SizeMap[][" << LogicalOpListSize
  471. << "] = {\n";
  472. for (auto &R : LogicalOpSizeList) {
  473. const auto &Row = *R;
  474. OS << " {";
  475. int i;
  476. for (i = 0; i < static_cast<int>(Row.size()); ++i) {
  477. OS << Row[i] << ", ";
  478. }
  479. for (; i < static_cast<int>(LogicalOpListSize); ++i) {
  480. OS << "0, ";
  481. }
  482. OS << "}, ";
  483. OS << "\n";
  484. }
  485. OS << " };\n";
  486. OS << " switch (Opcode) {\n";
  487. OS << " default: return LogicalOpIdx;\n";
  488. for (auto &P : InstMap) {
  489. auto OpMapIdx = P.first;
  490. const auto &Insts = P.second;
  491. for (const auto &Inst : Insts) {
  492. OS << " case " << Inst << ":\n";
  493. }
  494. OS << " return SizeMap[" << OpMapIdx << "][LogicalOpIdx];\n";
  495. }
  496. OS << " }\n";
  497. } else {
  498. OS << " return LogicalOpIdx;\n";
  499. }
  500. OS << "}\n";
  501. OS << "LLVM_READONLY static inline unsigned\n";
  502. OS << "getLogicalOperandIdx(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
  503. OS << " auto S = 0U;\n";
  504. OS << " for (auto i = 0U; i < LogicalOpIdx; ++i)\n";
  505. OS << " S += getLogicalOperandSize(Opcode, i);\n";
  506. OS << " return S;\n";
  507. OS << "}\n";
  508. OS << "} // end namespace " << Namespace << "\n";
  509. OS << "} // end namespace llvm\n";
  510. OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP\n\n";
  511. }
  512. void InstrInfoEmitter::emitLogicalOperandTypeMappings(
  513. raw_ostream &OS, StringRef Namespace,
  514. ArrayRef<const CodeGenInstruction *> NumberedInstructions) {
  515. std::map<std::vector<std::string>, unsigned> LogicalOpTypeMap;
  516. std::map<unsigned, std::vector<std::string>> InstMap;
  517. size_t OpTypeListSize = 0U;
  518. std::vector<std::string> LogicalOpTypeList;
  519. for (const auto *Inst : NumberedInstructions) {
  520. if (!Inst->TheDef->getValueAsBit("UseLogicalOperandMappings"))
  521. continue;
  522. LogicalOpTypeList.clear();
  523. for (const auto &Op : Inst->Operands) {
  524. auto *OpR = Op.Rec;
  525. if ((OpR->isSubClassOf("Operand") ||
  526. OpR->isSubClassOf("RegisterOperand") ||
  527. OpR->isSubClassOf("RegisterClass")) &&
  528. !OpR->isAnonymous()) {
  529. LogicalOpTypeList.push_back(
  530. (Namespace + "::OpTypes::" + Op.Rec->getName()).str());
  531. } else {
  532. LogicalOpTypeList.push_back("-1");
  533. }
  534. }
  535. OpTypeListSize = std::max(LogicalOpTypeList.size(), OpTypeListSize);
  536. auto I =
  537. LogicalOpTypeMap.insert({LogicalOpTypeList, LogicalOpTypeMap.size()})
  538. .first;
  539. InstMap[I->second].push_back(
  540. (Namespace + "::" + Inst->TheDef->getName()).str());
  541. }
  542. OS << "#ifdef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n";
  543. OS << "#undef GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n";
  544. OS << "namespace llvm {\n";
  545. OS << "namespace " << Namespace << " {\n";
  546. OS << "LLVM_READONLY static int\n";
  547. OS << "getLogicalOperandType(uint16_t Opcode, uint16_t LogicalOpIdx) {\n";
  548. if (!InstMap.empty()) {
  549. std::vector<const std::vector<std::string> *> LogicalOpTypeList(
  550. LogicalOpTypeMap.size());
  551. for (auto &P : LogicalOpTypeMap) {
  552. LogicalOpTypeList[P.second] = &P.first;
  553. }
  554. OS << " static const int TypeMap[][" << OpTypeListSize << "] = {\n";
  555. for (int r = 0, rs = LogicalOpTypeList.size(); r < rs; ++r) {
  556. const auto &Row = *LogicalOpTypeList[r];
  557. OS << " {";
  558. int i, s = Row.size();
  559. for (i = 0; i < s; ++i) {
  560. if (i > 0)
  561. OS << ", ";
  562. OS << Row[i];
  563. }
  564. for (; i < static_cast<int>(OpTypeListSize); ++i) {
  565. if (i > 0)
  566. OS << ", ";
  567. OS << "-1";
  568. }
  569. OS << "}";
  570. if (r != rs - 1)
  571. OS << ",";
  572. OS << "\n";
  573. }
  574. OS << " };\n";
  575. OS << " switch (Opcode) {\n";
  576. OS << " default: return -1;\n";
  577. for (auto &P : InstMap) {
  578. auto OpMapIdx = P.first;
  579. const auto &Insts = P.second;
  580. for (const auto &Inst : Insts) {
  581. OS << " case " << Inst << ":\n";
  582. }
  583. OS << " return TypeMap[" << OpMapIdx << "][LogicalOpIdx];\n";
  584. }
  585. OS << " }\n";
  586. } else {
  587. OS << " return -1;\n";
  588. }
  589. OS << "}\n";
  590. OS << "} // end namespace " << Namespace << "\n";
  591. OS << "} // end namespace llvm\n";
  592. OS << "#endif // GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP\n\n";
  593. }
  594. void InstrInfoEmitter::emitMCIIHelperMethods(raw_ostream &OS,
  595. StringRef TargetName) {
  596. RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
  597. OS << "#ifdef GET_INSTRINFO_MC_HELPER_DECLS\n";
  598. OS << "#undef GET_INSTRINFO_MC_HELPER_DECLS\n\n";
  599. OS << "namespace llvm {\n";
  600. OS << "class MCInst;\n";
  601. OS << "class FeatureBitset;\n\n";
  602. OS << "namespace " << TargetName << "_MC {\n\n";
  603. for (const Record *Rec : TIIPredicates) {
  604. OS << "bool " << Rec->getValueAsString("FunctionName")
  605. << "(const MCInst &MI);\n";
  606. }
  607. OS << "void verifyInstructionPredicates(unsigned Opcode, const FeatureBitset "
  608. "&Features);\n";
  609. OS << "\n} // end namespace " << TargetName << "_MC\n";
  610. OS << "} // end namespace llvm\n\n";
  611. OS << "#endif // GET_INSTRINFO_MC_HELPER_DECLS\n\n";
  612. OS << "#ifdef GET_INSTRINFO_MC_HELPERS\n";
  613. OS << "#undef GET_INSTRINFO_MC_HELPERS\n\n";
  614. OS << "namespace llvm {\n";
  615. OS << "namespace " << TargetName << "_MC {\n\n";
  616. PredicateExpander PE(TargetName);
  617. PE.setExpandForMC(true);
  618. for (const Record *Rec : TIIPredicates) {
  619. OS << "bool " << Rec->getValueAsString("FunctionName");
  620. OS << "(const MCInst &MI) {\n";
  621. OS.indent(PE.getIndentLevel() * 2);
  622. PE.expandStatement(OS, Rec->getValueAsDef("Body"));
  623. OS << "\n}\n\n";
  624. }
  625. OS << "} // end namespace " << TargetName << "_MC\n";
  626. OS << "} // end namespace llvm\n\n";
  627. OS << "#endif // GET_GENISTRINFO_MC_HELPERS\n\n";
  628. }
  629. static std::string
  630. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  631. std::string Name = "CEFBS";
  632. for (const auto &Feature : FeatureBitset)
  633. Name += ("_" + Feature->getName()).str();
  634. return Name;
  635. }
  636. void InstrInfoEmitter::emitFeatureVerifier(raw_ostream &OS,
  637. const CodeGenTarget &Target) {
  638. const auto &All = SubtargetFeatureInfo::getAll(Records);
  639. std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
  640. SubtargetFeatures.insert(All.begin(), All.end());
  641. OS << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  642. << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  643. << "#include <_llvm_sstream.h>\n\n";
  644. OS << "namespace llvm {\n";
  645. OS << "namespace " << Target.getName() << "_MC {\n\n";
  646. // Emit the subtarget feature enumeration.
  647. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
  648. OS);
  649. // Emit the name table for error messages.
  650. OS << "#ifndef NDEBUG\n";
  651. SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, OS);
  652. OS << "#endif // NDEBUG\n\n";
  653. // Emit the available features compute function.
  654. SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
  655. Target.getName(), "", "computeAvailableFeatures", SubtargetFeatures, OS);
  656. std::vector<std::vector<Record *>> FeatureBitsets;
  657. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  658. FeatureBitsets.emplace_back();
  659. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  660. const auto &I = SubtargetFeatures.find(Predicate);
  661. if (I != SubtargetFeatures.end())
  662. FeatureBitsets.back().push_back(I->second.TheDef);
  663. }
  664. }
  665. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  666. const std::vector<Record *> &B) {
  667. if (A.size() < B.size())
  668. return true;
  669. if (A.size() > B.size())
  670. return false;
  671. for (auto Pair : zip(A, B)) {
  672. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  673. return true;
  674. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  675. return false;
  676. }
  677. return false;
  678. });
  679. FeatureBitsets.erase(
  680. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  681. FeatureBitsets.end());
  682. OS << "#ifndef NDEBUG\n"
  683. << "// Feature bitsets.\n"
  684. << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
  685. << " CEFBS_None,\n";
  686. for (const auto &FeatureBitset : FeatureBitsets) {
  687. if (FeatureBitset.empty())
  688. continue;
  689. OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  690. }
  691. OS << "};\n\n"
  692. << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
  693. << " {}, // CEFBS_None\n";
  694. for (const auto &FeatureBitset : FeatureBitsets) {
  695. if (FeatureBitset.empty())
  696. continue;
  697. OS << " {";
  698. for (const auto &Feature : FeatureBitset) {
  699. const auto &I = SubtargetFeatures.find(Feature);
  700. assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
  701. OS << I->second.getEnumBitName() << ", ";
  702. }
  703. OS << "},\n";
  704. }
  705. OS << "};\n"
  706. << "#endif // NDEBUG\n\n";
  707. // Emit the predicate verifier.
  708. OS << "void verifyInstructionPredicates(\n"
  709. << " unsigned Opcode, const FeatureBitset &Features) {\n"
  710. << "#ifndef NDEBUG\n"
  711. << " static " << getMinimalTypeForRange(FeatureBitsets.size())
  712. << " RequiredFeaturesRefs[] = {\n";
  713. unsigned InstIdx = 0;
  714. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  715. OS << " CEFBS";
  716. unsigned NumPredicates = 0;
  717. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  718. const auto &I = SubtargetFeatures.find(Predicate);
  719. if (I != SubtargetFeatures.end()) {
  720. OS << '_' << I->second.TheDef->getName();
  721. NumPredicates++;
  722. }
  723. }
  724. if (!NumPredicates)
  725. OS << "_None";
  726. OS << ", // " << Inst->TheDef->getName() << " = " << InstIdx << "\n";
  727. InstIdx++;
  728. }
  729. OS << " };\n\n";
  730. OS << " assert(Opcode < " << InstIdx << ");\n";
  731. OS << " FeatureBitset AvailableFeatures = "
  732. "computeAvailableFeatures(Features);\n";
  733. OS << " const FeatureBitset &RequiredFeatures = "
  734. "FeatureBitsets[RequiredFeaturesRefs[Opcode]];\n";
  735. OS << " FeatureBitset MissingFeatures =\n"
  736. << " (AvailableFeatures & RequiredFeatures) ^\n"
  737. << " RequiredFeatures;\n"
  738. << " if (MissingFeatures.any()) {\n"
  739. << " std::ostringstream Msg;\n"
  740. << " Msg << \"Attempting to emit \" << &" << Target.getName()
  741. << "InstrNameData[" << Target.getName() << "InstrNameIndices[Opcode]]\n"
  742. << " << \" instruction but the \";\n"
  743. << " for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)\n"
  744. << " if (MissingFeatures.test(i))\n"
  745. << " Msg << SubtargetFeatureNames[i] << \" \";\n"
  746. << " Msg << \"predicate(s) are not met\";\n"
  747. << " report_fatal_error(Msg.str().c_str());\n"
  748. << " }\n"
  749. << "#endif // NDEBUG\n";
  750. OS << "}\n";
  751. OS << "} // end namespace " << Target.getName() << "_MC\n";
  752. OS << "} // end namespace llvm\n";
  753. OS << "#endif // ENABLE_INSTR_PREDICATE_VERIFIER\n\n";
  754. }
  755. void InstrInfoEmitter::emitTIIHelperMethods(raw_ostream &OS,
  756. StringRef TargetName,
  757. bool ExpandDefinition) {
  758. RecVec TIIPredicates = Records.getAllDerivedDefinitions("TIIPredicate");
  759. if (TIIPredicates.empty())
  760. return;
  761. PredicateExpander PE(TargetName);
  762. PE.setExpandForMC(false);
  763. for (const Record *Rec : TIIPredicates) {
  764. OS << (ExpandDefinition ? "" : "static ") << "bool ";
  765. if (ExpandDefinition)
  766. OS << TargetName << "InstrInfo::";
  767. OS << Rec->getValueAsString("FunctionName");
  768. OS << "(const MachineInstr &MI)";
  769. if (!ExpandDefinition) {
  770. OS << ";\n";
  771. continue;
  772. }
  773. OS << " {\n";
  774. OS.indent(PE.getIndentLevel() * 2);
  775. PE.expandStatement(OS, Rec->getValueAsDef("Body"));
  776. OS << "\n}\n\n";
  777. }
  778. }
  779. //===----------------------------------------------------------------------===//
  780. // Main Output.
  781. //===----------------------------------------------------------------------===//
  782. // run - Emit the main instruction description records for the target...
  783. void InstrInfoEmitter::run(raw_ostream &OS) {
  784. emitSourceFileHeader("Target Instruction Enum Values and Descriptors", OS);
  785. emitEnums(OS);
  786. OS << "#ifdef GET_INSTRINFO_MC_DESC\n";
  787. OS << "#undef GET_INSTRINFO_MC_DESC\n";
  788. OS << "namespace llvm {\n\n";
  789. CodeGenTarget &Target = CDP.getTargetInfo();
  790. const std::string &TargetName = std::string(Target.getName());
  791. Record *InstrInfo = Target.getInstructionSet();
  792. // Keep track of all of the def lists we have emitted already.
  793. std::map<std::vector<Record*>, unsigned> EmittedLists;
  794. unsigned ListNumber = 0;
  795. // Emit all of the instruction's implicit uses and defs.
  796. Records.startTimer("Emit uses/defs");
  797. for (const CodeGenInstruction *II : Target.getInstructionsByEnumValue()) {
  798. std::vector<Record *> ImplicitOps = II->ImplicitUses;
  799. llvm::append_range(ImplicitOps, II->ImplicitDefs);
  800. if (!ImplicitOps.empty()) {
  801. unsigned &IL = EmittedLists[ImplicitOps];
  802. if (!IL) {
  803. IL = ++ListNumber;
  804. PrintDefList(ImplicitOps, IL, OS);
  805. }
  806. }
  807. }
  808. OperandInfoMapTy OperandInfoIDs;
  809. // Emit all of the operand info records.
  810. Records.startTimer("Emit operand info");
  811. EmitOperandInfo(OS, OperandInfoIDs);
  812. // Emit all of the MCInstrDesc records in reverse ENUM ordering.
  813. Records.startTimer("Emit InstrDesc records");
  814. OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
  815. ArrayRef<const CodeGenInstruction*> NumberedInstructions =
  816. Target.getInstructionsByEnumValue();
  817. SequenceToOffsetTable<std::string> InstrNames;
  818. unsigned Num = NumberedInstructions.size();
  819. for (const CodeGenInstruction *Inst : reverse(NumberedInstructions)) {
  820. // Keep a list of the instruction names.
  821. InstrNames.add(std::string(Inst->TheDef->getName()));
  822. // Emit the record into the table.
  823. emitRecord(*Inst, --Num, InstrInfo, EmittedLists, OperandInfoIDs, OS);
  824. }
  825. OS << "};\n\n";
  826. // Emit the array of instruction names.
  827. Records.startTimer("Emit instruction names");
  828. InstrNames.layout();
  829. InstrNames.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
  830. "InstrNameData[]");
  831. OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
  832. Num = 0;
  833. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  834. // Newline every eight entries.
  835. if (Num % 8 == 0)
  836. OS << "\n ";
  837. OS << InstrNames.get(std::string(Inst->TheDef->getName())) << "U, ";
  838. ++Num;
  839. }
  840. OS << "\n};\n\n";
  841. bool HasDeprecationFeatures =
  842. llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
  843. return !Inst->HasComplexDeprecationPredicate &&
  844. !Inst->DeprecatedReason.empty();
  845. });
  846. if (HasDeprecationFeatures) {
  847. OS << "extern const uint8_t " << TargetName
  848. << "InstrDeprecationFeatures[] = {";
  849. Num = 0;
  850. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  851. if (Num % 8 == 0)
  852. OS << "\n ";
  853. if (!Inst->HasComplexDeprecationPredicate &&
  854. !Inst->DeprecatedReason.empty())
  855. OS << Target.getInstNamespace() << "::" << Inst->DeprecatedReason
  856. << ", ";
  857. else
  858. OS << "uint8_t(-1), ";
  859. ++Num;
  860. }
  861. OS << "\n};\n\n";
  862. }
  863. bool HasComplexDeprecationInfos =
  864. llvm::any_of(NumberedInstructions, [](const CodeGenInstruction *Inst) {
  865. return Inst->HasComplexDeprecationPredicate;
  866. });
  867. if (HasComplexDeprecationInfos) {
  868. OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
  869. << "InstrComplexDeprecationInfos[] = {";
  870. Num = 0;
  871. for (const CodeGenInstruction *Inst : NumberedInstructions) {
  872. if (Num % 8 == 0)
  873. OS << "\n ";
  874. if (Inst->HasComplexDeprecationPredicate)
  875. // Emit a function pointer to the complex predicate method.
  876. OS << "&get" << Inst->DeprecatedReason << "DeprecationInfo, ";
  877. else
  878. OS << "nullptr, ";
  879. ++Num;
  880. }
  881. OS << "\n};\n\n";
  882. }
  883. // MCInstrInfo initialization routine.
  884. Records.startTimer("Emit initialization routine");
  885. OS << "static inline void Init" << TargetName
  886. << "MCInstrInfo(MCInstrInfo *II) {\n";
  887. OS << " II->InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
  888. << "InstrNameIndices, " << TargetName << "InstrNameData, ";
  889. if (HasDeprecationFeatures)
  890. OS << TargetName << "InstrDeprecationFeatures, ";
  891. else
  892. OS << "nullptr, ";
  893. if (HasComplexDeprecationInfos)
  894. OS << TargetName << "InstrComplexDeprecationInfos, ";
  895. else
  896. OS << "nullptr, ";
  897. OS << NumberedInstructions.size() << ");\n}\n\n";
  898. OS << "} // end namespace llvm\n";
  899. OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
  900. // Create a TargetInstrInfo subclass to hide the MC layer initialization.
  901. OS << "#ifdef GET_INSTRINFO_HEADER\n";
  902. OS << "#undef GET_INSTRINFO_HEADER\n";
  903. std::string ClassName = TargetName + "GenInstrInfo";
  904. OS << "namespace llvm {\n";
  905. OS << "struct " << ClassName << " : public TargetInstrInfo {\n"
  906. << " explicit " << ClassName
  907. << "(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u, "
  908. "unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u);\n"
  909. << " ~" << ClassName << "() override = default;\n";
  910. OS << "\n};\n} // end namespace llvm\n";
  911. OS << "#endif // GET_INSTRINFO_HEADER\n\n";
  912. OS << "#ifdef GET_INSTRINFO_HELPER_DECLS\n";
  913. OS << "#undef GET_INSTRINFO_HELPER_DECLS\n\n";
  914. emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ false);
  915. OS << "\n";
  916. OS << "#endif // GET_INSTRINFO_HELPER_DECLS\n\n";
  917. OS << "#ifdef GET_INSTRINFO_HELPERS\n";
  918. OS << "#undef GET_INSTRINFO_HELPERS\n\n";
  919. emitTIIHelperMethods(OS, TargetName, /* ExpandDefinition = */ true);
  920. OS << "#endif // GET_INSTRINFO_HELPERS\n\n";
  921. OS << "#ifdef GET_INSTRINFO_CTOR_DTOR\n";
  922. OS << "#undef GET_INSTRINFO_CTOR_DTOR\n";
  923. OS << "namespace llvm {\n";
  924. OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
  925. OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
  926. OS << "extern const char " << TargetName << "InstrNameData[];\n";
  927. if (HasDeprecationFeatures)
  928. OS << "extern const uint8_t " << TargetName
  929. << "InstrDeprecationFeatures[];\n";
  930. if (HasComplexDeprecationInfos)
  931. OS << "extern const MCInstrInfo::ComplexDeprecationPredicate " << TargetName
  932. << "InstrComplexDeprecationInfos[];\n";
  933. OS << ClassName << "::" << ClassName
  934. << "(unsigned CFSetupOpcode, unsigned CFDestroyOpcode, unsigned "
  935. "CatchRetOpcode, unsigned ReturnOpcode)\n"
  936. << " : TargetInstrInfo(CFSetupOpcode, CFDestroyOpcode, CatchRetOpcode, "
  937. "ReturnOpcode) {\n"
  938. << " InitMCInstrInfo(" << TargetName << "Insts, " << TargetName
  939. << "InstrNameIndices, " << TargetName << "InstrNameData, ";
  940. if (HasDeprecationFeatures)
  941. OS << TargetName << "InstrDeprecationFeatures, ";
  942. else
  943. OS << "nullptr, ";
  944. if (HasComplexDeprecationInfos)
  945. OS << TargetName << "InstrComplexDeprecationInfos, ";
  946. else
  947. OS << "nullptr, ";
  948. OS << NumberedInstructions.size() << ");\n}\n";
  949. OS << "} // end namespace llvm\n";
  950. OS << "#endif // GET_INSTRINFO_CTOR_DTOR\n\n";
  951. Records.startTimer("Emit operand name mappings");
  952. emitOperandNameMappings(OS, Target, NumberedInstructions);
  953. Records.startTimer("Emit operand type mappings");
  954. emitOperandTypeMappings(OS, Target, NumberedInstructions);
  955. Records.startTimer("Emit logical operand size mappings");
  956. emitLogicalOperandSizeMappings(OS, TargetName, NumberedInstructions);
  957. Records.startTimer("Emit logical operand type mappings");
  958. emitLogicalOperandTypeMappings(OS, TargetName, NumberedInstructions);
  959. Records.startTimer("Emit helper methods");
  960. emitMCIIHelperMethods(OS, TargetName);
  961. Records.startTimer("Emit verifier methods");
  962. emitFeatureVerifier(OS, Target);
  963. }
  964. void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
  965. Record *InstrInfo,
  966. std::map<std::vector<Record*>, unsigned> &EmittedLists,
  967. const OperandInfoMapTy &OpInfo,
  968. raw_ostream &OS) {
  969. int MinOperands = 0;
  970. if (!Inst.Operands.empty())
  971. // Each logical operand can be multiple MI operands.
  972. MinOperands = Inst.Operands.back().MIOperandNo +
  973. Inst.Operands.back().MINumOperands;
  974. OS << " { ";
  975. OS << Num << ",\t" << MinOperands << ",\t"
  976. << Inst.Operands.NumDefs << ",\t"
  977. << Inst.TheDef->getValueAsInt("Size") << ",\t"
  978. << SchedModels.getSchedClassIdx(Inst) << ",\t"
  979. << Inst.ImplicitUses.size() << ",\t"
  980. << Inst.ImplicitDefs.size() << ",\t0";
  981. CodeGenTarget &Target = CDP.getTargetInfo();
  982. // Emit all of the target independent flags...
  983. if (Inst.isPreISelOpcode) OS << "|(1ULL<<MCID::PreISelOpcode)";
  984. if (Inst.isPseudo) OS << "|(1ULL<<MCID::Pseudo)";
  985. if (Inst.isMeta) OS << "|(1ULL<<MCID::Meta)";
  986. if (Inst.isReturn) OS << "|(1ULL<<MCID::Return)";
  987. if (Inst.isEHScopeReturn) OS << "|(1ULL<<MCID::EHScopeReturn)";
  988. if (Inst.isBranch) OS << "|(1ULL<<MCID::Branch)";
  989. if (Inst.isIndirectBranch) OS << "|(1ULL<<MCID::IndirectBranch)";
  990. if (Inst.isCompare) OS << "|(1ULL<<MCID::Compare)";
  991. if (Inst.isMoveImm) OS << "|(1ULL<<MCID::MoveImm)";
  992. if (Inst.isMoveReg) OS << "|(1ULL<<MCID::MoveReg)";
  993. if (Inst.isBitcast) OS << "|(1ULL<<MCID::Bitcast)";
  994. if (Inst.isAdd) OS << "|(1ULL<<MCID::Add)";
  995. if (Inst.isTrap) OS << "|(1ULL<<MCID::Trap)";
  996. if (Inst.isSelect) OS << "|(1ULL<<MCID::Select)";
  997. if (Inst.isBarrier) OS << "|(1ULL<<MCID::Barrier)";
  998. if (Inst.hasDelaySlot) OS << "|(1ULL<<MCID::DelaySlot)";
  999. if (Inst.isCall) OS << "|(1ULL<<MCID::Call)";
  1000. if (Inst.canFoldAsLoad) OS << "|(1ULL<<MCID::FoldableAsLoad)";
  1001. if (Inst.mayLoad) OS << "|(1ULL<<MCID::MayLoad)";
  1002. if (Inst.mayStore) OS << "|(1ULL<<MCID::MayStore)";
  1003. if (Inst.mayRaiseFPException) OS << "|(1ULL<<MCID::MayRaiseFPException)";
  1004. if (Inst.isPredicable) OS << "|(1ULL<<MCID::Predicable)";
  1005. if (Inst.isConvertibleToThreeAddress) OS << "|(1ULL<<MCID::ConvertibleTo3Addr)";
  1006. if (Inst.isCommutable) OS << "|(1ULL<<MCID::Commutable)";
  1007. if (Inst.isTerminator) OS << "|(1ULL<<MCID::Terminator)";
  1008. if (Inst.isReMaterializable) OS << "|(1ULL<<MCID::Rematerializable)";
  1009. if (Inst.isNotDuplicable) OS << "|(1ULL<<MCID::NotDuplicable)";
  1010. if (Inst.Operands.hasOptionalDef) OS << "|(1ULL<<MCID::HasOptionalDef)";
  1011. if (Inst.usesCustomInserter) OS << "|(1ULL<<MCID::UsesCustomInserter)";
  1012. if (Inst.hasPostISelHook) OS << "|(1ULL<<MCID::HasPostISelHook)";
  1013. if (Inst.Operands.isVariadic)OS << "|(1ULL<<MCID::Variadic)";
  1014. if (Inst.hasSideEffects) OS << "|(1ULL<<MCID::UnmodeledSideEffects)";
  1015. if (Inst.isAsCheapAsAMove) OS << "|(1ULL<<MCID::CheapAsAMove)";
  1016. if (!Target.getAllowRegisterRenaming() || Inst.hasExtraSrcRegAllocReq)
  1017. OS << "|(1ULL<<MCID::ExtraSrcRegAllocReq)";
  1018. if (!Target.getAllowRegisterRenaming() || Inst.hasExtraDefRegAllocReq)
  1019. OS << "|(1ULL<<MCID::ExtraDefRegAllocReq)";
  1020. if (Inst.isRegSequence) OS << "|(1ULL<<MCID::RegSequence)";
  1021. if (Inst.isExtractSubreg) OS << "|(1ULL<<MCID::ExtractSubreg)";
  1022. if (Inst.isInsertSubreg) OS << "|(1ULL<<MCID::InsertSubreg)";
  1023. if (Inst.isConvergent) OS << "|(1ULL<<MCID::Convergent)";
  1024. if (Inst.variadicOpsAreDefs) OS << "|(1ULL<<MCID::VariadicOpsAreDefs)";
  1025. if (Inst.isAuthenticated) OS << "|(1ULL<<MCID::Authenticated)";
  1026. // Emit all of the target-specific flags...
  1027. BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
  1028. if (!TSF)
  1029. PrintFatalError(Inst.TheDef->getLoc(), "no TSFlags?");
  1030. uint64_t Value = 0;
  1031. for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
  1032. if (const auto *Bit = dyn_cast<BitInit>(TSF->getBit(i)))
  1033. Value |= uint64_t(Bit->getValue()) << i;
  1034. else
  1035. PrintFatalError(Inst.TheDef->getLoc(),
  1036. "Invalid TSFlags bit in " + Inst.TheDef->getName());
  1037. }
  1038. OS << ", 0x";
  1039. OS.write_hex(Value);
  1040. OS << "ULL, ";
  1041. // Emit the implicit use/def list...
  1042. std::vector<Record *> ImplicitOps = Inst.ImplicitUses;
  1043. llvm::append_range(ImplicitOps, Inst.ImplicitDefs);
  1044. if (ImplicitOps.empty())
  1045. OS << "nullptr, ";
  1046. else
  1047. OS << "ImplicitList" << EmittedLists[ImplicitOps] << ", ";
  1048. // Emit the operand info.
  1049. std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
  1050. if (OperandInfo.empty())
  1051. OS << "nullptr";
  1052. else
  1053. OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
  1054. OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
  1055. }
  1056. // emitEnums - Print out enum values for all of the instructions.
  1057. void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
  1058. OS << "#ifdef GET_INSTRINFO_ENUM\n";
  1059. OS << "#undef GET_INSTRINFO_ENUM\n";
  1060. OS << "namespace llvm {\n\n";
  1061. const CodeGenTarget &Target = CDP.getTargetInfo();
  1062. // We must emit the PHI opcode first...
  1063. StringRef Namespace = Target.getInstNamespace();
  1064. if (Namespace.empty())
  1065. PrintFatalError("No instructions defined!");
  1066. OS << "namespace " << Namespace << " {\n";
  1067. OS << " enum {\n";
  1068. unsigned Num = 0;
  1069. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue())
  1070. OS << " " << Inst->TheDef->getName() << "\t= " << Num++ << ",\n";
  1071. OS << " INSTRUCTION_LIST_END = " << Num << "\n";
  1072. OS << " };\n\n";
  1073. OS << "} // end namespace " << Namespace << "\n";
  1074. OS << "} // end namespace llvm\n";
  1075. OS << "#endif // GET_INSTRINFO_ENUM\n\n";
  1076. OS << "#ifdef GET_INSTRINFO_SCHED_ENUM\n";
  1077. OS << "#undef GET_INSTRINFO_SCHED_ENUM\n";
  1078. OS << "namespace llvm {\n\n";
  1079. OS << "namespace " << Namespace << " {\n";
  1080. OS << "namespace Sched {\n";
  1081. OS << " enum {\n";
  1082. Num = 0;
  1083. for (const auto &Class : SchedModels.explicit_classes())
  1084. OS << " " << Class.Name << "\t= " << Num++ << ",\n";
  1085. OS << " SCHED_LIST_END = " << Num << "\n";
  1086. OS << " };\n";
  1087. OS << "} // end namespace Sched\n";
  1088. OS << "} // end namespace " << Namespace << "\n";
  1089. OS << "} // end namespace llvm\n";
  1090. OS << "#endif // GET_INSTRINFO_SCHED_ENUM\n\n";
  1091. }
  1092. namespace llvm {
  1093. void EmitInstrInfo(RecordKeeper &RK, raw_ostream &OS) {
  1094. RK.startTimer("Analyze DAG patterns");
  1095. InstrInfoEmitter(RK).run(OS);
  1096. RK.startTimer("Emit map table");
  1097. EmitMapTable(RK, OS);
  1098. }
  1099. } // end namespace llvm