AsmWriterEmitter.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This tablegen backend is emits an assembly printer for the current target.
  11. // Note that this is currently fairly skeletal, but will grow over time.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "AsmWriterInst.h"
  15. #include "CodeGenTarget.h"
  16. #include "SequenceToOffsetTable.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/Support/Debug.h"
  21. #include "llvm/Support/Format.h"
  22. #include "llvm/Support/MathExtras.h"
  23. #include "llvm/TableGen/Error.h"
  24. #include "llvm/TableGen/Record.h"
  25. #include "llvm/TableGen/TableGenBackend.h"
  26. #include <algorithm>
  27. #include <cassert>
  28. #include <map>
  29. #include <vector>
  30. using namespace llvm;
  31. #define DEBUG_TYPE "asm-writer-emitter"
  32. namespace {
  33. class AsmWriterEmitter {
  34. RecordKeeper &Records;
  35. CodeGenTarget Target;
  36. std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
  37. const std::vector<const CodeGenInstruction*> *NumberedInstructions;
  38. std::vector<AsmWriterInst> Instructions;
  39. std::vector<std::string> PrintMethods;
  40. public:
  41. AsmWriterEmitter(RecordKeeper &R);
  42. void run(raw_ostream &o);
  43. private:
  44. void EmitPrintInstruction(raw_ostream &o);
  45. void EmitGetRegisterName(raw_ostream &o);
  46. void EmitPrintAliasInstruction(raw_ostream &O);
  47. AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
  48. assert(ID < NumberedInstructions->size());
  49. std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
  50. CGIAWIMap.find(NumberedInstructions->at(ID));
  51. assert(I != CGIAWIMap.end() && "Didn't find inst!");
  52. return I->second;
  53. }
  54. void FindUniqueOperandCommands(std::vector<std::string> &UOC,
  55. std::vector<unsigned> &InstIdxs,
  56. std::vector<unsigned> &InstOpsUsed) const;
  57. };
  58. } // end anonymous namespace
  59. static void PrintCases(std::vector<std::pair<std::string,
  60. AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
  61. O << " case " << OpsToPrint.back().first << ": ";
  62. AsmWriterOperand TheOp = OpsToPrint.back().second;
  63. OpsToPrint.pop_back();
  64. // Check to see if any other operands are identical in this list, and if so,
  65. // emit a case label for them.
  66. for (unsigned i = OpsToPrint.size(); i != 0; --i)
  67. if (OpsToPrint[i-1].second == TheOp) {
  68. O << "\n case " << OpsToPrint[i-1].first << ": ";
  69. OpsToPrint.erase(OpsToPrint.begin()+i-1);
  70. }
  71. // Finally, emit the code.
  72. O << TheOp.getCode();
  73. O << "break;\n";
  74. }
  75. /// EmitInstructions - Emit the last instruction in the vector and any other
  76. /// instructions that are suitably similar to it.
  77. static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
  78. raw_ostream &O) {
  79. AsmWriterInst FirstInst = Insts.back();
  80. Insts.pop_back();
  81. std::vector<AsmWriterInst> SimilarInsts;
  82. unsigned DifferingOperand = ~0;
  83. for (unsigned i = Insts.size(); i != 0; --i) {
  84. unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
  85. if (DiffOp != ~1U) {
  86. if (DifferingOperand == ~0U) // First match!
  87. DifferingOperand = DiffOp;
  88. // If this differs in the same operand as the rest of the instructions in
  89. // this class, move it to the SimilarInsts list.
  90. if (DifferingOperand == DiffOp || DiffOp == ~0U) {
  91. SimilarInsts.push_back(Insts[i-1]);
  92. Insts.erase(Insts.begin()+i-1);
  93. }
  94. }
  95. }
  96. O << " case " << FirstInst.CGI->Namespace << "::"
  97. << FirstInst.CGI->TheDef->getName() << ":\n";
  98. for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
  99. O << " case " << SimilarInsts[i].CGI->Namespace << "::"
  100. << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
  101. for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
  102. if (i != DifferingOperand) {
  103. // If the operand is the same for all instructions, just print it.
  104. O << " " << FirstInst.Operands[i].getCode();
  105. } else {
  106. // If this is the operand that varies between all of the instructions,
  107. // emit a switch for just this operand now.
  108. O << " switch (MI->getOpcode()) {\n";
  109. std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
  110. OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
  111. FirstInst.CGI->TheDef->getName(),
  112. FirstInst.Operands[i]));
  113. for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
  114. AsmWriterInst &AWI = SimilarInsts[si];
  115. OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
  116. AWI.CGI->TheDef->getName(),
  117. AWI.Operands[i]));
  118. }
  119. std::reverse(OpsToPrint.begin(), OpsToPrint.end());
  120. while (!OpsToPrint.empty())
  121. PrintCases(OpsToPrint, O);
  122. O << " }";
  123. }
  124. O << "\n";
  125. }
  126. O << " break;\n";
  127. }
  128. void AsmWriterEmitter::
  129. FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
  130. std::vector<unsigned> &InstIdxs,
  131. std::vector<unsigned> &InstOpsUsed) const {
  132. InstIdxs.assign(NumberedInstructions->size(), ~0U);
  133. // This vector parallels UniqueOperandCommands, keeping track of which
  134. // instructions each case are used for. It is a comma separated string of
  135. // enums.
  136. std::vector<std::string> InstrsForCase;
  137. InstrsForCase.resize(UniqueOperandCommands.size());
  138. InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
  139. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  140. const AsmWriterInst *Inst = getAsmWriterInstByID(i);
  141. if (!Inst)
  142. continue; // PHI, INLINEASM, CFI_INSTRUCTION, etc.
  143. std::string Command;
  144. if (Inst->Operands.empty())
  145. continue; // Instruction already done.
  146. Command = " " + Inst->Operands[0].getCode() + "\n";
  147. // Check to see if we already have 'Command' in UniqueOperandCommands.
  148. // If not, add it.
  149. bool FoundIt = false;
  150. for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
  151. if (UniqueOperandCommands[idx] == Command) {
  152. InstIdxs[i] = idx;
  153. InstrsForCase[idx] += ", ";
  154. InstrsForCase[idx] += Inst->CGI->TheDef->getName();
  155. FoundIt = true;
  156. break;
  157. }
  158. if (!FoundIt) {
  159. InstIdxs[i] = UniqueOperandCommands.size();
  160. UniqueOperandCommands.push_back(Command);
  161. InstrsForCase.push_back(Inst->CGI->TheDef->getName());
  162. // This command matches one operand so far.
  163. InstOpsUsed.push_back(1);
  164. }
  165. }
  166. // For each entry of UniqueOperandCommands, there is a set of instructions
  167. // that uses it. If the next command of all instructions in the set are
  168. // identical, fold it into the command.
  169. for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
  170. CommandIdx != e; ++CommandIdx) {
  171. for (unsigned Op = 1; ; ++Op) {
  172. // Scan for the first instruction in the set.
  173. std::vector<unsigned>::iterator NIT =
  174. std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
  175. if (NIT == InstIdxs.end()) break; // No commonality.
  176. // If this instruction has no more operands, we isn't anything to merge
  177. // into this command.
  178. const AsmWriterInst *FirstInst =
  179. getAsmWriterInstByID(NIT-InstIdxs.begin());
  180. if (!FirstInst || FirstInst->Operands.size() == Op)
  181. break;
  182. // Otherwise, scan to see if all of the other instructions in this command
  183. // set share the operand.
  184. bool AllSame = true;
  185. for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
  186. NIT != InstIdxs.end();
  187. NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
  188. // Okay, found another instruction in this command set. If the operand
  189. // matches, we're ok, otherwise bail out.
  190. const AsmWriterInst *OtherInst =
  191. getAsmWriterInstByID(NIT-InstIdxs.begin());
  192. if (!OtherInst || OtherInst->Operands.size() == Op ||
  193. OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
  194. AllSame = false;
  195. break;
  196. }
  197. }
  198. if (!AllSame) break;
  199. // Okay, everything in this command set has the same next operand. Add it
  200. // to UniqueOperandCommands and remember that it was consumed.
  201. std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
  202. UniqueOperandCommands[CommandIdx] += Command;
  203. InstOpsUsed[CommandIdx]++;
  204. }
  205. }
  206. // Prepend some of the instructions each case is used for onto the case val.
  207. for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
  208. std::string Instrs = InstrsForCase[i];
  209. if (Instrs.size() > 70) {
  210. Instrs.erase(Instrs.begin()+70, Instrs.end());
  211. Instrs += "...";
  212. }
  213. if (!Instrs.empty())
  214. UniqueOperandCommands[i] = " // " + Instrs + "\n" +
  215. UniqueOperandCommands[i];
  216. }
  217. }
  218. static void UnescapeString(std::string &Str) {
  219. for (unsigned i = 0; i != Str.size(); ++i) {
  220. if (Str[i] == '\\' && i != Str.size()-1) {
  221. switch (Str[i+1]) {
  222. default: continue; // Don't execute the code after the switch.
  223. case 'a': Str[i] = '\a'; break;
  224. case 'b': Str[i] = '\b'; break;
  225. case 'e': Str[i] = 27; break;
  226. case 'f': Str[i] = '\f'; break;
  227. case 'n': Str[i] = '\n'; break;
  228. case 'r': Str[i] = '\r'; break;
  229. case 't': Str[i] = '\t'; break;
  230. case 'v': Str[i] = '\v'; break;
  231. case '"': Str[i] = '\"'; break;
  232. case '\'': Str[i] = '\''; break;
  233. case '\\': Str[i] = '\\'; break;
  234. }
  235. // Nuke the second character.
  236. Str.erase(Str.begin()+i+1);
  237. }
  238. }
  239. }
  240. /// EmitPrintInstruction - Generate the code for the "printInstruction" method
  241. /// implementation. Destroys all instances of AsmWriterInst information, by
  242. /// clearing the Instructions vector.
  243. void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
  244. Record *AsmWriter = Target.getAsmWriter();
  245. std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
  246. unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
  247. O <<
  248. "/// printInstruction - This method is automatically generated by tablegen\n"
  249. "/// from the instruction set description.\n"
  250. "void " << Target.getName() << ClassName
  251. << "::printInstruction(const MCInst *MI, "
  252. << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
  253. << "raw_ostream &O) {\n";
  254. // Build an aggregate string, and build a table of offsets into it.
  255. SequenceToOffsetTable<std::string> StringTable;
  256. /// OpcodeInfo - This encodes the index of the string to use for the first
  257. /// chunk of the output as well as indices used for operand printing.
  258. /// To reduce the number of unhandled cases, we expand the size from 32-bit
  259. /// to 32+16 = 48-bit.
  260. std::vector<uint64_t> OpcodeInfo;
  261. // Add all strings to the string table upfront so it can generate an optimized
  262. // representation.
  263. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  264. AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
  265. if (AWI &&
  266. AWI->Operands[0].OperandType ==
  267. AsmWriterOperand::isLiteralTextOperand &&
  268. !AWI->Operands[0].Str.empty()) {
  269. std::string Str = AWI->Operands[0].Str;
  270. UnescapeString(Str);
  271. StringTable.add(Str);
  272. }
  273. }
  274. StringTable.layout();
  275. unsigned MaxStringIdx = 0;
  276. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  277. AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
  278. unsigned Idx;
  279. if (!AWI) {
  280. // Something not handled by the asmwriter printer.
  281. Idx = ~0U;
  282. } else if (AWI->Operands[0].OperandType !=
  283. AsmWriterOperand::isLiteralTextOperand ||
  284. AWI->Operands[0].Str.empty()) {
  285. // Something handled by the asmwriter printer, but with no leading string.
  286. Idx = StringTable.get("");
  287. } else {
  288. std::string Str = AWI->Operands[0].Str;
  289. UnescapeString(Str);
  290. Idx = StringTable.get(Str);
  291. MaxStringIdx = std::max(MaxStringIdx, Idx);
  292. // Nuke the string from the operand list. It is now handled!
  293. AWI->Operands.erase(AWI->Operands.begin());
  294. }
  295. // Bias offset by one since we want 0 as a sentinel.
  296. OpcodeInfo.push_back(Idx+1);
  297. }
  298. // Figure out how many bits we used for the string index.
  299. unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
  300. // To reduce code size, we compactify common instructions into a few bits
  301. // in the opcode-indexed table.
  302. unsigned BitsLeft = 64-AsmStrBits;
  303. std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
  304. while (1) {
  305. std::vector<std::string> UniqueOperandCommands;
  306. std::vector<unsigned> InstIdxs;
  307. std::vector<unsigned> NumInstOpsHandled;
  308. FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
  309. NumInstOpsHandled);
  310. // If we ran out of operands to print, we're done.
  311. if (UniqueOperandCommands.empty()) break;
  312. // Compute the number of bits we need to represent these cases, this is
  313. // ceil(log2(numentries)).
  314. unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
  315. // If we don't have enough bits for this operand, don't include it.
  316. if (NumBits > BitsLeft) {
  317. DEBUG(errs() << "Not enough bits to densely encode " << NumBits
  318. << " more bits\n");
  319. break;
  320. }
  321. // Otherwise, we can include this in the initial lookup table. Add it in.
  322. for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
  323. if (InstIdxs[i] != ~0U) {
  324. OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
  325. }
  326. BitsLeft -= NumBits;
  327. // Remove the info about this operand.
  328. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  329. if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
  330. if (!Inst->Operands.empty()) {
  331. unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
  332. assert(NumOps <= Inst->Operands.size() &&
  333. "Can't remove this many ops!");
  334. Inst->Operands.erase(Inst->Operands.begin(),
  335. Inst->Operands.begin()+NumOps);
  336. }
  337. }
  338. // Remember the handlers for this set of operands.
  339. TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
  340. }
  341. // We always emit at least one 32-bit table. A second table is emitted if
  342. // more bits are needed.
  343. O<<" static const uint32_t OpInfo[] = {\n";
  344. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  345. O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
  346. << NumberedInstructions->at(i)->TheDef->getName() << "\n";
  347. }
  348. // Add a dummy entry so the array init doesn't end with a comma.
  349. O << " 0U\n";
  350. O << " };\n\n";
  351. if (BitsLeft < 32) {
  352. // Add a second OpInfo table only when it is necessary.
  353. // Adjust the type of the second table based on the number of bits needed.
  354. O << " static const uint"
  355. << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8")
  356. << "_t OpInfo2[] = {\n";
  357. for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
  358. O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
  359. << NumberedInstructions->at(i)->TheDef->getName() << "\n";
  360. }
  361. // Add a dummy entry so the array init doesn't end with a comma.
  362. O << " 0U\n";
  363. O << " };\n\n";
  364. }
  365. // Emit the string itself.
  366. O << " static const char AsmStrs[] = {\n";
  367. StringTable.emit(O, printChar);
  368. O << " };\n\n";
  369. O << " O << \"\\t\";\n\n";
  370. O << " // Emit the opcode for the instruction.\n";
  371. if (BitsLeft < 32) {
  372. // If we have two tables then we need to perform two lookups and combine
  373. // the results into a single 64-bit value.
  374. O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n"
  375. << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n"
  376. << " uint64_t Bits = (Bits2 << 32) | Bits1;\n";
  377. } else {
  378. // If only one table is used we just need to perform a single lookup.
  379. O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
  380. }
  381. O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
  382. << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
  383. // Output the table driven operand information.
  384. BitsLeft = 64-AsmStrBits;
  385. for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
  386. std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
  387. // Compute the number of bits we need to represent these cases, this is
  388. // ceil(log2(numentries)).
  389. unsigned NumBits = Log2_32_Ceil(Commands.size());
  390. assert(NumBits <= BitsLeft && "consistency error");
  391. // Emit code to extract this field from Bits.
  392. O << "\n // Fragment " << i << " encoded into " << NumBits
  393. << " bits for " << Commands.size() << " unique commands.\n";
  394. if (Commands.size() == 2) {
  395. // Emit two possibilitys with if/else.
  396. O << " if ((Bits >> "
  397. << (64-BitsLeft) << ") & "
  398. << ((1 << NumBits)-1) << ") {\n"
  399. << Commands[1]
  400. << " } else {\n"
  401. << Commands[0]
  402. << " }\n\n";
  403. } else if (Commands.size() == 1) {
  404. // Emit a single possibility.
  405. O << Commands[0] << "\n\n";
  406. } else {
  407. O << " switch ((Bits >> "
  408. << (64-BitsLeft) << ") & "
  409. << ((1 << NumBits)-1) << ") {\n"
  410. << " default: llvm_unreachable(\"Invalid command number.\");\n";
  411. // Print out all the cases.
  412. for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
  413. O << " case " << i << ":\n";
  414. O << Commands[i];
  415. O << " break;\n";
  416. }
  417. O << " }\n\n";
  418. }
  419. BitsLeft -= NumBits;
  420. }
  421. // Okay, delete instructions with no operand info left.
  422. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  423. // Entire instruction has been emitted?
  424. AsmWriterInst &Inst = Instructions[i];
  425. if (Inst.Operands.empty()) {
  426. Instructions.erase(Instructions.begin()+i);
  427. --i; --e;
  428. }
  429. }
  430. // Because this is a vector, we want to emit from the end. Reverse all of the
  431. // elements in the vector.
  432. std::reverse(Instructions.begin(), Instructions.end());
  433. // Now that we've emitted all of the operand info that fit into 32 bits, emit
  434. // information for those instructions that are left. This is a less dense
  435. // encoding, but we expect the main 32-bit table to handle the majority of
  436. // instructions.
  437. if (!Instructions.empty()) {
  438. // Find the opcode # of inline asm.
  439. O << " switch (MI->getOpcode()) {\n";
  440. while (!Instructions.empty())
  441. EmitInstructions(Instructions, O);
  442. O << " }\n";
  443. O << " return;\n";
  444. }
  445. O << "}\n";
  446. }
  447. static const char *getMinimalTypeForRange(uint64_t Range) {
  448. assert(Range < 0xFFFFFFFFULL && "Enum too large");
  449. if (Range > 0xFFFF)
  450. return "uint32_t";
  451. if (Range > 0xFF)
  452. return "uint16_t";
  453. return "uint8_t";
  454. }
  455. static void
  456. emitRegisterNameString(raw_ostream &O, StringRef AltName,
  457. const std::deque<CodeGenRegister> &Registers) {
  458. SequenceToOffsetTable<std::string> StringTable;
  459. SmallVector<std::string, 4> AsmNames(Registers.size());
  460. unsigned i = 0;
  461. for (const auto &Reg : Registers) {
  462. std::string &AsmName = AsmNames[i++];
  463. // "NoRegAltName" is special. We don't need to do a lookup for that,
  464. // as it's just a reference to the default register name.
  465. if (AltName == "" || AltName == "NoRegAltName") {
  466. AsmName = Reg.TheDef->getValueAsString("AsmName");
  467. if (AsmName.empty())
  468. AsmName = Reg.getName();
  469. } else {
  470. // Make sure the register has an alternate name for this index.
  471. std::vector<Record*> AltNameList =
  472. Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
  473. unsigned Idx = 0, e;
  474. for (e = AltNameList.size();
  475. Idx < e && (AltNameList[Idx]->getName() != AltName);
  476. ++Idx)
  477. ;
  478. // If the register has an alternate name for this index, use it.
  479. // Otherwise, leave it empty as an error flag.
  480. if (Idx < e) {
  481. std::vector<std::string> AltNames =
  482. Reg.TheDef->getValueAsListOfStrings("AltNames");
  483. if (AltNames.size() <= Idx)
  484. PrintFatalError(Reg.TheDef->getLoc(),
  485. "Register definition missing alt name for '" +
  486. AltName + "'.");
  487. AsmName = AltNames[Idx];
  488. }
  489. }
  490. StringTable.add(AsmName);
  491. }
  492. StringTable.layout();
  493. O << " static const char AsmStrs" << AltName << "[] = {\n";
  494. StringTable.emit(O, printChar);
  495. O << " };\n\n";
  496. O << " static const " << getMinimalTypeForRange(StringTable.size()-1)
  497. << " RegAsmOffset" << AltName << "[] = {";
  498. for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
  499. if ((i % 14) == 0)
  500. O << "\n ";
  501. O << StringTable.get(AsmNames[i]) << ", ";
  502. }
  503. O << "\n };\n"
  504. << "\n";
  505. }
  506. void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
  507. Record *AsmWriter = Target.getAsmWriter();
  508. std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
  509. const auto &Registers = Target.getRegBank().getRegisters();
  510. std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
  511. bool hasAltNames = AltNameIndices.size() > 1;
  512. O <<
  513. "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
  514. "/// from the register set description. This returns the assembler name\n"
  515. "/// for the specified register.\n"
  516. "const char *" << Target.getName() << ClassName << "::";
  517. if (hasAltNames)
  518. O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
  519. else
  520. O << "getRegisterName(unsigned RegNo) {\n";
  521. O << " assert(RegNo && RegNo < " << (Registers.size()+1)
  522. << " && \"Invalid register number!\");\n"
  523. << "\n";
  524. if (hasAltNames) {
  525. for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
  526. emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
  527. } else
  528. emitRegisterNameString(O, "", Registers);
  529. if (hasAltNames) {
  530. O << " switch(AltIdx) {\n"
  531. << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
  532. for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
  533. std::string Namespace = AltNameIndices[1]->getValueAsString("Namespace");
  534. std::string AltName(AltNameIndices[i]->getName());
  535. O << " case " << Namespace << "::" << AltName << ":\n"
  536. << " assert(*(AsmStrs" << AltName << "+RegAsmOffset"
  537. << AltName << "[RegNo-1]) &&\n"
  538. << " \"Invalid alt name index for register!\");\n"
  539. << " return AsmStrs" << AltName << "+RegAsmOffset"
  540. << AltName << "[RegNo-1];\n";
  541. }
  542. O << " }\n";
  543. } else {
  544. O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
  545. << " \"Invalid alt name index for register!\");\n"
  546. << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
  547. }
  548. O << "}\n";
  549. }
  550. namespace {
  551. // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
  552. // they both have the same conditionals. In which case, we cannot print out the
  553. // alias for that pattern.
  554. class IAPrinter {
  555. std::vector<std::string> Conds;
  556. std::map<StringRef, std::pair<int, int>> OpMap;
  557. SmallVector<Record*, 4> ReqFeatures;
  558. std::string Result;
  559. std::string AsmString;
  560. public:
  561. IAPrinter(std::string R, std::string AS) : Result(R), AsmString(AS) {}
  562. void addCond(const std::string &C) { Conds.push_back(C); }
  563. void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
  564. assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
  565. assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
  566. "Idx out of range");
  567. OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
  568. }
  569. bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
  570. int getOpIndex(StringRef Op) { return OpMap[Op].first; }
  571. std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
  572. std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
  573. StringRef::iterator End) {
  574. StringRef::iterator I = Start;
  575. StringRef::iterator Next;
  576. if (*I == '{') {
  577. // ${some_name}
  578. Start = ++I;
  579. while (I != End && *I != '}')
  580. ++I;
  581. Next = I;
  582. // eat the final '}'
  583. if (Next != End)
  584. ++Next;
  585. } else {
  586. // $name, just eat the usual suspects.
  587. while (I != End &&
  588. ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
  589. (*I >= '0' && *I <= '9') || *I == '_'))
  590. ++I;
  591. Next = I;
  592. }
  593. return std::make_pair(StringRef(Start, I - Start), Next);
  594. }
  595. void print(raw_ostream &O) {
  596. if (Conds.empty() && ReqFeatures.empty()) {
  597. O.indent(6) << "return true;\n";
  598. return;
  599. }
  600. O << "if (";
  601. for (std::vector<std::string>::iterator
  602. I = Conds.begin(), E = Conds.end(); I != E; ++I) {
  603. if (I != Conds.begin()) {
  604. O << " &&\n";
  605. O.indent(8);
  606. }
  607. O << *I;
  608. }
  609. O << ") {\n";
  610. O.indent(6) << "// " << Result << "\n";
  611. // Directly mangle mapped operands into the string. Each operand is
  612. // identified by a '$' sign followed by a byte identifying the number of the
  613. // operand. We add one to the index to avoid zero bytes.
  614. StringRef ASM(AsmString);
  615. SmallString<128> OutString;
  616. raw_svector_ostream OS(OutString);
  617. for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
  618. OS << *I;
  619. if (*I == '$') {
  620. StringRef Name;
  621. std::tie(Name, I) = parseName(++I, E);
  622. assert(isOpMapped(Name) && "Unmapped operand!");
  623. int OpIndex, PrintIndex;
  624. std::tie(OpIndex, PrintIndex) = getOpData(Name);
  625. if (PrintIndex == -1) {
  626. // Can use the default printOperand route.
  627. OS << format("\\x%02X", (unsigned char)OpIndex + 1);
  628. } else
  629. // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
  630. // number, and which of our pre-detected Methods to call.
  631. OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
  632. } else {
  633. ++I;
  634. }
  635. }
  636. OS.flush();
  637. // Emit the string.
  638. O.indent(6) << "AsmString = \"" << OutString << "\";\n";
  639. O.indent(6) << "break;\n";
  640. O.indent(4) << '}';
  641. }
  642. bool operator==(const IAPrinter &RHS) {
  643. if (Conds.size() != RHS.Conds.size())
  644. return false;
  645. unsigned Idx = 0;
  646. for (std::vector<std::string>::iterator
  647. I = Conds.begin(), E = Conds.end(); I != E; ++I)
  648. if (*I != RHS.Conds[Idx++])
  649. return false;
  650. return true;
  651. }
  652. };
  653. } // end anonymous namespace
  654. static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
  655. std::string FlatAsmString =
  656. CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);
  657. AsmString = FlatAsmString;
  658. return AsmString.count(' ') + AsmString.count('\t');
  659. }
  660. namespace {
  661. struct AliasPriorityComparator {
  662. typedef std::pair<CodeGenInstAlias *, int> ValueType;
  663. bool operator()(const ValueType &LHS, const ValueType &RHS) const {
  664. if (LHS.second == RHS.second) {
  665. // We don't actually care about the order, but for consistency it
  666. // shouldn't depend on pointer comparisons.
  667. return LHS.first->TheDef->getName() < RHS.first->TheDef->getName();
  668. }
  669. // Aliases with larger priorities should be considered first.
  670. return LHS.second > RHS.second;
  671. }
  672. };
  673. }
  674. void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
  675. Record *AsmWriter = Target.getAsmWriter();
  676. O << "\n#ifdef PRINT_ALIAS_INSTR\n";
  677. O << "#undef PRINT_ALIAS_INSTR\n\n";
  678. //////////////////////////////
  679. // Gather information about aliases we need to print
  680. //////////////////////////////
  681. // Emit the method that prints the alias instruction.
  682. std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
  683. unsigned Variant = AsmWriter->getValueAsInt("Variant");
  684. unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
  685. std::vector<Record*> AllInstAliases =
  686. Records.getAllDerivedDefinitions("InstAlias");
  687. // Create a map from the qualified name to a list of potential matches.
  688. typedef std::set<std::pair<CodeGenInstAlias*, int>, AliasPriorityComparator>
  689. AliasWithPriority;
  690. std::map<std::string, AliasWithPriority> AliasMap;
  691. for (std::vector<Record*>::iterator
  692. I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
  693. CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Variant, Target);
  694. const Record *R = *I;
  695. int Priority = R->getValueAsInt("EmitPriority");
  696. if (Priority < 1)
  697. continue; // Aliases with priority 0 are never emitted.
  698. const DagInit *DI = R->getValueAsDag("ResultInst");
  699. const DefInit *Op = cast<DefInit>(DI->getOperator());
  700. AliasMap[getQualifiedName(Op->getDef())].insert(std::make_pair(Alias,
  701. Priority));
  702. }
  703. // A map of which conditions need to be met for each instruction operand
  704. // before it can be matched to the mnemonic.
  705. std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
  706. // A list of MCOperandPredicates for all operands in use, and the reverse map
  707. std::vector<const Record*> MCOpPredicates;
  708. DenseMap<const Record*, unsigned> MCOpPredicateMap;
  709. for (auto &Aliases : AliasMap) {
  710. for (auto &Alias : Aliases.second) {
  711. const CodeGenInstAlias *CGA = Alias.first;
  712. unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
  713. unsigned NumResultOps =
  714. CountNumOperands(CGA->ResultInst->AsmString, Variant);
  715. // Don't emit the alias if it has more operands than what it's aliasing.
  716. if (NumResultOps < CountNumOperands(CGA->AsmString, Variant))
  717. continue;
  718. IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
  719. CGA->AsmString);
  720. unsigned NumMIOps = 0;
  721. for (auto &Operand : CGA->ResultOperands)
  722. NumMIOps += Operand.getMINumOperands();
  723. std::string Cond;
  724. Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(NumMIOps);
  725. IAP->addCond(Cond);
  726. bool CantHandle = false;
  727. unsigned MIOpNum = 0;
  728. for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
  729. std::string Op = "MI->getOperand(" + llvm::utostr(MIOpNum) + ")";
  730. const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
  731. switch (RO.Kind) {
  732. case CodeGenInstAlias::ResultOperand::K_Record: {
  733. const Record *Rec = RO.getRecord();
  734. StringRef ROName = RO.getName();
  735. int PrintMethodIdx = -1;
  736. // These two may have a PrintMethod, which we want to record (if it's
  737. // the first time we've seen it) and provide an index for the aliasing
  738. // code to use.
  739. if (Rec->isSubClassOf("RegisterOperand") ||
  740. Rec->isSubClassOf("Operand")) {
  741. std::string PrintMethod = Rec->getValueAsString("PrintMethod");
  742. if (PrintMethod != "" && PrintMethod != "printOperand") {
  743. PrintMethodIdx = std::find(PrintMethods.begin(),
  744. PrintMethods.end(), PrintMethod) -
  745. PrintMethods.begin();
  746. if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
  747. PrintMethods.push_back(PrintMethod);
  748. }
  749. }
  750. if (Rec->isSubClassOf("RegisterOperand"))
  751. Rec = Rec->getValueAsDef("RegClass");
  752. if (Rec->isSubClassOf("RegisterClass")) {
  753. IAP->addCond(Op + ".isReg()");
  754. if (!IAP->isOpMapped(ROName)) {
  755. IAP->addOperand(ROName, MIOpNum, PrintMethodIdx);
  756. Record *R = CGA->ResultOperands[i].getRecord();
  757. if (R->isSubClassOf("RegisterOperand"))
  758. R = R->getValueAsDef("RegClass");
  759. Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
  760. R->getName() + "RegClassID)"
  761. ".contains(" + Op + ".getReg())";
  762. } else {
  763. Cond = Op + ".getReg() == MI->getOperand(" +
  764. llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
  765. }
  766. } else {
  767. // Assume all printable operands are desired for now. This can be
  768. // overridden in the InstAlias instantiation if necessary.
  769. IAP->addOperand(ROName, MIOpNum, PrintMethodIdx);
  770. // There might be an additional predicate on the MCOperand
  771. unsigned Entry = MCOpPredicateMap[Rec];
  772. if (!Entry) {
  773. if (!Rec->isValueUnset("MCOperandPredicate")) {
  774. MCOpPredicates.push_back(Rec);
  775. Entry = MCOpPredicates.size();
  776. MCOpPredicateMap[Rec] = Entry;
  777. } else
  778. break; // No conditions on this operand at all
  779. }
  780. Cond = Target.getName() + ClassName + "ValidateMCOperand(" +
  781. Op + ", " + llvm::utostr(Entry) + ")";
  782. }
  783. // for all subcases of ResultOperand::K_Record:
  784. IAP->addCond(Cond);
  785. break;
  786. }
  787. case CodeGenInstAlias::ResultOperand::K_Imm: {
  788. // Just because the alias has an immediate result, doesn't mean the
  789. // MCInst will. An MCExpr could be present, for example.
  790. IAP->addCond(Op + ".isImm()");
  791. Cond = Op + ".getImm() == "
  792. + llvm::utostr(CGA->ResultOperands[i].getImm());
  793. IAP->addCond(Cond);
  794. break;
  795. }
  796. case CodeGenInstAlias::ResultOperand::K_Reg:
  797. // If this is zero_reg, something's playing tricks we're not
  798. // equipped to handle.
  799. if (!CGA->ResultOperands[i].getRegister()) {
  800. CantHandle = true;
  801. break;
  802. }
  803. Cond = Op + ".getReg() == " + Target.getName() +
  804. "::" + CGA->ResultOperands[i].getRegister()->getName();
  805. IAP->addCond(Cond);
  806. break;
  807. }
  808. if (!IAP) break;
  809. MIOpNum += RO.getMINumOperands();
  810. }
  811. if (CantHandle) continue;
  812. IAPrinterMap[Aliases.first].push_back(IAP);
  813. }
  814. }
  815. //////////////////////////////
  816. // Write out the printAliasInstr function
  817. //////////////////////////////
  818. std::string Header;
  819. raw_string_ostream HeaderO(Header);
  820. HeaderO << "bool " << Target.getName() << ClassName
  821. << "::printAliasInstr(const MCInst"
  822. << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
  823. << "raw_ostream &OS) {\n";
  824. std::string Cases;
  825. raw_string_ostream CasesO(Cases);
  826. for (std::map<std::string, std::vector<IAPrinter*> >::iterator
  827. I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
  828. std::vector<IAPrinter*> &IAPs = I->second;
  829. std::vector<IAPrinter*> UniqueIAPs;
  830. for (std::vector<IAPrinter*>::iterator
  831. II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
  832. IAPrinter *LHS = *II;
  833. bool IsDup = false;
  834. for (std::vector<IAPrinter*>::iterator
  835. III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
  836. IAPrinter *RHS = *III;
  837. if (LHS != RHS && *LHS == *RHS) {
  838. IsDup = true;
  839. break;
  840. }
  841. }
  842. if (!IsDup) UniqueIAPs.push_back(LHS);
  843. }
  844. if (UniqueIAPs.empty()) continue;
  845. CasesO.indent(2) << "case " << I->first << ":\n";
  846. for (std::vector<IAPrinter*>::iterator
  847. II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
  848. IAPrinter *IAP = *II;
  849. CasesO.indent(4);
  850. IAP->print(CasesO);
  851. CasesO << '\n';
  852. }
  853. CasesO.indent(4) << "return false;\n";
  854. }
  855. if (CasesO.str().empty()) {
  856. O << HeaderO.str();
  857. O << " return false;\n";
  858. O << "}\n\n";
  859. O << "#endif // PRINT_ALIAS_INSTR\n";
  860. return;
  861. }
  862. if (!MCOpPredicates.empty())
  863. O << "static bool " << Target.getName() << ClassName
  864. << "ValidateMCOperand(\n"
  865. << " const MCOperand &MCOp, unsigned PredicateIndex);\n";
  866. O << HeaderO.str();
  867. O.indent(2) << "const char *AsmString;\n";
  868. O.indent(2) << "switch (MI->getOpcode()) {\n";
  869. O.indent(2) << "default: return false;\n";
  870. O << CasesO.str();
  871. O.indent(2) << "}\n\n";
  872. // Code that prints the alias, replacing the operands with the ones from the
  873. // MCInst.
  874. O << " unsigned I = 0;\n";
  875. O << " while (AsmString[I] != ' ' && AsmString[I] != '\t' &&\n";
  876. O << " AsmString[I] != '\\0')\n";
  877. O << " ++I;\n";
  878. O << " OS << '\\t' << StringRef(AsmString, I);\n";
  879. O << " if (AsmString[I] != '\\0') {\n";
  880. O << " OS << '\\t';\n";
  881. O << " do {\n";
  882. O << " if (AsmString[I] == '$') {\n";
  883. O << " ++I;\n";
  884. O << " if (AsmString[I] == (char)0xff) {\n";
  885. O << " ++I;\n";
  886. O << " int OpIdx = AsmString[I++] - 1;\n";
  887. O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
  888. O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
  889. O << (PassSubtarget ? "STI, " : "");
  890. O << "OS);\n";
  891. O << " } else\n";
  892. O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
  893. O << (PassSubtarget ? "STI, " : "");
  894. O << "OS);\n";
  895. O << " } else {\n";
  896. O << " OS << AsmString[I++];\n";
  897. O << " }\n";
  898. O << " } while (AsmString[I] != '\\0');\n";
  899. O << " }\n\n";
  900. O << " return true;\n";
  901. O << "}\n\n";
  902. //////////////////////////////
  903. // Write out the printCustomAliasOperand function
  904. //////////////////////////////
  905. O << "void " << Target.getName() << ClassName << "::"
  906. << "printCustomAliasOperand(\n"
  907. << " const MCInst *MI, unsigned OpIdx,\n"
  908. << " unsigned PrintMethodIdx,\n"
  909. << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "")
  910. << " raw_ostream &OS) {\n";
  911. if (PrintMethods.empty())
  912. O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
  913. else {
  914. O << " switch (PrintMethodIdx) {\n"
  915. << " default:\n"
  916. << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
  917. << " break;\n";
  918. for (unsigned i = 0; i < PrintMethods.size(); ++i) {
  919. O << " case " << i << ":\n"
  920. << " " << PrintMethods[i] << "(MI, OpIdx, "
  921. << (PassSubtarget ? "STI, " : "") << "OS);\n"
  922. << " break;\n";
  923. }
  924. O << " }\n";
  925. }
  926. O << "}\n\n";
  927. if (!MCOpPredicates.empty()) {
  928. O << "static bool " << Target.getName() << ClassName
  929. << "ValidateMCOperand(\n"
  930. << " const MCOperand &MCOp, unsigned PredicateIndex) {\n"
  931. << " switch (PredicateIndex) {\n"
  932. << " default:\n"
  933. << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
  934. << " break;\n";
  935. for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
  936. Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
  937. if (StringInit *SI = dyn_cast<StringInit>(MCOpPred)) {
  938. O << " case " << i + 1 << ": {\n"
  939. << SI->getValue() << "\n"
  940. << " }\n";
  941. } else
  942. llvm_unreachable("Unexpected MCOperandPredicate field!");
  943. }
  944. O << " }\n"
  945. << "}\n\n";
  946. }
  947. O << "#endif // PRINT_ALIAS_INSTR\n";
  948. }
  949. AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
  950. Record *AsmWriter = Target.getAsmWriter();
  951. for (const CodeGenInstruction *I : Target.instructions())
  952. if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
  953. Instructions.emplace_back(*I, AsmWriter->getValueAsInt("Variant"),
  954. AsmWriter->getValueAsInt("PassSubtarget"));
  955. // Get the instruction numbering.
  956. NumberedInstructions = &Target.getInstructionsByEnumValue();
  957. // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
  958. // all machine instructions are necessarily being printed, so there may be
  959. // target instructions not in this map.
  960. for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
  961. CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
  962. }
  963. void AsmWriterEmitter::run(raw_ostream &O) {
  964. EmitPrintInstruction(O);
  965. EmitGetRegisterName(O);
  966. EmitPrintAliasInstruction(O);
  967. }
  968. namespace llvm {
  969. void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
  970. emitSourceFileHeader("Assembly Writer Source Fragment", OS);
  971. AsmWriterEmitter(RK).run(OS);
  972. }
  973. } // End llvm namespace