CodeEmitterGen.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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.Map) {
  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.Map) {
  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 (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
  409. IC != EC; ++IC) {
  410. Record *R = *IC;
  411. if (R->getValueAsString("Namespace") == "TargetOpcode" ||
  412. R->getValueAsBit("isPseudo"))
  413. continue;
  414. std::string InstName =
  415. (R->getValueAsString("Namespace") + "::" + R->getName()).str();
  416. std::string Case = getInstructionCase(R, Target);
  417. CaseMap[Case].push_back(std::move(InstName));
  418. }
  419. // Emit initial function code
  420. if (UseAPInt) {
  421. int NumWords = APInt::getNumWords(BitWidth);
  422. int NumBytes = (BitWidth + 7) / 8;
  423. o << " const unsigned opcode = MI.getOpcode();\n"
  424. << " if (Inst.getBitWidth() != " << BitWidth << ")\n"
  425. << " Inst = Inst.zext(" << BitWidth << ");\n"
  426. << " if (Scratch.getBitWidth() != " << BitWidth << ")\n"
  427. << " Scratch = Scratch.zext(" << BitWidth << ");\n"
  428. << " LoadIntFromMemory(Inst, (uint8_t *)&InstBits[opcode * " << NumWords
  429. << "], " << NumBytes << ");\n"
  430. << " APInt &Value = Inst;\n"
  431. << " APInt &op = Scratch;\n"
  432. << " switch (opcode) {\n";
  433. } else {
  434. o << " const unsigned opcode = MI.getOpcode();\n"
  435. << " uint64_t Value = InstBits[opcode];\n"
  436. << " uint64_t op = 0;\n"
  437. << " (void)op; // suppress warning\n"
  438. << " switch (opcode) {\n";
  439. }
  440. // Emit each case statement
  441. std::map<std::string, std::vector<std::string>>::iterator IE, EE;
  442. for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
  443. const std::string &Case = IE->first;
  444. std::vector<std::string> &InstList = IE->second;
  445. for (int i = 0, N = InstList.size(); i < N; i++) {
  446. if (i) o << "\n";
  447. o << " case " << InstList[i] << ":";
  448. }
  449. o << " {\n";
  450. o << Case;
  451. o << " break;\n"
  452. << " }\n";
  453. }
  454. // Default case: unhandled opcode
  455. o << " default:\n"
  456. << " std::string msg;\n"
  457. << " raw_string_ostream Msg(msg);\n"
  458. << " Msg << \"Not supported instr: \" << MI;\n"
  459. << " report_fatal_error(Msg.str());\n"
  460. << " }\n";
  461. if (UseAPInt)
  462. o << " Inst = Value;\n";
  463. else
  464. o << " return Value;\n";
  465. o << "}\n\n";
  466. const auto &All = SubtargetFeatureInfo::getAll(Records);
  467. std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
  468. SubtargetFeatures.insert(All.begin(), All.end());
  469. o << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  470. << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n"
  471. << "#include <_llvm_sstream.h>\n\n";
  472. // Emit the subtarget feature enumeration.
  473. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
  474. o);
  475. // Emit the name table for error messages.
  476. o << "#ifndef NDEBUG\n";
  477. SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, o);
  478. o << "#endif // NDEBUG\n";
  479. // Emit the available features compute function.
  480. SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
  481. Target.getName(), "MCCodeEmitter", "computeAvailableFeatures",
  482. SubtargetFeatures, o);
  483. std::vector<std::vector<Record *>> FeatureBitsets;
  484. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  485. FeatureBitsets.emplace_back();
  486. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  487. const auto &I = SubtargetFeatures.find(Predicate);
  488. if (I != SubtargetFeatures.end())
  489. FeatureBitsets.back().push_back(I->second.TheDef);
  490. }
  491. }
  492. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  493. const std::vector<Record *> &B) {
  494. if (A.size() < B.size())
  495. return true;
  496. if (A.size() > B.size())
  497. return false;
  498. for (auto Pair : zip(A, B)) {
  499. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  500. return true;
  501. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  502. return false;
  503. }
  504. return false;
  505. });
  506. FeatureBitsets.erase(
  507. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  508. FeatureBitsets.end());
  509. o << "#ifndef NDEBUG\n"
  510. << "// Feature bitsets.\n"
  511. << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
  512. << " CEFBS_None,\n";
  513. for (const auto &FeatureBitset : FeatureBitsets) {
  514. if (FeatureBitset.empty())
  515. continue;
  516. o << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  517. }
  518. o << "};\n\n"
  519. << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
  520. << " {}, // CEFBS_None\n";
  521. for (const auto &FeatureBitset : FeatureBitsets) {
  522. if (FeatureBitset.empty())
  523. continue;
  524. o << " {";
  525. for (const auto &Feature : FeatureBitset) {
  526. const auto &I = SubtargetFeatures.find(Feature);
  527. assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
  528. o << I->second.getEnumBitName() << ", ";
  529. }
  530. o << "},\n";
  531. }
  532. o << "};\n"
  533. << "#endif // NDEBUG\n\n";
  534. // Emit the predicate verifier.
  535. o << "void " << Target.getName()
  536. << "MCCodeEmitter::verifyInstructionPredicates(\n"
  537. << " const MCInst &Inst, const FeatureBitset &AvailableFeatures) const {\n"
  538. << "#ifndef NDEBUG\n"
  539. << " static " << getMinimalTypeForRange(FeatureBitsets.size())
  540. << " RequiredFeaturesRefs[] = {\n";
  541. unsigned InstIdx = 0;
  542. for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
  543. o << " CEFBS";
  544. unsigned NumPredicates = 0;
  545. for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
  546. const auto &I = SubtargetFeatures.find(Predicate);
  547. if (I != SubtargetFeatures.end()) {
  548. o << '_' << I->second.TheDef->getName();
  549. NumPredicates++;
  550. }
  551. }
  552. if (!NumPredicates)
  553. o << "_None";
  554. o << ", // " << Inst->TheDef->getName() << " = " << InstIdx << "\n";
  555. InstIdx++;
  556. }
  557. o << " };\n\n";
  558. o << " assert(Inst.getOpcode() < " << InstIdx << ");\n";
  559. o << " const FeatureBitset &RequiredFeatures = "
  560. "FeatureBitsets[RequiredFeaturesRefs[Inst.getOpcode()]];\n";
  561. o << " FeatureBitset MissingFeatures =\n"
  562. << " (AvailableFeatures & RequiredFeatures) ^\n"
  563. << " RequiredFeatures;\n"
  564. << " if (MissingFeatures.any()) {\n"
  565. << " std::ostringstream Msg;\n"
  566. << " Msg << \"Attempting to emit \" << "
  567. "MCII.getName(Inst.getOpcode()).str()\n"
  568. << " << \" instruction but the \";\n"
  569. << " for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)\n"
  570. << " if (MissingFeatures.test(i))\n"
  571. << " Msg << SubtargetFeatureNames[i] << \" \";\n"
  572. << " Msg << \"predicate(s) are not met\";\n"
  573. << " report_fatal_error(Msg.str());\n"
  574. << " }\n"
  575. << "#else\n"
  576. << " // Silence unused variable warning on targets that don't use MCII for "
  577. "other purposes (e.g. BPF).\n"
  578. << " (void)MCII;\n"
  579. << "#endif // NDEBUG\n";
  580. o << "}\n";
  581. o << "#endif\n";
  582. }
  583. } // end anonymous namespace
  584. namespace llvm {
  585. void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
  586. emitSourceFileHeader("Machine Code Emitter", OS);
  587. CodeEmitterGen(RK).run(OS);
  588. }
  589. } // end namespace llvm