CodeEmitterGen.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
  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. // CodeEmitterGen uses the descriptions of instructions and their fields to
  10. // construct an automated code emitter: a function that, given a MachineInstr,
  11. // returns the (currently, 32-bit unsigned) value of the instruction.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenInstruction.h"
  15. #include "CodeGenTarget.h"
  16. #include "SubtargetFeatureInfo.h"
  17. #include "Types.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/Support/Casting.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include "llvm/TableGen/Record.h"
  24. #include "llvm/TableGen/TableGenBackend.h"
  25. #include <cassert>
  26. #include <cstdint>
  27. #include <map>
  28. #include <set>
  29. #include <string>
  30. #include <utility>
  31. #include <vector>
  32. using namespace llvm;
  33. namespace {
  34. class CodeEmitterGen {
  35. RecordKeeper &Records;
  36. public:
  37. CodeEmitterGen(RecordKeeper &R) : Records(R) {}
  38. void run(raw_ostream &o);
  39. private:
  40. int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
  41. std::string getInstructionCase(Record *R, CodeGenTarget &Target);
  42. std::string getInstructionCaseForEncoding(Record *R, Record *EncodingDef,
  43. CodeGenTarget &Target);
  44. void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
  45. const std::string &VarName,
  46. unsigned &NumberedOp,
  47. std::set<unsigned> &NamedOpIndices,
  48. std::string &Case, CodeGenTarget &Target);
  49. void emitInstructionBaseValues(
  50. raw_ostream &o, ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  51. CodeGenTarget &Target, int HwMode = -1);
  52. unsigned BitWidth;
  53. bool UseAPInt;
  54. };
  55. // If the VarBitInit at position 'bit' matches the specified variable then
  56. // return the variable bit position. Otherwise return -1.
  57. int CodeEmitterGen::getVariableBit(const std::string &VarName,
  58. BitsInit *BI, int bit) {
  59. if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) {
  60. if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar()))
  61. if (VI->getName() == VarName)
  62. return VBI->getBitNum();
  63. } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) {
  64. if (VI->getName() == VarName)
  65. return 0;
  66. }
  67. return -1;
  68. }
  69. void CodeEmitterGen::
  70. AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
  71. unsigned &NumberedOp,
  72. std::set<unsigned> &NamedOpIndices,
  73. std::string &Case, CodeGenTarget &Target) {
  74. CodeGenInstruction &CGI = Target.getInstruction(R);
  75. // Determine if VarName actually contributes to the Inst encoding.
  76. int bit = BI->getNumBits()-1;
  77. // Scan for a bit that this contributed to.
  78. for (; bit >= 0; ) {
  79. if (getVariableBit(VarName, BI, bit) != -1)
  80. break;
  81. --bit;
  82. }
  83. // If we found no bits, ignore this value, otherwise emit the call to get the
  84. // operand encoding.
  85. if (bit < 0) return;
  86. // If the operand matches by name, reference according to that
  87. // operand number. Non-matching operands are assumed to be in
  88. // order.
  89. unsigned OpIdx;
  90. if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
  91. // Get the machine operand number for the indicated operand.
  92. OpIdx = CGI.Operands[OpIdx].MIOperandNo;
  93. assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
  94. "Explicitly used operand also marked as not emitted!");
  95. } else {
  96. unsigned NumberOps = CGI.Operands.size();
  97. /// If this operand is not supposed to be emitted by the
  98. /// generated emitter, skip it.
  99. while (NumberedOp < NumberOps &&
  100. (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
  101. (!NamedOpIndices.empty() && NamedOpIndices.count(
  102. CGI.Operands.getSubOperandNumber(NumberedOp).first)))) {
  103. ++NumberedOp;
  104. if (NumberedOp >= CGI.Operands.back().MIOperandNo +
  105. CGI.Operands.back().MINumOperands) {
  106. errs() << "Too few operands in record " << R->getName() <<
  107. " (no match for variable " << VarName << "):\n";
  108. errs() << *R;
  109. errs() << '\n';
  110. return;
  111. }
  112. }
  113. OpIdx = NumberedOp++;
  114. }
  115. std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
  116. std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
  117. if (UseAPInt)
  118. Case += " op.clearAllBits();\n";
  119. // If the source operand has a custom encoder, use it. This will
  120. // get the encoding for all of the suboperands.
  121. if (!EncoderMethodName.empty()) {
  122. // A custom encoder has all of the information for the
  123. // sub-operands, if there are more than one, so only
  124. // query the encoder once per source operand.
  125. if (SO.second == 0) {
  126. Case += " // op: " + VarName + "\n";
  127. if (UseAPInt) {
  128. Case += " " + EncoderMethodName + "(MI, " + utostr(OpIdx);
  129. Case += ", op";
  130. } else {
  131. Case += " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
  132. }
  133. Case += ", Fixups, STI);\n";
  134. }
  135. } else {
  136. Case += " // op: " + VarName + "\n";
  137. if (UseAPInt) {
  138. Case += " getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
  139. Case += ", op, Fixups, STI";
  140. } else {
  141. Case += " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
  142. Case += ", Fixups, STI";
  143. }
  144. Case += ");\n";
  145. }
  146. // Precalculate the number of lits this variable contributes to in the
  147. // operand. If there is a single lit (consecutive range of bits) we can use a
  148. // destructive sequence on APInt that reduces memory allocations.
  149. int numOperandLits = 0;
  150. for (int tmpBit = bit; tmpBit >= 0;) {
  151. int varBit = getVariableBit(VarName, BI, tmpBit);
  152. // If this bit isn't from a variable, skip it.
  153. if (varBit == -1) {
  154. --tmpBit;
  155. continue;
  156. }
  157. // Figure out the consecutive range of bits covered by this operand, in
  158. // order to generate better encoding code.
  159. int beginVarBit = varBit;
  160. int N = 1;
  161. for (--tmpBit; tmpBit >= 0;) {
  162. varBit = getVariableBit(VarName, BI, tmpBit);
  163. if (varBit == -1 || varBit != (beginVarBit - N))
  164. break;
  165. ++N;
  166. --tmpBit;
  167. }
  168. ++numOperandLits;
  169. }
  170. for (; bit >= 0; ) {
  171. int varBit = getVariableBit(VarName, BI, bit);
  172. // If this bit isn't from a variable, skip it.
  173. if (varBit == -1) {
  174. --bit;
  175. continue;
  176. }
  177. // Figure out the consecutive range of bits covered by this operand, in
  178. // order to generate better encoding code.
  179. int beginInstBit = bit;
  180. int beginVarBit = varBit;
  181. int N = 1;
  182. for (--bit; bit >= 0;) {
  183. varBit = getVariableBit(VarName, BI, bit);
  184. if (varBit == -1 || varBit != (beginVarBit - N)) break;
  185. ++N;
  186. --bit;
  187. }
  188. std::string maskStr;
  189. int opShift;
  190. unsigned loBit = beginVarBit - N + 1;
  191. unsigned hiBit = loBit + N;
  192. unsigned loInstBit = beginInstBit - N + 1;
  193. if (UseAPInt) {
  194. std::string extractStr;
  195. if (N >= 64) {
  196. extractStr = "op.extractBits(" + itostr(hiBit - loBit) + ", " +
  197. itostr(loBit) + ")";
  198. Case += " Value.insertBits(" + extractStr + ", " +
  199. itostr(loInstBit) + ");\n";
  200. } else {
  201. extractStr = "op.extractBitsAsZExtValue(" + itostr(hiBit - loBit) +
  202. ", " + itostr(loBit) + ")";
  203. Case += " Value.insertBits(" + extractStr + ", " +
  204. itostr(loInstBit) + ", " + itostr(hiBit - loBit) + ");\n";
  205. }
  206. } else {
  207. uint64_t opMask = ~(uint64_t)0 >> (64 - N);
  208. opShift = beginVarBit - N + 1;
  209. opMask <<= opShift;
  210. maskStr = "UINT64_C(" + utostr(opMask) + ")";
  211. opShift = beginInstBit - beginVarBit;
  212. if (numOperandLits == 1) {
  213. Case += " op &= " + maskStr + ";\n";
  214. if (opShift > 0) {
  215. Case += " op <<= " + itostr(opShift) + ";\n";
  216. } else if (opShift < 0) {
  217. Case += " op >>= " + itostr(-opShift) + ";\n";
  218. }
  219. Case += " Value |= op;\n";
  220. } else {
  221. if (opShift > 0) {
  222. Case += " Value |= (op & " + maskStr + ") << " +
  223. itostr(opShift) + ";\n";
  224. } else if (opShift < 0) {
  225. Case += " Value |= (op & " + maskStr + ") >> " +
  226. itostr(-opShift) + ";\n";
  227. } else {
  228. Case += " Value |= (op & " + maskStr + ");\n";
  229. }
  230. }
  231. }
  232. }
  233. }
  234. std::string CodeEmitterGen::getInstructionCase(Record *R,
  235. CodeGenTarget &Target) {
  236. std::string Case;
  237. if (const RecordVal *RV = R->getValue("EncodingInfos")) {
  238. if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
  239. const CodeGenHwModes &HWM = Target.getHwModes();
  240. EncodingInfoByHwMode EBM(DI->getDef(), HWM);
  241. Case += " switch (HwMode) {\n";
  242. Case += " default: llvm_unreachable(\"Unhandled HwMode\");\n";
  243. for (auto &KV : EBM) {
  244. Case += " case " + itostr(KV.first) + ": {\n";
  245. Case += getInstructionCaseForEncoding(R, KV.second, Target);
  246. Case += " break;\n";
  247. Case += " }\n";
  248. }
  249. Case += " }\n";
  250. return Case;
  251. }
  252. }
  253. return getInstructionCaseForEncoding(R, R, Target);
  254. }
  255. std::string CodeEmitterGen::getInstructionCaseForEncoding(Record *R, Record *EncodingDef,
  256. CodeGenTarget &Target) {
  257. std::string Case;
  258. BitsInit *BI = EncodingDef->getValueAsBitsInit("Inst");
  259. unsigned NumberedOp = 0;
  260. std::set<unsigned> NamedOpIndices;
  261. // Collect the set of operand indices that might correspond to named
  262. // operand, and skip these when assigning operands based on position.
  263. if (Target.getInstructionSet()->
  264. getValueAsBit("noNamedPositionallyEncodedOperands")) {
  265. CodeGenInstruction &CGI = Target.getInstruction(R);
  266. for (const RecordVal &RV : R->getValues()) {
  267. unsigned OpIdx;
  268. if (!CGI.Operands.hasOperandNamed(RV.getName(), OpIdx))
  269. continue;
  270. NamedOpIndices.insert(OpIdx);
  271. }
  272. }
  273. // Loop over all of the fields in the instruction, determining which are the
  274. // operands to the instruction.
  275. for (const RecordVal &RV : EncodingDef->getValues()) {
  276. // Ignore fixed fields in the record, we're looking for values like:
  277. // bits<5> RST = { ?, ?, ?, ?, ? };
  278. if (RV.isNonconcreteOK() || RV.getValue()->isComplete())
  279. continue;
  280. AddCodeToMergeInOperand(R, BI, std::string(RV.getName()), NumberedOp,
  281. NamedOpIndices, Case, Target);
  282. }
  283. StringRef PostEmitter = R->getValueAsString("PostEncoderMethod");
  284. if (!PostEmitter.empty()) {
  285. Case += " Value = ";
  286. Case += PostEmitter;
  287. Case += "(MI, Value";
  288. Case += ", STI";
  289. Case += ");\n";
  290. }
  291. return Case;
  292. }
  293. static std::string
  294. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  295. std::string Name = "CEFBS";
  296. for (const auto &Feature : FeatureBitset)
  297. Name += ("_" + Feature->getName()).str();
  298. return Name;
  299. }
  300. static void emitInstBits(raw_ostream &OS, const APInt &Bits) {
  301. for (unsigned I = 0; I < Bits.getNumWords(); ++I)
  302. OS << ((I > 0) ? ", " : "") << "UINT64_C(" << utostr(Bits.getRawData()[I])
  303. << ")";
  304. }
  305. void CodeEmitterGen::emitInstructionBaseValues(
  306. raw_ostream &o, ArrayRef<const CodeGenInstruction *> NumberedInstructions,
  307. CodeGenTarget &Target, int HwMode) {
  308. const CodeGenHwModes &HWM = Target.getHwModes();
  309. if (HwMode == -1)
  310. o << " static const uint64_t InstBits[] = {\n";
  311. else
  312. o << " static const uint64_t InstBits_" << HWM.getMode(HwMode).Name
  313. << "[] = {\n";
  314. for (const CodeGenInstruction *CGI : NumberedInstructions) {
  315. Record *R = CGI->TheDef;
  316. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  317. R->getValueAsBit("isPseudo")) {
  318. o << " "; emitInstBits(o, APInt(BitWidth, 0)); o << ",\n";
  319. continue;
  320. }
  321. Record *EncodingDef = R;
  322. if (const RecordVal *RV = R->getValue("EncodingInfos")) {
  323. if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
  324. EncodingInfoByHwMode EBM(DI->getDef(), HWM);
  325. if (EBM.hasMode(HwMode))
  326. EncodingDef = EBM.get(HwMode);
  327. }
  328. }
  329. BitsInit *BI = EncodingDef->getValueAsBitsInit("Inst");
  330. // Start by filling in fixed values.
  331. APInt Value(BitWidth, 0);
  332. for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
  333. if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e - i - 1)))
  334. Value |= APInt(BitWidth, (uint64_t)B->getValue()) << (e - i - 1);
  335. }
  336. o << " ";
  337. emitInstBits(o, Value);
  338. o << "," << '\t' << "// " << R->getName() << "\n";
  339. }
  340. o << " UINT64_C(0)\n };\n";
  341. }
  342. void CodeEmitterGen::run(raw_ostream &o) {
  343. CodeGenTarget Target(Records);
  344. std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
  345. // For little-endian instruction bit encodings, reverse the bit order
  346. Target.reverseBitsForLittleEndianEncoding();
  347. ArrayRef<const CodeGenInstruction*> NumberedInstructions =
  348. Target.getInstructionsByEnumValue();
  349. const CodeGenHwModes &HWM = Target.getHwModes();
  350. // The set of HwModes used by instruction encodings.
  351. std::set<unsigned> HwModes;
  352. BitWidth = 0;
  353. for (const CodeGenInstruction *CGI : NumberedInstructions) {
  354. Record *R = CGI->TheDef;
  355. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  356. R->getValueAsBit("isPseudo"))
  357. continue;
  358. if (const RecordVal *RV = R->getValue("EncodingInfos")) {
  359. if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
  360. EncodingInfoByHwMode EBM(DI->getDef(), HWM);
  361. for (auto &KV : EBM) {
  362. BitsInit *BI = KV.second->getValueAsBitsInit("Inst");
  363. BitWidth = std::max(BitWidth, BI->getNumBits());
  364. HwModes.insert(KV.first);
  365. }
  366. continue;
  367. }
  368. }
  369. BitsInit *BI = R->getValueAsBitsInit("Inst");
  370. BitWidth = std::max(BitWidth, BI->getNumBits());
  371. }
  372. UseAPInt = BitWidth > 64;
  373. // Emit function declaration
  374. if (UseAPInt) {
  375. o << "void " << Target.getName()
  376. << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
  377. << " SmallVectorImpl<MCFixup> &Fixups,\n"
  378. << " APInt &Inst,\n"
  379. << " APInt &Scratch,\n"
  380. << " const MCSubtargetInfo &STI) const {\n";
  381. } else {
  382. o << "uint64_t " << Target.getName();
  383. o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
  384. << " SmallVectorImpl<MCFixup> &Fixups,\n"
  385. << " const MCSubtargetInfo &STI) const {\n";
  386. }
  387. // Emit instruction base values
  388. if (HwModes.empty()) {
  389. emitInstructionBaseValues(o, NumberedInstructions, Target, -1);
  390. } else {
  391. for (unsigned HwMode : HwModes)
  392. emitInstructionBaseValues(o, NumberedInstructions, Target, (int)HwMode);
  393. }
  394. if (!HwModes.empty()) {
  395. o << " const uint64_t *InstBits;\n";
  396. o << " unsigned HwMode = STI.getHwMode();\n";
  397. o << " switch (HwMode) {\n";
  398. o << " default: llvm_unreachable(\"Unknown hardware mode!\"); break;\n";
  399. for (unsigned I : HwModes) {
  400. o << " case " << I << ": InstBits = InstBits_" << HWM.getMode(I).Name
  401. << "; break;\n";
  402. }
  403. o << " };\n";
  404. }
  405. // Map to accumulate all the cases.
  406. std::map<std::string, std::vector<std::string>> CaseMap;
  407. // Construct all cases statement for each opcode
  408. for (Record *R : Insts) {
  409. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  410. R->getValueAsBit("isPseudo"))
  411. continue;
  412. std::string InstName =
  413. (R->getValueAsString("Namespace") + "::" + R->getName()).str();
  414. std::string Case = getInstructionCase(R, Target);
  415. CaseMap[Case].push_back(std::move(InstName));
  416. }
  417. // Emit initial function code
  418. if (UseAPInt) {
  419. int NumWords = APInt::getNumWords(BitWidth);
  420. int NumBytes = (BitWidth + 7) / 8;
  421. o << " const unsigned opcode = MI.getOpcode();\n"
  422. << " if (Inst.getBitWidth() != " << BitWidth << ")\n"
  423. << " Inst = Inst.zext(" << BitWidth << ");\n"
  424. << " if (Scratch.getBitWidth() != " << BitWidth << ")\n"
  425. << " Scratch = Scratch.zext(" << BitWidth << ");\n"
  426. << " LoadIntFromMemory(Inst, (const uint8_t *)&InstBits[opcode * "
  427. << NumWords << "], " << NumBytes << ");\n"
  428. << " APInt &Value = Inst;\n"
  429. << " APInt &op = Scratch;\n"
  430. << " switch (opcode) {\n";
  431. } else {
  432. o << " const unsigned opcode = MI.getOpcode();\n"
  433. << " uint64_t Value = InstBits[opcode];\n"
  434. << " uint64_t op = 0;\n"
  435. << " (void)op; // suppress warning\n"
  436. << " switch (opcode) {\n";
  437. }
  438. // Emit each case statement
  439. std::map<std::string, std::vector<std::string>>::iterator IE, EE;
  440. for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
  441. const std::string &Case = IE->first;
  442. std::vector<std::string> &InstList = IE->second;
  443. for (int i = 0, N = InstList.size(); i < N; i++) {
  444. if (i) o << "\n";
  445. o << " case " << InstList[i] << ":";
  446. }
  447. o << " {\n";
  448. o << Case;
  449. o << " break;\n"
  450. << " }\n";
  451. }
  452. // Default case: unhandled opcode
  453. o << " default:\n"
  454. << " std::string msg;\n"
  455. << " raw_string_ostream Msg(msg);\n"
  456. << " Msg << \"Not supported instr: \" << MI;\n"
  457. << " report_fatal_error(msg.c_str());\n"
  458. << " }\n";
  459. if (UseAPInt)
  460. o << " Inst = Value;\n";
  461. else
  462. o << " return Value;\n";
  463. o << "}\n\n";
  464. const auto &All = SubtargetFeatureInfo::getAll(Records);
  465. std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
  466. SubtargetFeatures.insert(All.begin(), All.end());
  467. o << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  468. << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  469. << "#include <_llvm_sstream.h>\n\n";
  470. // Emit the subtarget feature enumeration.
  471. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
  472. o);
  473. // Emit the name table for error messages.
  474. o << "#ifndef NDEBUG\n";
  475. SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, o);
  476. o << "#endif // NDEBUG\n";
  477. // Emit the available features compute function.
  478. SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
  479. Target.getName(), "MCCodeEmitter", "computeAvailableFeatures",
  480. SubtargetFeatures, o);
  481. std::vector<std::vector<Record *>> FeatureBitsets;
  482. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  483. FeatureBitsets.emplace_back();
  484. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  485. const auto &I = SubtargetFeatures.find(Predicate);
  486. if (I != SubtargetFeatures.end())
  487. FeatureBitsets.back().push_back(I->second.TheDef);
  488. }
  489. }
  490. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  491. const std::vector<Record *> &B) {
  492. if (A.size() < B.size())
  493. return true;
  494. if (A.size() > B.size())
  495. return false;
  496. for (auto Pair : zip(A, B)) {
  497. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  498. return true;
  499. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  500. return false;
  501. }
  502. return false;
  503. });
  504. FeatureBitsets.erase(
  505. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  506. FeatureBitsets.end());
  507. o << "#ifndef NDEBUG\n"
  508. << "// Feature bitsets.\n"
  509. << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
  510. << " CEFBS_None,\n";
  511. for (const auto &FeatureBitset : FeatureBitsets) {
  512. if (FeatureBitset.empty())
  513. continue;
  514. o << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  515. }
  516. o << "};\n\n"
  517. << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
  518. << " {}, // CEFBS_None\n";
  519. for (const auto &FeatureBitset : FeatureBitsets) {
  520. if (FeatureBitset.empty())
  521. continue;
  522. o << " {";
  523. for (const auto &Feature : FeatureBitset) {
  524. const auto &I = SubtargetFeatures.find(Feature);
  525. assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
  526. o << I->second.getEnumBitName() << ", ";
  527. }
  528. o << "},\n";
  529. }
  530. o << "};\n"
  531. << "#endif // NDEBUG\n\n";
  532. // Emit the predicate verifier.
  533. o << "void " << Target.getName()
  534. << "MCCodeEmitter::verifyInstructionPredicates(\n"
  535. << " const MCInst &Inst, const FeatureBitset &AvailableFeatures) const {\n"
  536. << "#ifndef NDEBUG\n"
  537. << " static " << getMinimalTypeForRange(FeatureBitsets.size())
  538. << " RequiredFeaturesRefs[] = {\n";
  539. unsigned InstIdx = 0;
  540. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  541. o << " CEFBS";
  542. unsigned NumPredicates = 0;
  543. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  544. const auto &I = SubtargetFeatures.find(Predicate);
  545. if (I != SubtargetFeatures.end()) {
  546. o << '_' << I->second.TheDef->getName();
  547. NumPredicates++;
  548. }
  549. }
  550. if (!NumPredicates)
  551. o << "_None";
  552. o << ", // " << Inst->TheDef->getName() << " = " << InstIdx << "\n";
  553. InstIdx++;
  554. }
  555. o << " };\n\n";
  556. o << " assert(Inst.getOpcode() < " << InstIdx << ");\n";
  557. o << " const FeatureBitset &RequiredFeatures = "
  558. "FeatureBitsets[RequiredFeaturesRefs[Inst.getOpcode()]];\n";
  559. o << " FeatureBitset MissingFeatures =\n"
  560. << " (AvailableFeatures & RequiredFeatures) ^\n"
  561. << " RequiredFeatures;\n"
  562. << " if (MissingFeatures.any()) {\n"
  563. << " std::ostringstream Msg;\n"
  564. << " Msg << \"Attempting to emit \" << "
  565. "MCII.getName(Inst.getOpcode()).str()\n"
  566. << " << \" instruction but the \";\n"
  567. << " for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)\n"
  568. << " if (MissingFeatures.test(i))\n"
  569. << " Msg << SubtargetFeatureNames[i] << \" \";\n"
  570. << " Msg << \"predicate(s) are not met\";\n"
  571. << " report_fatal_error(Msg.str().c_str());\n"
  572. << " }\n"
  573. << "#else\n"
  574. << " // Silence unused variable warning on targets that don't use MCII for "
  575. "other purposes (e.g. BPF).\n"
  576. << " (void)MCII;\n"
  577. << "#endif // NDEBUG\n";
  578. o << "}\n";
  579. o << "#endif\n";
  580. }
  581. } // end anonymous namespace
  582. namespace llvm {
  583. void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
  584. emitSourceFileHeader("Machine Code Emitter", OS);
  585. CodeEmitterGen(RK).run(OS);
  586. }
  587. } // end namespace llvm