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 "CodeEmitterGen.h"
17 #include "CodeGenTarget.h"
18 #include "llvm/TableGen/Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
25 // FIXME: Somewhat hackish to use a command line option for this. There should
26 // be a CodeEmitter class in the Target.td that controls this sort of thing
29 MCEmitter("mc-emitter",
30 cl::desc("Generate CodeEmitter for use with the MC library."),
33 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
34 for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
37 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
38 R->getValueAsBit("isPseudo"))
41 BitsInit *BI = R->getValueAsBitsInit("Inst");
43 unsigned numBits = BI->getNumBits();
45 SmallVector<Init *, 16> NewBits(numBits);
47 for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
48 unsigned bitSwapIdx = numBits - bit - 1;
49 Init *OrigBit = BI->getBit(bit);
50 Init *BitSwap = BI->getBit(bitSwapIdx);
51 NewBits[bit] = BitSwap;
52 NewBits[bitSwapIdx] = OrigBit;
55 unsigned middle = (numBits + 1) / 2;
56 NewBits[middle] = BI->getBit(middle);
59 BitsInit *NewBI = BitsInit::get(NewBits);
61 // Update the bits in reversed order so that emitInstrOpBits will get the
62 // correct endianness.
63 R->getValue("Inst")->setValue(NewBI);
67 // If the VarBitInit at position 'bit' matches the specified variable then
68 // return the variable bit position. Otherwise return -1.
69 int CodeEmitterGen::getVariableBit(const std::string &VarName,
70 BitsInit *BI, int bit) {
71 if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
72 if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
73 if (VI->getName() == VarName)
74 return VBI->getBitNum();
75 } else if (VarInit *VI = dynamic_cast<VarInit*>(BI->getBit(bit))) {
76 if (VI->getName() == VarName)
84 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
86 std::string &Case, CodeGenTarget &Target) {
87 CodeGenInstruction &CGI = Target.getInstruction(R);
89 // Determine if VarName actually contributes to the Inst encoding.
90 int bit = BI->getNumBits()-1;
92 // Scan for a bit that this contributed to.
94 if (getVariableBit(VarName, BI, bit) != -1)
100 // If we found no bits, ignore this value, otherwise emit the call to get the
104 // If the operand matches by name, reference according to that
105 // operand number. Non-matching operands are assumed to be in
108 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
109 // Get the machine operand number for the indicated operand.
110 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
111 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
112 "Explicitly used operand also marked as not emitted!");
114 /// If this operand is not supposed to be emitted by the
115 /// generated emitter, skip it.
116 while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
118 OpIdx = NumberedOp++;
121 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
122 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
124 // If the source operand has a custom encoder, use it. This will
125 // get the encoding for all of the suboperands.
126 if (!EncoderMethodName.empty()) {
127 // A custom encoder has all of the information for the
128 // sub-operands, if there are more than one, so only
129 // query the encoder once per source operand.
130 if (SO.second == 0) {
131 Case += " // op: " + VarName + "\n" +
132 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
138 Case += " // op: " + VarName + "\n" +
139 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
146 int varBit = getVariableBit(VarName, BI, bit);
148 // If this bit isn't from a variable, skip it.
154 // Figure out the consecutive range of bits covered by this operand, in
155 // order to generate better encoding code.
156 int beginInstBit = bit;
157 int beginVarBit = varBit;
159 for (--bit; bit >= 0;) {
160 varBit = getVariableBit(VarName, BI, bit);
161 if (varBit == -1 || varBit != (beginVarBit - N)) break;
166 unsigned opMask = ~0U >> (32-N);
167 int opShift = beginVarBit - N + 1;
169 opShift = beginInstBit - beginVarBit;
172 Case += " Value |= (op & " + utostr(opMask) + "U) << " +
173 itostr(opShift) + ";\n";
174 } else if (opShift < 0) {
175 Case += " Value |= (op & " + utostr(opMask) + "U) >> " +
176 itostr(-opShift) + ";\n";
178 Case += " Value |= op & " + utostr(opMask) + "U;\n";
184 std::string CodeEmitterGen::getInstructionCase(Record *R,
185 CodeGenTarget &Target) {
188 BitsInit *BI = R->getValueAsBitsInit("Inst");
189 const std::vector<RecordVal> &Vals = R->getValues();
190 unsigned NumberedOp = 0;
192 // Loop over all of the fields in the instruction, determining which are the
193 // operands to the instruction.
194 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
195 // Ignore fixed fields in the record, we're looking for values like:
196 // bits<5> RST = { ?, ?, ?, ?, ? };
197 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
200 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
203 std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
204 if (!PostEmitter.empty())
205 Case += " Value = " + PostEmitter + "(MI, Value);\n";
210 void CodeEmitterGen::run(raw_ostream &o) {
211 CodeGenTarget Target(Records);
212 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
214 // For little-endian instruction bit encodings, reverse the bit order
215 if (Target.isLittleEndianEncoding()) reverseBits(Insts);
217 EmitSourceFileHeader("Machine Code Emitter", o);
219 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
220 Target.getInstructionsByEnumValue();
222 // Emit function declaration
223 o << "unsigned " << Target.getName();
225 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
226 << " SmallVectorImpl<MCFixup> &Fixups) const {\n";
228 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
230 // Emit instruction base values
231 o << " static const unsigned InstBits[] = {\n";
232 for (std::vector<const CodeGenInstruction*>::const_iterator
233 IN = NumberedInstructions.begin(),
234 EN = NumberedInstructions.end();
236 const CodeGenInstruction *CGI = *IN;
237 Record *R = CGI->TheDef;
239 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
240 R->getValueAsBit("isPseudo")) {
245 BitsInit *BI = R->getValueAsBitsInit("Inst");
247 // Start by filling in fixed values.
249 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
250 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
251 Value |= B->getValue() << (e-i-1);
253 o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
257 // Map to accumulate all the cases.
258 std::map<std::string, std::vector<std::string> > CaseMap;
260 // Construct all cases statement for each opcode
261 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
264 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
265 R->getValueAsBit("isPseudo"))
267 const std::string &InstName = R->getValueAsString("Namespace") + "::"
269 std::string Case = getInstructionCase(R, Target);
271 CaseMap[Case].push_back(InstName);
274 // Emit initial function code
275 o << " const unsigned opcode = MI.getOpcode();\n"
276 << " unsigned Value = InstBits[opcode];\n"
277 << " unsigned op = 0;\n"
278 << " (void)op; // suppress warning\n"
279 << " switch (opcode) {\n";
281 // Emit each case statement
282 std::map<std::string, std::vector<std::string> >::iterator IE, EE;
283 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
284 const std::string &Case = IE->first;
285 std::vector<std::string> &InstList = IE->second;
287 for (int i = 0, N = InstList.size(); i < N; i++) {
289 o << " case " << InstList[i] << ":";
297 // Default case: unhandled opcode
299 << " std::string msg;\n"
300 << " raw_string_ostream Msg(msg);\n"
301 << " Msg << \"Not supported instr: \" << MI;\n"
302 << " report_fatal_error(Msg.str());\n"
304 << " return Value;\n"