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