Add instruction names as comments to InstBits entries.
[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->getName() == "PHI" ||
28         R->getName() == "INLINEASM" ||
29         R->getName() == "DBG_LABEL" ||
30         R->getName() == "EH_LABEL" ||
31         R->getName() == "GC_LABEL" ||
32         R->getName() == "DECLARE" ||
33         R->getName() == "EXTRACT_SUBREG" ||
34         R->getName() == "INSERT_SUBREG" ||
35         R->getName() == "IMPLICIT_DEF" ||
36         R->getName() == "SUBREG_TO_REG") continue;
37     
38     BitsInit *BI = R->getValueAsBitsInit("Inst");
39
40     unsigned numBits = BI->getNumBits();
41     BitsInit *NewBI = new BitsInit(numBits);
42     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
43       unsigned bitSwapIdx = numBits - bit - 1;
44       Init *OrigBit = BI->getBit(bit);
45       Init *BitSwap = BI->getBit(bitSwapIdx);
46       NewBI->setBit(bit, BitSwap);
47       NewBI->setBit(bitSwapIdx, OrigBit);
48     }
49     if (numBits % 2) {
50       unsigned middle = (numBits + 1) / 2;
51       NewBI->setBit(middle, BI->getBit(middle));
52     }
53     
54     // Update the bits in reversed order so that emitInstrOpBits will get the
55     // correct endianness.
56     R->getValue("Inst")->setValue(NewBI);
57   }
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     TypedInit *TI = VBI->getVariable();
67     
68     if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
69       if (VI->getName() == VarName) return VBI->getBitNum();
70     }
71   }
72   
73   return -1;
74
75
76
77 void CodeEmitterGen::run(std::ostream &o) {
78   CodeGenTarget Target;
79   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
80   
81   // For little-endian instruction bit encodings, reverse the bit order
82   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
83
84   EmitSourceFileHeader("Machine Code Emitter", o);
85   std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
86   
87   std::vector<const CodeGenInstruction*> NumberedInstructions;
88   Target.getInstructionsByEnumValue(NumberedInstructions);
89
90   // Emit function declaration
91   o << "unsigned " << Target.getName() << "CodeEmitter::"
92     << "getBinaryCodeForInstr(const MachineInstr &MI) {\n";
93
94   // Emit instruction base values
95   o << "  static const unsigned InstBits[] = {\n";
96   for (std::vector<const CodeGenInstruction*>::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->getName() == "PHI" ||
104         R->getName() == "INLINEASM" ||
105         R->getName() == "DBG_LABEL" ||
106         R->getName() == "EH_LABEL" ||
107         R->getName() == "GC_LABEL" ||
108         R->getName() == "DECLARE" ||
109         R->getName() == "EXTRACT_SUBREG" ||
110         R->getName() == "INSERT_SUBREG" ||
111         R->getName() == "IMPLICIT_DEF" ||
112         R->getName() == "SUBREG_TO_REG") {
113       o << "    0U,\n";
114       continue;
115     }
116     
117     BitsInit *BI = R->getValueAsBitsInit("Inst");
118
119     // Start by filling in fixed values...
120     unsigned Value = 0;
121     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
122       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
123         Value |= B->getValue() << (e-i-1);
124       }
125     }
126     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
127   }
128   o << "    0U\n  };\n";
129   
130   // Map to accumulate all the cases.
131   std::map<std::string, std::vector<std::string> > CaseMap;
132   
133   // Construct all cases statement for each opcode
134   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
135         IC != EC; ++IC) {
136     Record *R = *IC;
137     const std::string &InstName = R->getName();
138     std::string Case("");
139     
140     if (InstName == "PHI" ||
141         InstName == "INLINEASM" ||
142         InstName == "DBG_LABEL"||
143         InstName == "EH_LABEL"||
144         InstName == "GC_LABEL"||
145         InstName == "DECLARE"||
146         InstName == "EXTRACT_SUBREG" ||
147         InstName == "INSERT_SUBREG" ||
148         InstName == "IMPLICIT_DEF" ||
149         InstName == "SUBREG_TO_REG") continue;
150     
151     BitsInit *BI = R->getValueAsBitsInit("Inst");
152     const std::vector<RecordVal> &Vals = R->getValues();
153     CodeGenInstruction &CGI = Target.getInstruction(InstName);
154     
155     // Loop over all of the fields in the instruction, determining which are the
156     // operands to the instruction.
157     unsigned op = 0;
158     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
159       if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
160         // Is the operand continuous? If so, we can just mask and OR it in
161         // instead of doing it bit-by-bit, saving a lot in runtime cost.
162         const std::string &VarName = Vals[i].getName();
163         bool gotOp = false;
164         
165         for (int bit = BI->getNumBits()-1; bit >= 0; ) {
166           int varBit = getVariableBit(VarName, BI, bit);
167           
168           if (varBit == -1) {
169             --bit;
170           } else {
171             int beginInstBit = bit;
172             int beginVarBit = varBit;
173             int N = 1;
174             
175             for (--bit; bit >= 0;) {
176               varBit = getVariableBit(VarName, BI, bit);
177               if (varBit == -1 || varBit != (beginVarBit - N)) break;
178               ++N;
179               --bit;
180             }
181
182             if (!gotOp) {
183               /// If this operand is not supposed to be emitted by the generated
184               /// emitter, skip it.
185               while (CGI.isFlatOperandNotEmitted(op))
186                 ++op;
187               
188               Case += "      // op: " + VarName + "\n"
189                    +  "      op = getMachineOpValue(MI, MI.getOperand("
190                    +  utostr(op++) + "));\n";
191               gotOp = true;
192             }
193             
194             unsigned opMask = (1 << N) - 1;
195             int opShift = beginVarBit - N + 1;
196             opMask <<= opShift;
197             opShift = beginInstBit - beginVarBit;
198             
199             if (opShift > 0) {
200               Case += "      Value |= (op & " + utostr(opMask) + "U) << "
201                    +  itostr(opShift) + ";\n";
202             } else if (opShift < 0) {
203               Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
204                    +  itostr(-opShift) + ";\n";
205             } else {
206               Case += "      Value |= op & " + utostr(opMask) + "U;\n";
207             }
208           }
209         }
210       }
211     }
212
213     std::vector<std::string> &InstList = CaseMap[Case];
214     InstList.push_back(InstName);
215   }
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     << "    cerr << \"Not supported instr: \" << MI << \"\\n\";\n"
244     << "    abort();\n"
245     << "  }\n"
246     << "  return Value;\n"
247     << "}\n\n";
248 }