1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // CodeEmitterGen uses the descriptions of instructions and their fields to
11 // construct an automated code emitter: a function that, given a MachineInstr,
12 // returns the (currently, 32-bit unsigned) value of the instruction.
14 //===----------------------------------------------------------------------===//
16 #include "CodeGenInstruction.h"
17 #include "CodeGenTarget.h"
18 #include "SubtargetFeatureInfo.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"
37 class CodeEmitterGen {
38 RecordKeeper &Records;
41 CodeEmitterGen(RecordKeeper &R) : Records(R) {}
43 void run(raw_ostream &o);
46 int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
47 std::string getInstructionCase(Record *R, CodeGenTarget &Target);
48 void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
49 const std::string &VarName,
51 std::set<unsigned> &NamedOpIndices,
52 std::string &Case, CodeGenTarget &Target);
56 // If the VarBitInit at position 'bit' matches the specified variable then
57 // return the variable bit position. Otherwise return -1.
58 int CodeEmitterGen::getVariableBit(const std::string &VarName,
59 BitsInit *BI, int bit) {
60 if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) {
61 if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar()))
62 if (VI->getName() == VarName)
63 return VBI->getBitNum();
64 } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) {
65 if (VI->getName() == VarName)
73 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
75 std::set<unsigned> &NamedOpIndices,
76 std::string &Case, CodeGenTarget &Target) {
77 CodeGenInstruction &CGI = Target.getInstruction(R);
79 // Determine if VarName actually contributes to the Inst encoding.
80 int bit = BI->getNumBits()-1;
82 // Scan for a bit that this contributed to.
84 if (getVariableBit(VarName, BI, bit) != -1)
90 // If we found no bits, ignore this value, otherwise emit the call to get the
94 // If the operand matches by name, reference according to that
95 // operand number. Non-matching operands are assumed to be in
98 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
99 // Get the machine operand number for the indicated operand.
100 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
101 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
102 "Explicitly used operand also marked as not emitted!");
104 unsigned NumberOps = CGI.Operands.size();
105 /// If this operand is not supposed to be emitted by the
106 /// generated emitter, skip it.
107 while (NumberedOp < NumberOps &&
108 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
109 (!NamedOpIndices.empty() && NamedOpIndices.count(
110 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) {
113 if (NumberedOp >= CGI.Operands.back().MIOperandNo +
114 CGI.Operands.back().MINumOperands) {
115 errs() << "Too few operands in record " << R->getName() <<
116 " (no match for variable " << VarName << "):\n";
124 OpIdx = NumberedOp++;
127 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
128 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
130 // If the source operand has a custom encoder, use it. This will
131 // get the encoding for all of the suboperands.
132 if (!EncoderMethodName.empty()) {
133 // A custom encoder has all of the information for the
134 // sub-operands, if there are more than one, so only
135 // query the encoder once per source operand.
136 if (SO.second == 0) {
137 Case += " // op: " + VarName + "\n" +
138 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
139 Case += ", Fixups, STI";
143 Case += " // op: " + VarName + "\n" +
144 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
145 Case += ", Fixups, STI";
150 int varBit = getVariableBit(VarName, BI, bit);
152 // If this bit isn't from a variable, skip it.
158 // Figure out the consecutive range of bits covered by this operand, in
159 // order to generate better encoding code.
160 int beginInstBit = bit;
161 int beginVarBit = varBit;
163 for (--bit; bit >= 0;) {
164 varBit = getVariableBit(VarName, BI, bit);
165 if (varBit == -1 || varBit != (beginVarBit - N)) break;
170 uint64_t opMask = ~(uint64_t)0 >> (64-N);
171 int opShift = beginVarBit - N + 1;
173 opShift = beginInstBit - beginVarBit;
176 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
177 itostr(opShift) + ";\n";
178 } else if (opShift < 0) {
179 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
180 itostr(-opShift) + ";\n";
182 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
187 std::string CodeEmitterGen::getInstructionCase(Record *R,
188 CodeGenTarget &Target) {
190 BitsInit *BI = R->getValueAsBitsInit("Inst");
191 unsigned NumberedOp = 0;
192 std::set<unsigned> NamedOpIndices;
194 // Collect the set of operand indices that might correspond to named
195 // operand, and skip these when assigning operands based on position.
196 if (Target.getInstructionSet()->
197 getValueAsBit("noNamedPositionallyEncodedOperands")) {
198 CodeGenInstruction &CGI = Target.getInstruction(R);
199 for (const RecordVal &RV : R->getValues()) {
201 if (!CGI.Operands.hasOperandNamed(RV.getName(), OpIdx))
204 NamedOpIndices.insert(OpIdx);
208 // Loop over all of the fields in the instruction, determining which are the
209 // operands to the instruction.
210 for (const RecordVal &RV : R->getValues()) {
211 // Ignore fixed fields in the record, we're looking for values like:
212 // bits<5> RST = { ?, ?, ?, ?, ? };
213 if (RV.getPrefix() || RV.getValue()->isComplete())
216 AddCodeToMergeInOperand(R, BI, RV.getName(), NumberedOp,
217 NamedOpIndices, Case, Target);
220 StringRef PostEmitter = R->getValueAsString("PostEncoderMethod");
221 if (!PostEmitter.empty()) {
224 Case += "(MI, Value";
232 void CodeEmitterGen::run(raw_ostream &o) {
233 CodeGenTarget Target(Records);
234 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
236 // For little-endian instruction bit encodings, reverse the bit order
237 Target.reverseBitsForLittleEndianEncoding();
239 ArrayRef<const CodeGenInstruction*> NumberedInstructions =
240 Target.getInstructionsByEnumValue();
242 // Emit function declaration
243 o << "uint64_t " << Target.getName();
244 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
245 << " SmallVectorImpl<MCFixup> &Fixups,\n"
246 << " const MCSubtargetInfo &STI) const {\n";
248 // Emit instruction base values
249 o << " static const uint64_t InstBits[] = {\n";
250 for (const CodeGenInstruction *CGI : NumberedInstructions) {
251 Record *R = CGI->TheDef;
253 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
254 R->getValueAsBit("isPseudo")) {
255 o << " UINT64_C(0),\n";
259 BitsInit *BI = R->getValueAsBitsInit("Inst");
261 // Start by filling in fixed values.
263 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
264 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1)))
265 Value |= (uint64_t)B->getValue() << (e-i-1);
267 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
269 o << " UINT64_C(0)\n };\n";
271 // Map to accumulate all the cases.
272 std::map<std::string, std::vector<std::string>> CaseMap;
274 // Construct all cases statement for each opcode
275 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
278 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
279 R->getValueAsBit("isPseudo"))
281 std::string InstName =
282 (R->getValueAsString("Namespace") + "::" + R->getName()).str();
283 std::string Case = getInstructionCase(R, Target);
285 CaseMap[Case].push_back(std::move(InstName));
288 // Emit initial function code
289 o << " const unsigned opcode = MI.getOpcode();\n"
290 << " uint64_t Value = InstBits[opcode];\n"
291 << " uint64_t op = 0;\n"
292 << " (void)op; // suppress warning\n"
293 << " switch (opcode) {\n";
295 // Emit each case statement
296 std::map<std::string, std::vector<std::string>>::iterator IE, EE;
297 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
298 const std::string &Case = IE->first;
299 std::vector<std::string> &InstList = IE->second;
301 for (int i = 0, N = InstList.size(); i < N; i++) {
303 o << " case " << InstList[i] << ":";
311 // Default case: unhandled opcode
313 << " std::string msg;\n"
314 << " raw_string_ostream Msg(msg);\n"
315 << " Msg << \"Not supported instr: \" << MI;\n"
316 << " report_fatal_error(Msg.str());\n"
318 << " return Value;\n"
321 const auto &All = SubtargetFeatureInfo::getAll(Records);
322 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
323 SubtargetFeatures.insert(All.begin(), All.end());
325 o << "#ifdef ENABLE_INSTR_PREDICATE_VERIFIER\n"
326 << "#undef ENABLE_INSTR_PREDICATE_VERIFIER\n"
327 << "#include <sstream>\n\n";
329 // Emit the subtarget feature enumeration.
330 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(SubtargetFeatures,
333 // Emit the name table for error messages.
334 o << "#ifndef NDEBUG\n";
335 SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, o);
336 o << "#endif // NDEBUG\n";
338 // Emit the available features compute function.
339 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
340 Target.getName(), "MCCodeEmitter", "computeAvailableFeatures",
341 SubtargetFeatures, o);
343 // Emit the predicate verifier.
344 o << "void " << Target.getName()
345 << "MCCodeEmitter::verifyInstructionPredicates(\n"
346 << " const MCInst &Inst, uint64_t AvailableFeatures) const {\n"
347 << "#ifndef NDEBUG\n"
348 << " static uint64_t RequiredFeatures[] = {\n";
349 unsigned InstIdx = 0;
350 for (const CodeGenInstruction *Inst : Target.getInstructionsByEnumValue()) {
352 for (Record *Predicate : Inst->TheDef->getValueAsListOfDefs("Predicates")) {
353 const auto &I = SubtargetFeatures.find(Predicate);
354 if (I != SubtargetFeatures.end())
355 o << I->second.getEnumName() << " | ";
357 o << "0, // " << Inst->TheDef->getName() << " = " << InstIdx << "\n";
361 o << " assert(Inst.getOpcode() < " << InstIdx << ");\n";
362 o << " uint64_t MissingFeatures =\n"
363 << " (AvailableFeatures & RequiredFeatures[Inst.getOpcode()]) ^\n"
364 << " RequiredFeatures[Inst.getOpcode()];\n"
365 << " if (MissingFeatures) {\n"
366 << " std::ostringstream Msg;\n"
367 << " Msg << \"Attempting to emit \" << "
368 "MCII.getName(Inst.getOpcode()).str()\n"
369 << " << \" instruction but the \";\n"
370 << " for (unsigned i = 0; i < 8 * sizeof(MissingFeatures); ++i)\n"
371 << " if (MissingFeatures & (1ULL << i))\n"
372 << " Msg << SubtargetFeatureNames[i] << \" \";\n"
373 << " Msg << \"predicate(s) are not met\";\n"
374 << " report_fatal_error(Msg.str());\n"
377 << "// Silence unused variable warning on targets that don't use MCII for "
378 "other purposes (e.g. BPF).\n"
380 << "#endif // NDEBUG\n";
385 } // end anonymous namespace
389 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
390 emitSourceFileHeader("Machine Code Emitter", OS);
391 CodeEmitterGen(RK).run(OS);
394 } // end namespace llvm