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 "CodeGenTarget.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/TableGen/Record.h" 21 #include "llvm/TableGen/TableGenBackend.h" 22 #include <map> 23 #include <string> 24 #include <vector> 25 using namespace llvm; 26 27 // FIXME: Somewhat hackish to use a command line option for this. There should 28 // be a CodeEmitter class in the Target.td that controls this sort of thing 29 // instead. 30 static cl::opt<bool> 31 MCEmitter("mc-emitter", 32 cl::desc("Generate CodeEmitter for use with the MC library."), 33 cl::init(false)); 34 35 namespace { 36 37 class CodeEmitterGen { 38 RecordKeeper &Records; 39 public: 40 CodeEmitterGen(RecordKeeper &R) : Records(R) {} 41 42 void run(raw_ostream &o); 43 private: 44 void emitMachineOpEmitter(raw_ostream &o, const std::string &Namespace); 45 void emitGetValueBit(raw_ostream &o, const std::string &Namespace); 46 int getVariableBit(const std::string &VarName, BitsInit *BI, int bit); 47 std::string getInstructionCase(Record *R, CodeGenTarget &Target); 48 void AddCodeToMergeInOperand(Record *R, BitsInit *BI, 49 const std::string &VarName, 50 unsigned &NumberedOp, 51 std::set<unsigned> &NamedOpIndices, 52 std::string &Case, CodeGenTarget &Target); 53 54 }; 55 56 // If the VarBitInit at position 'bit' matches the specified variable then 57 // return the variable bit position. Otherwise return -1. 58 int CodeEmitterGen::getVariableBit(const std::string &VarName, 59 BitsInit *BI, int bit) { 60 if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) { 61 if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar())) 62 if (VI->getName() == VarName) 63 return VBI->getBitNum(); 64 } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) { 65 if (VI->getName() == VarName) 66 return 0; 67 } 68 69 return -1; 70 } 71 72 void CodeEmitterGen:: 73 AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, 74 unsigned &NumberedOp, 75 std::set<unsigned> &NamedOpIndices, 76 std::string &Case, CodeGenTarget &Target) { 77 CodeGenInstruction &CGI = Target.getInstruction(R); 78 79 // Determine if VarName actually contributes to the Inst encoding. 80 int bit = BI->getNumBits()-1; 81 82 // Scan for a bit that this contributed to. 83 for (; bit >= 0; ) { 84 if (getVariableBit(VarName, BI, bit) != -1) 85 break; 86 87 --bit; 88 } 89 90 // If we found no bits, ignore this value, otherwise emit the call to get the 91 // operand encoding. 92 if (bit < 0) return; 93 94 // If the operand matches by name, reference according to that 95 // operand number. Non-matching operands are assumed to be in 96 // order. 97 unsigned OpIdx; 98 if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) { 99 // Get the machine operand number for the indicated operand. 100 OpIdx = CGI.Operands[OpIdx].MIOperandNo; 101 assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) && 102 "Explicitly used operand also marked as not emitted!"); 103 } else { 104 unsigned NumberOps = CGI.Operands.size(); 105 /// If this operand is not supposed to be emitted by the 106 /// generated emitter, skip it. 107 while (NumberedOp < NumberOps && 108 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) || 109 (NamedOpIndices.size() && NamedOpIndices.count( 110 CGI.Operands.getSubOperandNumber(NumberedOp).first)))) 111 ++NumberedOp; 112 113 OpIdx = NumberedOp++; 114 } 115 116 std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx); 117 std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName; 118 119 // If the source operand has a custom encoder, use it. This will 120 // get the encoding for all of the suboperands. 121 if (!EncoderMethodName.empty()) { 122 // A custom encoder has all of the information for the 123 // sub-operands, if there are more than one, so only 124 // query the encoder once per source operand. 125 if (SO.second == 0) { 126 Case += " // op: " + VarName + "\n" + 127 " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx); 128 if (MCEmitter) 129 Case += ", Fixups, STI"; 130 Case += ");\n"; 131 } 132 } else { 133 Case += " // op: " + VarName + "\n" + 134 " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")"; 135 if (MCEmitter) 136 Case += ", Fixups, STI"; 137 Case += ");\n"; 138 } 139 140 for (; bit >= 0; ) { 141 int varBit = getVariableBit(VarName, BI, bit); 142 143 // If this bit isn't from a variable, skip it. 144 if (varBit == -1) { 145 --bit; 146 continue; 147 } 148 149 // Figure out the consecutive range of bits covered by this operand, in 150 // order to generate better encoding code. 151 int beginInstBit = bit; 152 int beginVarBit = varBit; 153 int N = 1; 154 for (--bit; bit >= 0;) { 155 varBit = getVariableBit(VarName, BI, bit); 156 if (varBit == -1 || varBit != (beginVarBit - N)) break; 157 ++N; 158 --bit; 159 } 160 161 uint64_t opMask = ~(uint64_t)0 >> (64-N); 162 int opShift = beginVarBit - N + 1; 163 opMask <<= opShift; 164 opShift = beginInstBit - beginVarBit; 165 166 if (opShift > 0) { 167 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " + 168 itostr(opShift) + ";\n"; 169 } else if (opShift < 0) { 170 Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " + 171 itostr(-opShift) + ";\n"; 172 } else { 173 Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n"; 174 } 175 } 176 } 177 178 179 std::string CodeEmitterGen::getInstructionCase(Record *R, 180 CodeGenTarget &Target) { 181 std::string Case; 182 183 BitsInit *BI = R->getValueAsBitsInit("Inst"); 184 const std::vector<RecordVal> &Vals = R->getValues(); 185 unsigned NumberedOp = 0; 186 187 std::set<unsigned> NamedOpIndices; 188 // Collect the set of operand indices that might correspond to named 189 // operand, and skip these when assigning operands based on position. 190 if (Target.getInstructionSet()-> 191 getValueAsBit("noNamedPositionallyEncodedOperands")) { 192 CodeGenInstruction &CGI = Target.getInstruction(R); 193 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 194 unsigned OpIdx; 195 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx)) 196 continue; 197 198 NamedOpIndices.insert(OpIdx); 199 } 200 } 201 202 // Loop over all of the fields in the instruction, determining which are the 203 // operands to the instruction. 204 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 205 // Ignore fixed fields in the record, we're looking for values like: 206 // bits<5> RST = { ?, ?, ?, ?, ? }; 207 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete()) 208 continue; 209 210 AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, 211 NamedOpIndices, Case, Target); 212 } 213 214 std::string PostEmitter = R->getValueAsString("PostEncoderMethod"); 215 if (!PostEmitter.empty()) { 216 Case += " Value = " + PostEmitter + "(MI, Value"; 217 if (MCEmitter) 218 Case += ", STI"; 219 Case += ");\n"; 220 } 221 222 return Case; 223 } 224 225 void CodeEmitterGen::run(raw_ostream &o) { 226 CodeGenTarget Target(Records); 227 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); 228 229 // For little-endian instruction bit encodings, reverse the bit order 230 Target.reverseBitsForLittleEndianEncoding(); 231 232 const std::vector<const CodeGenInstruction*> &NumberedInstructions = 233 Target.getInstructionsByEnumValue(); 234 235 // Emit function declaration 236 o << "uint64_t " << Target.getName(); 237 if (MCEmitter) 238 o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n" 239 << " SmallVectorImpl<MCFixup> &Fixups,\n" 240 << " const MCSubtargetInfo &STI) const {\n"; 241 else 242 o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n"; 243 244 // Emit instruction base values 245 o << " static const uint64_t InstBits[] = {\n"; 246 for (std::vector<const CodeGenInstruction*>::const_iterator 247 IN = NumberedInstructions.begin(), 248 EN = NumberedInstructions.end(); 249 IN != EN; ++IN) { 250 const CodeGenInstruction *CGI = *IN; 251 Record *R = CGI->TheDef; 252 253 if (R->getValueAsString("Namespace") == "TargetOpcode" || 254 R->getValueAsBit("isPseudo")) { 255 o << " UINT64_C(0),\n"; 256 continue; 257 } 258 259 BitsInit *BI = R->getValueAsBitsInit("Inst"); 260 261 // Start by filling in fixed values. 262 uint64_t Value = 0; 263 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { 264 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1))) 265 Value |= (uint64_t)B->getValue() << (e-i-1); 266 } 267 o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n"; 268 } 269 o << " UINT64_C(0)\n };\n"; 270 271 // Map to accumulate all the cases. 272 std::map<std::string, std::vector<std::string> > CaseMap; 273 274 // Construct all cases statement for each opcode 275 for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end(); 276 IC != EC; ++IC) { 277 Record *R = *IC; 278 if (R->getValueAsString("Namespace") == "TargetOpcode" || 279 R->getValueAsBit("isPseudo")) 280 continue; 281 const std::string &InstName = R->getValueAsString("Namespace") + "::" 282 + R->getName(); 283 std::string Case = getInstructionCase(R, Target); 284 285 CaseMap[Case].push_back(InstName); 286 } 287 288 // Emit initial function code 289 o << " const unsigned opcode = MI.getOpcode();\n" 290 << " uint64_t Value = InstBits[opcode];\n" 291 << " uint64_t op = 0;\n" 292 << " (void)op; // suppress warning\n" 293 << " switch (opcode) {\n"; 294 295 // Emit each case statement 296 std::map<std::string, std::vector<std::string> >::iterator IE, EE; 297 for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) { 298 const std::string &Case = IE->first; 299 std::vector<std::string> &InstList = IE->second; 300 301 for (int i = 0, N = InstList.size(); i < N; i++) { 302 if (i) o << "\n"; 303 o << " case " << InstList[i] << ":"; 304 } 305 o << " {\n"; 306 o << Case; 307 o << " break;\n" 308 << " }\n"; 309 } 310 311 // Default case: unhandled opcode 312 o << " default:\n" 313 << " std::string msg;\n" 314 << " raw_string_ostream Msg(msg);\n" 315 << " Msg << \"Not supported instr: \" << MI;\n" 316 << " report_fatal_error(Msg.str());\n" 317 << " }\n" 318 << " return Value;\n" 319 << "}\n\n"; 320 } 321 322 } // End anonymous namespace 323 324 namespace llvm { 325 326 void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) { 327 emitSourceFileHeader("Machine Code Emitter", OS); 328 CodeEmitterGen(RK).run(OS); 329 } 330 331 } // End llvm namespace 332