[AVX] Make Inits Foldable
[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     const BitsInit *BI = R->getValueAsBitsInit("Inst");
42
43     unsigned numBits = BI->getNumBits();
44  
45     SmallVector<const Init *, 16> NewBits(numBits);
46  
47     for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
48       unsigned bitSwapIdx = numBits - bit - 1;
49       const Init *OrigBit = BI->getBit(bit);
50       const Init *BitSwap = BI->getBit(bitSwapIdx);
51       NewBits[bit]        = BitSwap;
52       NewBits[bitSwapIdx] = OrigBit;
53     }
54     if (numBits % 2) {
55       unsigned middle = (numBits + 1) / 2;
56       NewBits[middle] = BI->getBit(middle);
57     }
58  
59     const BitsInit *NewBI = BitsInit::Create(NewBits.begin(), NewBits.end());
60
61     // Update the bits in reversed order so that emitInstrOpBits will get the
62     // correct endianness.
63     R->getValue("Inst")->setValue(NewBI);
64   }
65 }
66
67 // If the VarBitInit at position 'bit' matches the specified variable then
68 // return the variable bit position.  Otherwise return -1.
69 int CodeEmitterGen::getVariableBit(const std::string &VarName,
70                                    const BitsInit *BI, int bit) {
71   if (const VarBitInit *VBI =
72       dynamic_cast<const VarBitInit*>(BI->getBit(bit))) {
73     if (const VarInit *VI = dynamic_cast<const VarInit*>(VBI->getVariable()))
74       if (VI->getName() == VarName)
75         return VBI->getBitNum();
76   } else if (const VarInit *VI =
77              dynamic_cast<const VarInit*>(BI->getBit(bit))) {
78     if (VI->getName() == VarName)
79       return 0;
80   }
81
82   return -1;
83 }
84
85 void CodeEmitterGen::
86 AddCodeToMergeInOperand(Record *R, const BitsInit *BI,
87                         const std::string &VarName, unsigned &NumberedOp,
88                         std::string &Case, CodeGenTarget &Target) {
89   CodeGenInstruction &CGI = Target.getInstruction(R);
90
91   // Determine if VarName actually contributes to the Inst encoding.
92   int bit = BI->getNumBits()-1;
93
94   // Scan for a bit that this contributed to.
95   for (; bit >= 0; ) {
96     if (getVariableBit(VarName, BI, bit) != -1)
97       break;
98     
99     --bit;
100   }
101   
102   // If we found no bits, ignore this value, otherwise emit the call to get the
103   // operand encoding.
104   if (bit < 0) return;
105   
106   // If the operand matches by name, reference according to that
107   // operand number. Non-matching operands are assumed to be in
108   // order.
109   unsigned OpIdx;
110   if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
111     // Get the machine operand number for the indicated operand.
112     OpIdx = CGI.Operands[OpIdx].MIOperandNo;
113     assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
114            "Explicitly used operand also marked as not emitted!");
115   } else {
116     /// If this operand is not supposed to be emitted by the
117     /// generated emitter, skip it.
118     while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
119       ++NumberedOp;
120     OpIdx = NumberedOp++;
121   }
122   
123   std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
124   std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
125   
126   // If the source operand has a custom encoder, use it. This will
127   // get the encoding for all of the suboperands.
128   if (!EncoderMethodName.empty()) {
129     // A custom encoder has all of the information for the
130     // sub-operands, if there are more than one, so only
131     // query the encoder once per source operand.
132     if (SO.second == 0) {
133       Case += "      // op: " + VarName + "\n" +
134               "      op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
135       if (MCEmitter)
136         Case += ", Fixups";
137       Case += ");\n";
138     }
139   } else {
140     Case += "      // op: " + VarName + "\n" +
141       "      op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
142     if (MCEmitter)
143       Case += ", Fixups";
144     Case += ");\n";
145   }
146   
147   for (; bit >= 0; ) {
148     int varBit = getVariableBit(VarName, BI, bit);
149     
150     // If this bit isn't from a variable, skip it.
151     if (varBit == -1) {
152       --bit;
153       continue;
154     }
155     
156     // Figure out the consecutive range of bits covered by this operand, in
157     // order to generate better encoding code.
158     int beginInstBit = bit;
159     int beginVarBit = varBit;
160     int N = 1;
161     for (--bit; bit >= 0;) {
162       varBit = getVariableBit(VarName, BI, bit);
163       if (varBit == -1 || varBit != (beginVarBit - N)) break;
164       ++N;
165       --bit;
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 std::string CodeEmitterGen::getInstructionCase(Record *R,
187                                                CodeGenTarget &Target) {
188   std::string Case;
189   
190   const BitsInit *BI = R->getValueAsBitsInit("Inst");
191   const std::vector<RecordVal> &Vals = R->getValues();
192   unsigned NumberedOp = 0;
193
194   // Loop over all of the fields in the instruction, determining which are the
195   // operands to the instruction.
196   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
197     // Ignore fixed fields in the record, we're looking for values like:
198     //    bits<5> RST = { ?, ?, ?, ?, ? };
199     if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
200       continue;
201     
202     AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
203   }
204   
205   std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
206   if (!PostEmitter.empty())
207     Case += "      Value = " + PostEmitter + "(MI, Value);\n";
208   
209   return Case;
210 }
211
212 void CodeEmitterGen::run(raw_ostream &o) {
213   CodeGenTarget Target(Records);
214   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
215
216   // For little-endian instruction bit encodings, reverse the bit order
217   if (Target.isLittleEndianEncoding()) reverseBits(Insts);
218
219   EmitSourceFileHeader("Machine Code Emitter", o);
220
221   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
222     Target.getInstructionsByEnumValue();
223
224   // Emit function declaration
225   o << "unsigned " << Target.getName();
226   if (MCEmitter)
227     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
228       << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
229   else
230     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
231
232   // Emit instruction base values
233   o << "  static const unsigned InstBits[] = {\n";
234   for (std::vector<const CodeGenInstruction*>::const_iterator
235           IN = NumberedInstructions.begin(),
236           EN = NumberedInstructions.end();
237        IN != EN; ++IN) {
238     const CodeGenInstruction *CGI = *IN;
239     Record *R = CGI->TheDef;
240
241     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
242         R->getValueAsBit("isPseudo")) {
243       o << "    0U,\n";
244       continue;
245     }
246
247     const BitsInit *BI = R->getValueAsBitsInit("Inst");
248
249     // Start by filling in fixed values.
250     unsigned Value = 0;
251     for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
252       if (const BitInit *B = dynamic_cast<const BitInit*>(BI->getBit(e-i-1)))
253         Value |= B->getValue() << (e-i-1);
254     }
255     o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
256   }
257   o << "    0U\n  };\n";
258
259   // Map to accumulate all the cases.
260   std::map<std::string, std::vector<std::string> > CaseMap;
261
262   // Construct all cases statement for each opcode
263   for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
264         IC != EC; ++IC) {
265     Record *R = *IC;
266     if (R->getValueAsString("Namespace") == "TargetOpcode" ||
267         R->getValueAsBit("isPseudo"))
268       continue;
269     const std::string &InstName = R->getValueAsString("Namespace") + "::"
270       + R->getName();
271     std::string Case = getInstructionCase(R, Target);
272
273     CaseMap[Case].push_back(InstName);
274   }
275
276   // Emit initial function code
277   o << "  const unsigned opcode = MI.getOpcode();\n"
278     << "  unsigned Value = InstBits[opcode];\n"
279     << "  unsigned op = 0;\n"
280     << "  (void)op;  // suppress warning\n"
281     << "  switch (opcode) {\n";
282
283   // Emit each case statement
284   std::map<std::string, std::vector<std::string> >::iterator IE, EE;
285   for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
286     const std::string &Case = IE->first;
287     std::vector<std::string> &InstList = IE->second;
288
289     for (int i = 0, N = InstList.size(); i < N; i++) {
290       if (i) o << "\n";
291       o << "    case " << InstList[i]  << ":";
292     }
293     o << " {\n";
294     o << Case;
295     o << "      break;\n"
296       << "    }\n";
297   }
298
299   // Default case: unhandled opcode
300   o << "  default:\n"
301     << "    std::string msg;\n"
302     << "    raw_string_ostream Msg(msg);\n"
303     << "    Msg << \"Not supported instr: \" << MI;\n"
304     << "    report_fatal_error(Msg.str());\n"
305     << "  }\n"
306     << "  return Value;\n"
307     << "}\n\n";
308 }