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