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/TableGen/Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/TableGen/TableGenBackend.h"
27 // FIXME: Somewhat hackish to use a command line option for this. There should
28 // be a CodeEmitter class in the Target.td that controls this sort of thing
31 MCEmitter("mc-emitter",
32 cl::desc("Generate CodeEmitter for use with the MC library."),
37 class CodeEmitterGen {
38 RecordKeeper &Records;
40 CodeEmitterGen(RecordKeeper &R) : Records(R) {}
42 void run(raw_ostream &o);
44 void emitMachineOpEmitter(raw_ostream &o, const std::string &Namespace);
45 void emitGetValueBit(raw_ostream &o, const std::string &Namespace);
46 void reverseBits(std::vector<Record*> &Insts);
47 int getVariableBit(const std::string &VarName, BitsInit *BI, int bit);
48 std::string getInstructionCase(Record *R, CodeGenTarget &Target);
49 void AddCodeToMergeInOperand(Record *R, BitsInit *BI,
50 const std::string &VarName,
52 std::string &Case, CodeGenTarget &Target);
56 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
57 for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
60 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
61 R->getValueAsBit("isPseudo"))
64 BitsInit *BI = R->getValueAsBitsInit("Inst");
66 unsigned numBits = BI->getNumBits();
68 SmallVector<Init *, 16> NewBits(numBits);
70 for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
71 unsigned bitSwapIdx = numBits - bit - 1;
72 Init *OrigBit = BI->getBit(bit);
73 Init *BitSwap = BI->getBit(bitSwapIdx);
74 NewBits[bit] = BitSwap;
75 NewBits[bitSwapIdx] = OrigBit;
78 unsigned middle = (numBits + 1) / 2;
79 NewBits[middle] = BI->getBit(middle);
82 BitsInit *NewBI = BitsInit::get(NewBits);
84 // Update the bits in reversed order so that emitInstrOpBits will get the
85 // correct endianness.
86 R->getValue("Inst")->setValue(NewBI);
90 // If the VarBitInit at position 'bit' matches the specified variable then
91 // return the variable bit position. Otherwise return -1.
92 int CodeEmitterGen::getVariableBit(const std::string &VarName,
93 BitsInit *BI, int bit) {
94 if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
95 if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getBitVar()))
96 if (VI->getName() == VarName)
97 return VBI->getBitNum();
98 } else if (VarInit *VI = dynamic_cast<VarInit*>(BI->getBit(bit))) {
99 if (VI->getName() == VarName)
106 void CodeEmitterGen::
107 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
108 unsigned &NumberedOp,
109 std::string &Case, CodeGenTarget &Target) {
110 CodeGenInstruction &CGI = Target.getInstruction(R);
112 // Determine if VarName actually contributes to the Inst encoding.
113 int bit = BI->getNumBits()-1;
115 // Scan for a bit that this contributed to.
117 if (getVariableBit(VarName, BI, bit) != -1)
123 // If we found no bits, ignore this value, otherwise emit the call to get the
127 // If the operand matches by name, reference according to that
128 // operand number. Non-matching operands are assumed to be in
131 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
132 // Get the machine operand number for the indicated operand.
133 OpIdx = CGI.Operands[OpIdx].MIOperandNo;
134 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
135 "Explicitly used operand also marked as not emitted!");
137 /// If this operand is not supposed to be emitted by the
138 /// generated emitter, skip it.
139 while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
141 OpIdx = NumberedOp++;
144 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
145 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
147 // If the source operand has a custom encoder, use it. This will
148 // get the encoding for all of the suboperands.
149 if (!EncoderMethodName.empty()) {
150 // A custom encoder has all of the information for the
151 // sub-operands, if there are more than one, so only
152 // query the encoder once per source operand.
153 if (SO.second == 0) {
154 Case += " // op: " + VarName + "\n" +
155 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
161 Case += " // op: " + VarName + "\n" +
162 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
169 int varBit = getVariableBit(VarName, BI, bit);
171 // If this bit isn't from a variable, skip it.
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;
182 for (--bit; bit >= 0;) {
183 varBit = getVariableBit(VarName, BI, bit);
184 if (varBit == -1 || varBit != (beginVarBit - N)) break;
189 uint64_t opMask = ~(uint64_t)0 >> (64-N);
190 int opShift = beginVarBit - N + 1;
192 opShift = beginInstBit - beginVarBit;
195 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
196 itostr(opShift) + ";\n";
197 } else if (opShift < 0) {
198 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
199 itostr(-opShift) + ";\n";
201 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
207 std::string CodeEmitterGen::getInstructionCase(Record *R,
208 CodeGenTarget &Target) {
211 BitsInit *BI = R->getValueAsBitsInit("Inst");
212 const std::vector<RecordVal> &Vals = R->getValues();
213 unsigned NumberedOp = 0;
215 // Loop over all of the fields in the instruction, determining which are the
216 // operands to the instruction.
217 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
218 // Ignore fixed fields in the record, we're looking for values like:
219 // bits<5> RST = { ?, ?, ?, ?, ? };
220 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
223 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
226 std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
227 if (!PostEmitter.empty())
228 Case += " Value = " + PostEmitter + "(MI, Value);\n";
233 void CodeEmitterGen::run(raw_ostream &o) {
234 CodeGenTarget Target(Records);
235 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
237 // For little-endian instruction bit encodings, reverse the bit order
238 if (Target.isLittleEndianEncoding()) reverseBits(Insts);
241 const std::vector<const CodeGenInstruction*> &NumberedInstructions =
242 Target.getInstructionsByEnumValue();
244 // Emit function declaration
245 o << "uint64_t " << Target.getName();
247 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
248 << " SmallVectorImpl<MCFixup> &Fixups) const {\n";
250 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
252 // Emit instruction base values
253 o << " static const uint64_t InstBits[] = {\n";
254 for (std::vector<const CodeGenInstruction*>::const_iterator
255 IN = NumberedInstructions.begin(),
256 EN = NumberedInstructions.end();
258 const CodeGenInstruction *CGI = *IN;
259 Record *R = CGI->TheDef;
261 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
262 R->getValueAsBit("isPseudo")) {
263 o << " UINT64_C(0),\n";
267 BitsInit *BI = R->getValueAsBitsInit("Inst");
269 // Start by filling in fixed values.
271 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
272 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
273 Value |= (uint64_t)B->getValue() << (e-i-1);
275 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
277 o << " UINT64_C(0)\n };\n";
279 // Map to accumulate all the cases.
280 std::map<std::string, std::vector<std::string> > CaseMap;
282 // Construct all cases statement for each opcode
283 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
286 if (R->getValueAsString("Namespace") == "TargetOpcode" ||
287 R->getValueAsBit("isPseudo"))
289 const std::string &InstName = R->getValueAsString("Namespace") + "::"
291 std::string Case = getInstructionCase(R, Target);
293 CaseMap[Case].push_back(InstName);
296 // Emit initial function code
297 o << " const unsigned opcode = MI.getOpcode();\n"
298 << " uint64_t Value = InstBits[opcode];\n"
299 << " uint64_t op = 0;\n"
300 << " (void)op; // suppress warning\n"
301 << " switch (opcode) {\n";
303 // Emit each case statement
304 std::map<std::string, std::vector<std::string> >::iterator IE, EE;
305 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
306 const std::string &Case = IE->first;
307 std::vector<std::string> &InstList = IE->second;
309 for (int i = 0, N = InstList.size(); i < N; i++) {
311 o << " case " << InstList[i] << ":";
319 // Default case: unhandled opcode
321 << " std::string msg;\n"
322 << " raw_string_ostream Msg(msg);\n"
323 << " Msg << \"Not supported instr: \" << MI;\n"
324 << " report_fatal_error(Msg.str());\n"
326 << " return Value;\n"
330 } // End anonymous namespace
334 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) {
335 emitSourceFileHeader("Machine Code Emitter", OS);
336 CodeEmitterGen(RK).run(OS);
339 } // End llvm namespace