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