Clean up TargetOpcodes.h a bit, and limit the number of places where the full
[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
53 // If the VarBitInit at position 'bit' matches the specified variable then
54 // return the variable bit position.  Otherwise return -1.
55 int CodeEmitterGen::getVariableBit(const std::string &VarName,
56             BitsInit *BI, int bit) {
57   if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
58     TypedInit *TI = VBI->getVariable();
59     
60     if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
61       if (VI->getName() == VarName) return VBI->getBitNum();
62     }
63   }
64   
65   return -1;
66
67
68
69 void CodeEmitterGen::run(raw_ostream &o) {
70   CodeGenTarget Target;
71   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
72   
73   // For little-endian instruction bit encodings, reverse the bit order
74   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
75
76   EmitSourceFileHeader("Machine Code Emitter", o);
77   std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
78   
79   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
80     Target.getInstructionsByEnumValue();
81
82   // Emit function declaration
83   o << "unsigned " << Target.getName() << "CodeEmitter::"
84     << "getBinaryCodeForInstr(const MachineInstr &MI) {\n";
85
86   // Emit instruction base values
87   o << "  static const unsigned InstBits[] = {\n";
88   for (std::vector<const CodeGenInstruction*>::const_iterator
89           IN = NumberedInstructions.begin(),
90           EN = NumberedInstructions.end();
91        IN != EN; ++IN) {
92     const CodeGenInstruction *CGI = *IN;
93     Record *R = CGI->TheDef;
94     
95     if (R->getValueAsString("Namespace") == "TargetOpcode") {
96       o << "    0U,\n";
97       continue;
98     }
99     
100     BitsInit *BI = R->getValueAsBitsInit("Inst");
101
102     // Start by filling in fixed values...
103     unsigned Value = 0;
104     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
105       if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
106         Value |= B->getValue() << (e-i-1);
107       }
108     }
109     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
110   }
111   o << "    0U\n  };\n";
112   
113   // Map to accumulate all the cases.
114   std::map<std::string, std::vector<std::string> > CaseMap;
115   
116   // Construct all cases statement for each opcode
117   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
118         IC != EC; ++IC) {
119     Record *R = *IC;
120     if (R->getValueAsString("Namespace") == "TargetOpcode")
121       continue;
122     const std::string &InstName = R->getName();
123     std::string Case("");
124
125     BitsInit *BI = R->getValueAsBitsInit("Inst");
126     const std::vector<RecordVal> &Vals = R->getValues();
127     CodeGenInstruction &CGI = Target.getInstruction(R);
128     
129     // Loop over all of the fields in the instruction, determining which are the
130     // operands to the instruction.
131     unsigned op = 0;
132     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
133       if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
134         // Is the operand continuous? If so, we can just mask and OR it in
135         // instead of doing it bit-by-bit, saving a lot in runtime cost.
136         const std::string &VarName = Vals[i].getName();
137         bool gotOp = false;
138         
139         for (int bit = BI->getNumBits()-1; bit >= 0; ) {
140           int varBit = getVariableBit(VarName, BI, bit);
141           
142           if (varBit == -1) {
143             --bit;
144           } else {
145             int beginInstBit = bit;
146             int beginVarBit = varBit;
147             int N = 1;
148             
149             for (--bit; bit >= 0;) {
150               varBit = getVariableBit(VarName, BI, bit);
151               if (varBit == -1 || varBit != (beginVarBit - N)) break;
152               ++N;
153               --bit;
154             }
155
156             if (!gotOp) {
157               /// If this operand is not supposed to be emitted by the generated
158               /// emitter, skip it.
159               while (CGI.isFlatOperandNotEmitted(op))
160                 ++op;
161               
162               Case += "      // op: " + VarName + "\n"
163                    +  "      op = getMachineOpValue(MI, MI.getOperand("
164                    +  utostr(op++) + "));\n";
165               gotOp = true;
166             }
167             
168             unsigned opMask = ~0U >> (32-N);
169             int opShift = beginVarBit - N + 1;
170             opMask <<= opShift;
171             opShift = beginInstBit - beginVarBit;
172             
173             if (opShift > 0) {
174               Case += "      Value |= (op & " + utostr(opMask) + "U) << "
175                    +  itostr(opShift) + ";\n";
176             } else if (opShift < 0) {
177               Case += "      Value |= (op & " + utostr(opMask) + "U) >> "
178                    +  itostr(-opShift) + ";\n";
179             } else {
180               Case += "      Value |= op & " + utostr(opMask) + "U;\n";
181             }
182           }
183         }
184       }
185     }
186
187     std::vector<std::string> &InstList = CaseMap[Case];
188     InstList.push_back(InstName);
189   }
190
191
192   // Emit initial function code
193   o << "  const unsigned opcode = MI.getOpcode();\n"
194     << "  unsigned Value = InstBits[opcode];\n"
195     << "  unsigned op = 0;\n"
196     << "  op = op;  // suppress warning\n"
197     << "  switch (opcode) {\n";
198
199   // Emit each case statement
200   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
201   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
202     const std::string &Case = IE->first;
203     std::vector<std::string> &InstList = IE->second;
204
205     for (int i = 0, N = InstList.size(); i < N; i++) {
206       if (i) o << "\n";
207       o << "    case " << Namespace << InstList[i]  << ":";
208     }
209     o << " {\n";
210     o << Case;
211     o << "      break;\n"
212       << "    }\n";
213   }
214
215   // Default case: unhandled opcode
216   o << "  default:\n"
217     << "    std::string msg;\n"
218     << "    raw_string_ostream Msg(msg);\n"
219     << "    Msg << \"Not supported instr: \" << MI;\n"
220     << "    report_fatal_error(Msg.str());\n"
221     << "  }\n"
222     << "  return Value;\n"
223     << "}\n\n";
224 }