Don't require pseudo-instructions to carry encoding information.
[oota-llvm.git] / utils / TableGen / CodeEmitterGen.cpp
1 //===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "CodeEmitterGen.h"
17 #include "CodeGenTarget.h"
18 #include "Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include <map>
23 using namespace llvm;
24
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
27 // instead.
28 static cl::opt<bool>
29 MCEmitter("mc-emitter",
30           cl::desc("Generate CodeEmitter for use with the MC library."),
31           cl::init(false));
32
33 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
34   for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
35        I != E; ++I) {
36     Record *R = *I;
37     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
38         R->getValueAsBit("isPseudo"))
39       continue;
40
41     BitsInit *BI = R->getValueAsBitsInit("Inst");
42
43     unsigned numBits = BI->getNumBits();
44     BitsInit *NewBI = new BitsInit(numBits);
45     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
46       unsigned bitSwapIdx = numBits - bit - 1;
47       Init *OrigBit = BI->getBit(bit);
48       Init *BitSwap = BI->getBit(bitSwapIdx);
49       NewBI->setBit(bit, BitSwap);
50       NewBI->setBit(bitSwapIdx, OrigBit);
51     }
52     if (numBits % 2) {
53       unsigned middle = (numBits + 1) / 2;
54       NewBI->setBit(middle, BI->getBit(middle));
55     }
56
57     // Update the bits in reversed order so that emitInstrOpBits will get the
58     // correct endianness.
59     R->getValue("Inst")->setValue(NewBI);
60   }
61 }
62
63 // If the VarBitInit at position 'bit' matches the specified variable then
64 // return the variable bit position.  Otherwise return -1.
65 int CodeEmitterGen::getVariableBit(const std::string &VarName,
66                                    BitsInit *BI, int bit) {
67   if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
68     if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
69       if (VI->getName() == VarName)
70         return VBI->getBitNum();
71   } else if (VarInit *VI = dynamic_cast<VarInit*>(BI->getBit(bit))) {
72     if (VI->getName() == VarName)
73       return 0;
74   }
75
76   return -1;
77 }
78
79 void CodeEmitterGen::
80 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
81                         unsigned &NumberedOp,
82                         std::string &Case, CodeGenTarget &Target) {
83   CodeGenInstruction &CGI = Target.getInstruction(R);
84
85   // Determine if VarName actually contributes to the Inst encoding.
86   int bit = BI->getNumBits()-1;
87
88   // Scan for a bit that this contributed to.
89   for (; bit >= 0; ) {
90     if (getVariableBit(VarName, BI, bit) != -1)
91       break;
92     
93     --bit;
94   }
95   
96   // If we found no bits, ignore this value, otherwise emit the call to get the
97   // operand encoding.
98   if (bit < 0) return;
99   
100   // If the operand matches by name, reference according to that
101   // operand number. Non-matching operands are assumed to be in
102   // order.
103   unsigned OpIdx;
104   if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
105     // Get the machine operand number for the indicated operand.
106     OpIdx = CGI.Operands[OpIdx].MIOperandNo;
107     assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
108            "Explicitly used operand also marked as not emitted!");
109   } else {
110     /// If this operand is not supposed to be emitted by the
111     /// generated emitter, skip it.
112     while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
113       ++NumberedOp;
114     OpIdx = NumberedOp++;
115   }
116   
117   std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
118   std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
119   
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       if (MCEmitter)
130         Case += ", Fixups";
131       Case += ");\n";
132     }
133   } else {
134     Case += "      // op: " + VarName + "\n" +
135       "      op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
136     if (MCEmitter)
137       Case += ", Fixups";
138     Case += ");\n";
139   }
140   
141   for (; bit >= 0; ) {
142     int varBit = getVariableBit(VarName, BI, bit);
143     
144     // If this bit isn't from a variable, skip it.
145     if (varBit == -1) {
146       --bit;
147       continue;
148     }
149     
150     // Figure out the consecutive range of bits covered by this operand, in
151     // order to generate better encoding code.
152     int beginInstBit = bit;
153     int beginVarBit = varBit;
154     int N = 1;
155     for (--bit; bit >= 0;) {
156       varBit = getVariableBit(VarName, BI, bit);
157       if (varBit == -1 || varBit != (beginVarBit - N)) break;
158       ++N;
159       --bit;
160     }
161      
162     unsigned opMask = ~0U >> (32-N);
163     int opShift = beginVarBit - N + 1;
164     opMask <<= opShift;
165     opShift = beginInstBit - beginVarBit;
166     
167     if (opShift > 0) {
168       Case += "      Value |= (op & " + utostr(opMask) + "U) << " +
169               itostr(opShift) + ";\n";
170     } else if (opShift < 0) {
171       Case += "      Value |= (op & " + utostr(opMask) + "U) >> " + 
172               itostr(-opShift) + ";\n";
173     } else {
174       Case += "      Value |= op & " + utostr(opMask) + "U;\n";
175     }
176   }
177 }
178
179
180 std::string CodeEmitterGen::getInstructionCase(Record *R,
181                                                CodeGenTarget &Target) {
182   std::string Case;
183   
184   BitsInit *BI = R->getValueAsBitsInit("Inst");
185   const std::vector<RecordVal> &Vals = R->getValues();
186   unsigned NumberedOp = 0;
187
188   // Loop over all of the fields in the instruction, determining which are the
189   // operands to the instruction.
190   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
191     // Ignore fixed fields in the record, we're looking for values like:
192     //    bits<5> RST = { ?, ?, ?, ?, ? };
193     if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
194       continue;
195     
196     AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
197   }
198   
199   std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
200   if (!PostEmitter.empty())
201     Case += "      Value = " + PostEmitter + "(MI, Value);\n";
202   
203   return Case;
204 }
205
206 void CodeEmitterGen::run(raw_ostream &o) {
207   CodeGenTarget Target(Records);
208   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
209
210   // For little-endian instruction bit encodings, reverse the bit order
211   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
212
213   EmitSourceFileHeader("Machine Code Emitter", o);
214
215   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
216     Target.getInstructionsByEnumValue();
217
218   // Emit function declaration
219   o << "unsigned " << Target.getName();
220   if (MCEmitter)
221     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
222       << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
223   else
224     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
225
226   // Emit instruction base values
227   o << "  static const unsigned InstBits[] = {\n";
228   for (std::vector<const CodeGenInstruction*>::const_iterator
229           IN = NumberedInstructions.begin(),
230           EN = NumberedInstructions.end();
231        IN != EN; ++IN) {
232     const CodeGenInstruction *CGI = *IN;
233     Record *R = CGI->TheDef;
234
235     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
236         R->getValueAsBit("isPseudo")) {
237       o << "    0U,\n";
238       continue;
239     }
240
241     BitsInit *BI = R->getValueAsBitsInit("Inst");
242
243     // Start by filling in fixed values.
244     unsigned Value = 0;
245     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
246       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
247         Value |= B->getValue() << (e-i-1);
248     }
249     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
250   }
251   o << "    0U\n  };\n";
252
253   // Map to accumulate all the cases.
254   std::map<std::string, std::vector<std::string> > CaseMap;
255
256   // Construct all cases statement for each opcode
257   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
258         IC != EC; ++IC) {
259     Record *R = *IC;
260     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
261         R->getValueAsBit("isPseudo"))
262       continue;
263     const std::string &InstName = R->getValueAsString("Namespace") + "::"
264       + R->getName();
265     std::string Case = getInstructionCase(R, Target);
266
267     CaseMap[Case].push_back(InstName);
268   }
269
270   // Emit initial function code
271   o << "  const unsigned opcode = MI.getOpcode();\n"
272     << "  unsigned Value = InstBits[opcode];\n"
273     << "  unsigned op = 0;\n"
274     << "  (void)op;  // suppress warning\n"
275     << "  switch (opcode) {\n";
276
277   // Emit each case statement
278   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
279   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
280     const std::string &Case = IE->first;
281     std::vector<std::string> &InstList = IE->second;
282
283     for (int i = 0, N = InstList.size(); i < N; i++) {
284       if (i) o << "\n";
285       o << "    case " << InstList[i]  << ":";
286     }
287     o << " {\n";
288     o << Case;
289     o << "      break;\n"
290       << "    }\n";
291   }
292
293   // Default case: unhandled opcode
294   o << "  default:\n"
295     << "    std::string msg;\n"
296     << "    raw_string_ostream Msg(msg);\n"
297     << "    Msg << \"Not supported instr: \" << MI;\n"
298     << "    report_fatal_error(Msg.str());\n"
299     << "  }\n"
300     << "  return Value;\n"
301     << "}\n\n";
302 }