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 "CodeGenTarget.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/TableGenBackend.h"
29 class CodeEmitterGen {
30 RecordKeeper &Records;
32 CodeEmitterGen(RecordKeeper &R) : Records(R) {}
34 void run(raw_ostream &o);
36 int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
37 std::string getInstructionCase(Record *R, CodeGenTarget &Target);
38 void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
39 const std::string &VarName,
41 std::set<unsigned> &NamedOpIndices,
42 std::string &Case, CodeGenTarget &Target);
46 // If the VarBitInit at position 'bit' matches the specified variable then
47 // return the variable bit position. Otherwise return -1.
48 int CodeEmitterGen::getVariableBit(const std::string &VarName,
49 BitsInit *BI, int bit) {
50 if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) {
51 if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar()))
52 if (VI->getName() == VarName)
53 return VBI->getBitNum();
54 } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) {
55 if (VI->getName() == VarName)
63 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
65 std::set<unsigned> &NamedOpIndices,
66 std::string &Case, CodeGenTarget &Target) {
67 CodeGenInstruction &CGI = Target.getInstruction(R);
69 // Determine if VarName actually contributes to the Inst encoding.
70 int bit = BI->getNumBits()-1;
72 // Scan for a bit that this contributed to.
74 if (getVariableBit(VarName, BI, bit) != -1)
80 // If we found no bits, ignore this value, otherwise emit the call to get the
84 // If the operand matches by name, reference according to that
85 // operand number. Non-matching operands are assumed to be in
88 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
89 // Get the machine operand number for the indicated operand.
90 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
91 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
92 "Explicitly used operand also marked as not emitted!");
94 unsigned NumberOps = CGI.Operands.size();
95 /// If this operand is not supposed to be emitted by the
96 /// generated emitter, skip it.
97 while (NumberedOp < NumberOps &&
98 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
99 (!NamedOpIndices.empty() && NamedOpIndices.count(
100 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) {
103 if (NumberedOp >= CGI.Operands.back().MIOperandNo +
104 CGI.Operands.back().MINumOperands) {
105 errs() << "Too few operands in record " << R->getName() <<
106 " (no match for variable " << VarName << "):\n";
114 OpIdx = NumberedOp++;
117 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
118 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
120 // If the source operand has a custom encoder, use it. This will
121 // get the encoding for all of the suboperands.
122 if (!EncoderMethodName.empty()) {
123 // A custom encoder has all of the information for the
124 // sub-operands, if there are more than one, so only
125 // query the encoder once per source operand.
126 if (SO.second == 0) {
127 Case += " // op: " + VarName + "\n" +
128 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
129 Case += ", Fixups, STI";
133 Case += " // op: " + VarName + "\n" +
134 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
135 Case += ", Fixups, STI";
140 int varBit = getVariableBit(VarName, BI, bit);
142 // If this bit isn't from a variable, skip it.
148 // Figure out the consecutive range of bits covered by this operand, in
149 // order to generate better encoding code.
150 int beginInstBit = bit;
151 int beginVarBit = varBit;
153 for (--bit; bit >= 0;) {
154 varBit = getVariableBit(VarName, BI, bit);
155 if (varBit == -1 || varBit != (beginVarBit - N)) break;
160 uint64_t opMask = ~(uint64_t)0 >> (64-N);
161 int opShift = beginVarBit - N + 1;
163 opShift = beginInstBit - beginVarBit;
166 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
167 itostr(opShift) + ";\n";
168 } else if (opShift < 0) {
169 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
170 itostr(-opShift) + ";\n";
172 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
178 std::string CodeEmitterGen::getInstructionCase(Record *R,
179 CodeGenTarget &Target) {
182 BitsInit *BI = R->getValueAsBitsInit("Inst");
183 const std::vector<RecordVal> &Vals = R->getValues();
184 unsigned NumberedOp = 0;
186 std::set<unsigned> NamedOpIndices;
187 // Collect the set of operand indices that might correspond to named
188 // operand, and skip these when assigning operands based on position.
189 if (Target.getInstructionSet()->
190 getValueAsBit("noNamedPositionallyEncodedOperands")) {
191 CodeGenInstruction &CGI = Target.getInstruction(R);
192 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
194 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
197 NamedOpIndices.insert(OpIdx);
201 // Loop over all of the fields in the instruction, determining which are the
202 // operands to the instruction.
203 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
204 // Ignore fixed fields in the record, we're looking for values like:
205 // bits<5> RST = { ?, ?, ?, ?, ? };
206 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
209 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp,
210 NamedOpIndices, Case, Target);
213 std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
214 if (!PostEmitter.empty()) {
215 Case += " Value = " + PostEmitter + "(MI, Value";
223 void CodeEmitterGen::run(raw_ostream &o) {
224 CodeGenTarget Target(Records);
225 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
227 // For little-endian instruction bit encodings, reverse the bit order
228 Target.reverseBitsForLittleEndianEncoding();
230 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
231 Target.getInstructionsByEnumValue();
233 // Emit function declaration
234 o << "uint64_t " << Target.getName();
235 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
236 << " SmallVectorImpl<MCFixup> &Fixups,\n"
237 << " const MCSubtargetInfo &STI) const {\n";
239 // Emit instruction base values
240 o << " static const uint64_t InstBits[] = {\n";
241 for (std::vector<const CodeGenInstruction*>::const_iterator
242 IN = NumberedInstructions.begin(),
243 EN = NumberedInstructions.end();
245 const CodeGenInstruction *CGI = *IN;
246 Record *R = CGI->TheDef;
248 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
249 R->getValueAsBit("isPseudo")) {
250 o << " UINT64_C(0),\n";
254 BitsInit *BI = R->getValueAsBitsInit("Inst");
256 // Start by filling in fixed values.
258 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
259 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1)))
260 Value |= (uint64_t)B->getValue() << (e-i-1);
262 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
264 o << " UINT64_C(0)\n };\n";
266 // Map to accumulate all the cases.
267 std::map<std::string, std::vector<std::string> > CaseMap;
269 // Construct all cases statement for each opcode
270 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
273 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
274 R->getValueAsBit("isPseudo"))
276 const std::string &InstName = R->getValueAsString("Namespace") + "::"
278 std::string Case = getInstructionCase(R, Target);
280 CaseMap[Case].push_back(InstName);
283 // Emit initial function code
284 o << " const unsigned opcode = MI.getOpcode();\n"
285 << " uint64_t Value = InstBits[opcode];\n"
286 << " uint64_t op = 0;\n"
287 << " (void)op; // suppress warning\n"
288 << " switch (opcode) {\n";
290 // Emit each case statement
291 std::map<std::string, std::vector<std::string> >::iterator IE, EE;
292 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
293 const std::string &Case = IE->first;
294 std::vector<std::string> &InstList = IE->second;
296 for (int i = 0, N = InstList.size(); i < N; i++) {
298 o << " case " << InstList[i] << ":";
306 // Default case: unhandled opcode
308 << " std::string msg;\n"
309 << " raw_string_ostream Msg(msg);\n"
310 << " Msg << \"Not supported instr: \" << MI;\n"
311 << " report_fatal_error(Msg.str());\n"
313 << " return Value;\n"
317 } // End anonymous namespace
321 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
322 emitSourceFileHeader("Machine Code Emitter", OS);
323 CodeEmitterGen(RK).run(OS);
326 } // End llvm namespace