reduce nesting and minor cleanups, no functionality change.
[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 using namespace llvm;
23
24 // FIXME: Somewhat hackish to use a command line option for this. There should
25 // be a CodeEmitter class in the Target.td that controls this sort of thing
26 // instead.
27 static cl::opt<bool>
28 MCEmitter("mc-emitter",
29           cl::desc("Generate CodeEmitter for use with the MC library."),
30           cl::init(false));
31
32 void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
33   for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
34        I != E; ++I) {
35     Record *R = *I;
36     if (R->getValueAsString("Namespace") == "TargetOpcode")
37       continue;
38
39     BitsInit *BI = R->getValueAsBitsInit("Inst");
40
41     unsigned numBits = BI->getNumBits();
42     BitsInit *NewBI = new BitsInit(numBits);
43     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
44       unsigned bitSwapIdx = numBits - bit - 1;
45       Init *OrigBit = BI->getBit(bit);
46       Init *BitSwap = BI->getBit(bitSwapIdx);
47       NewBI->setBit(bit, BitSwap);
48       NewBI->setBit(bitSwapIdx, OrigBit);
49     }
50     if (numBits % 2) {
51       unsigned middle = (numBits + 1) / 2;
52       NewBI->setBit(middle, BI->getBit(middle));
53     }
54
55     // Update the bits in reversed order so that emitInstrOpBits will get the
56     // correct endianness.
57     R->getValue("Inst")->setValue(NewBI);
58   }
59 }
60
61 // If the VarBitInit at position 'bit' matches the specified variable then
62 // return the variable bit position.  Otherwise return -1.
63 int CodeEmitterGen::getVariableBit(const std::string &VarName,
64             BitsInit *BI, int bit) {
65   if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit)))
66     if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
67       if (VI->getName() == VarName)
68         return VBI->getBitNum();
69
70   return -1;
71 }
72
73 void CodeEmitterGen::run(raw_ostream &o) {
74   CodeGenTarget Target;
75   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
76
77   // For little-endian instruction bit encodings, reverse the bit order
78   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
79
80   EmitSourceFileHeader("Machine Code Emitter", o);
81   std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
82
83   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
84     Target.getInstructionsByEnumValue();
85
86   // Emit function declaration
87   o << "unsigned " << Target.getName();
88   if (MCEmitter)
89     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
90       << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
91   else
92     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
93
94   // Emit instruction base values
95   o << "  static const unsigned InstBits[] = {\n";
96   for (std::vector<const CodeGenInstruction*>::const_iterator
97           IN = NumberedInstructions.begin(),
98           EN = NumberedInstructions.end();
99        IN != EN; ++IN) {
100     const CodeGenInstruction *CGI = *IN;
101     Record *R = CGI->TheDef;
102
103     if (R->getValueAsString("Namespace") == "TargetOpcode") {
104       o << "    0U,\n";
105       continue;
106     }
107
108     BitsInit *BI = R->getValueAsBitsInit("Inst");
109
110     // Start by filling in fixed values...
111     unsigned Value = 0;
112     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
113       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
114         Value |= B->getValue() << (e-i-1);
115       }
116     }
117     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
118   }
119   o << "    0U\n  };\n";
120
121   // Map to accumulate all the cases.
122   std::map<std::string, std::vector<std::string> > CaseMap;
123
124   // Construct all cases statement for each opcode
125   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
126         IC != EC; ++IC) {
127     Record *R = *IC;
128     if (R->getValueAsString("Namespace") == "TargetOpcode")
129       continue;
130     const std::string &InstName = R->getName();
131     std::string Case("");
132
133     BitsInit *BI = R->getValueAsBitsInit("Inst");
134     const std::vector<RecordVal> &Vals = R->getValues();
135     CodeGenInstruction &CGI = Target.getInstruction(R);
136
137     // Loop over all of the fields in the instruction, determining which are the
138     // operands to the instruction.
139     unsigned NumberedOp = 0;
140     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
141       // Ignore fixed fields.
142       if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
143         continue;
144       
145       // Is the operand continuous? If so, we can just mask and OR it in
146       // instead of doing it bit-by-bit, saving a lot in runtime cost.
147       const std::string &VarName = Vals[i].getName();
148       bool gotOp = false;
149
150       for (int bit = BI->getNumBits()-1; bit >= 0; ) {
151         int varBit = getVariableBit(VarName, BI, bit);
152
153         // If this bit isn't from a variable, skip it.
154         if (varBit == -1) {
155           --bit;
156           continue;
157         }
158
159         int beginInstBit = bit;
160         int beginVarBit = varBit;
161         int N = 1;
162
163         for (--bit; bit >= 0;) {
164           varBit = getVariableBit(VarName, BI, bit);
165           if (varBit == -1 || varBit != (beginVarBit - N)) break;
166           ++N;
167           --bit;
168         }
169
170         if (!gotOp) {
171           // If the operand matches by name, reference according to that
172           // operand number. Non-matching operands are assumed to be in
173           // order.
174           unsigned OpIdx;
175           if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
176             // Get the machine operand number for the indicated operand.
177             OpIdx = CGI.Operands[OpIdx].MIOperandNo;
178             assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
179                     "Explicitly used operand also marked as not emitted!");
180           } else {
181             /// If this operand is not supposed to be emitted by the
182             /// generated emitter, skip it.
183             while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
184               ++NumberedOp;
185             OpIdx = NumberedOp++;
186           }
187           std::pair<unsigned, unsigned> SO =
188             CGI.Operands.getSubOperandNumber(OpIdx);
189           std::string &EncoderMethodName =
190             CGI.Operands[SO.first].EncoderMethodName;
191
192           // If the source operand has a custom encoder, use it. This will
193           // get the encoding for all of the suboperands.
194           if (!EncoderMethodName.empty()) {
195             // A custom encoder has all of the information for the
196             // sub-operands, if there are more than one, so only
197             // query the encoder once per source operand.
198             if (SO.second == 0) {
199               Case += "      // op: " + VarName + "\n"
200                    + "      op = " + EncoderMethodName + "(MI, "
201                    + utostr(OpIdx);
202               if (MCEmitter)
203                 Case += ", Fixups";
204               Case += ");\n";
205             }
206           } else {
207             Case += "      // op: " + VarName + "\n"
208                  +  "      op = getMachineOpValue(MI, MI.getOperand("
209                  +  utostr(OpIdx) + ")";
210             if (MCEmitter)
211               Case += ", Fixups";
212             Case += ");\n";
213           }
214           gotOp = true;
215         }
216
217         unsigned opMask = ~0U >> (32-N);
218         int opShift = beginVarBit - N + 1;
219         opMask <<= opShift;
220         opShift = beginInstBit - beginVarBit;
221
222         if (opShift > 0) {
223           Case += "      Value |= (op & " + utostr(opMask) + "U) << "
224                +  itostr(opShift) + ";\n";
225         } else if (opShift < 0) {
226           Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
227                +  itostr(-opShift) + ";\n";
228         } else {
229           Case += "      Value |= op & " + utostr(opMask) + "U;\n";
230         }
231       }
232     }
233
234     std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
235     if (!PostEmitter.empty())
236       Case += "      Value = " + PostEmitter + "(MI, Value);\n";
237
238     std::vector<std::string> &InstList = CaseMap[Case];
239     InstList.push_back(InstName);
240   }
241
242   // Emit initial function code
243   o << "  const unsigned opcode = MI.getOpcode();\n"
244     << "  unsigned Value = InstBits[opcode];\n"
245     << "  unsigned op = 0;\n"
246     << "  op = op;  // suppress warning\n"
247     << "  switch (opcode) {\n";
248
249   // Emit each case statement
250   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
251   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
252     const std::string &Case = IE->first;
253     std::vector<std::string> &InstList = IE->second;
254
255     for (int i = 0, N = InstList.size(); i < N; i++) {
256       if (i) o << "\n";
257       o << "    case " << Namespace << InstList[i]  << ":";
258     }
259     o << " {\n";
260     o << Case;
261     o << "      break;\n"
262       << "    }\n";
263   }
264
265   // Default case: unhandled opcode
266   o << "  default:\n"
267     << "    std::string msg;\n"
268     << "    raw_string_ostream Msg(msg);\n"
269     << "    Msg << \"Not supported instr: \" << MI;\n"
270     << "    report_fatal_error(Msg.str());\n"
271     << "  }\n"
272     << "  return Value;\n"
273     << "}\n\n";
274 }