1 //===- TableGen.cpp - Top-Level TableGen implementation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // TableGen is a tool which can be used to build up a description of something,
11 // then invoke one or more "tablegen backends" to emit information about the
12 // description in some predefined format. In practice, this is used by the LLVM
13 // code generators to automate generation of a code generator through a
14 // high-level description of the target.
16 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/System/Signals.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "CodeEmitterGen.h"
23 #include "RegisterInfoEmitter.h"
24 #include "InstrInfoEmitter.h"
25 #include "AsmWriterEmitter.h"
26 #include "DAGISelEmitter.h"
27 #include "SubtargetEmitter.h"
28 #include "IntrinsicEmitter.h"
38 GenRegisterEnums, GenRegister, GenRegisterHeader,
39 GenInstrEnums, GenInstrs, GenAsmWriter,
49 Action(cl::desc("Action to perform:"),
50 cl::values(clEnumValN(PrintRecords, "print-records",
51 "Print all records to stdout (default)"),
52 clEnumValN(GenEmitter, "gen-emitter",
53 "Generate machine code emitter"),
54 clEnumValN(GenRegisterEnums, "gen-register-enums",
55 "Generate enum values for registers"),
56 clEnumValN(GenRegister, "gen-register-desc",
57 "Generate a register info description"),
58 clEnumValN(GenRegisterHeader, "gen-register-desc-header",
59 "Generate a register info description header"),
60 clEnumValN(GenInstrEnums, "gen-instr-enums",
61 "Generate enum values for instructions"),
62 clEnumValN(GenInstrs, "gen-instr-desc",
63 "Generate instruction descriptions"),
64 clEnumValN(GenAsmWriter, "gen-asm-writer",
65 "Generate assembly writer"),
66 clEnumValN(GenDAGISel, "gen-dag-isel",
67 "Generate a DAG instruction selector"),
68 clEnumValN(GenSubtarget, "gen-subtarget",
69 "Generate subtarget enumerations"),
70 clEnumValN(GenIntrinsic, "gen-intrinsic",
71 "Generate intrinsic information"),
72 clEnumValN(PrintEnums, "print-enums",
73 "Print enum values for a class"),
74 clEnumValN(Parse, "parse",
75 "Interpret machine code (testing only)"),
79 Class("class", cl::desc("Print Enum list for this class"),
80 cl::value_desc("class name"));
83 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
87 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
90 IncludeDirs("I", cl::desc("Directory of include files"),
91 cl::value_desc("directory"), cl::Prefix);
95 void ParseFile(const std::string &Filename,
96 const std::vector<std::string> &IncludeDirs);
99 RecordKeeper llvm::Records;
101 static Init *getBit(Record *R, unsigned BitNo) {
102 const std::vector<RecordVal> &V = R->getValues();
103 for (unsigned i = 0, e = V.size(); i != e; ++i)
104 if (V[i].getPrefix()) {
105 assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
106 "Can only handle fields of bits<> type!");
107 BitsInit *I = (BitsInit*)V[i].getValue();
108 if (BitNo < I->getNumBits())
109 return I->getBit(BitNo);
110 BitNo -= I->getNumBits();
113 std::cerr << "Cannot find requested bit!\n";
118 static unsigned getNumBits(Record *R) {
119 const std::vector<RecordVal> &V = R->getValues();
121 for (unsigned i = 0, e = V.size(); i != e; ++i)
122 if (V[i].getPrefix()) {
123 assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
124 "Can only handle fields of bits<> type!");
125 Num += ((BitsInit*)V[i].getValue())->getNumBits();
130 static bool BitsAreFixed(Record *I1, Record *I2, unsigned BitNo) {
131 return dynamic_cast<BitInit*>(getBit(I1, BitNo)) &&
132 dynamic_cast<BitInit*>(getBit(I2, BitNo));
135 static bool BitsAreEqual(Record *I1, Record *I2, unsigned BitNo) {
136 BitInit *Bit1 = dynamic_cast<BitInit*>(getBit(I1, BitNo));
137 BitInit *Bit2 = dynamic_cast<BitInit*>(getBit(I2, BitNo));
139 return Bit1 && Bit2 && Bit1->getValue() == Bit2->getValue();
142 static bool BitRangesEqual(Record *I1, Record *I2,
143 unsigned Start, unsigned End) {
144 for (unsigned i = Start; i != End; ++i)
145 if (!BitsAreEqual(I1, I2, i))
150 static unsigned getFirstFixedBit(Record *R, unsigned FirstFixedBit) {
151 // Look for the first bit of the pair that are required to be 0 or 1.
152 while (!dynamic_cast<BitInit*>(getBit(R, FirstFixedBit)))
154 return FirstFixedBit;
157 static void FindInstDifferences(Record *I1, Record *I2,
158 unsigned FirstFixedBit, unsigned MaxBits,
159 unsigned &FirstVaryingBitOverall,
160 unsigned &LastFixedBitOverall) {
161 // Compare the first instruction to the rest of the instructions, looking for
162 // fields that differ.
164 unsigned FirstVaryingBit = FirstFixedBit;
165 while (FirstVaryingBit < MaxBits && BitsAreEqual(I1, I2, FirstVaryingBit))
168 unsigned LastFixedBit = FirstVaryingBit;
169 while (LastFixedBit < MaxBits && BitsAreFixed(I1, I2, LastFixedBit))
172 if (FirstVaryingBit < FirstVaryingBitOverall)
173 FirstVaryingBitOverall = FirstVaryingBit;
174 if (LastFixedBit < LastFixedBitOverall)
175 LastFixedBitOverall = LastFixedBit;
178 static bool getBitValue(Record *R, unsigned BitNo) {
179 Init *I = getBit(R, BitNo);
180 assert(dynamic_cast<BitInit*>(I) && "Bit should be fixed!");
181 return ((BitInit*)I)->getValue();
184 struct BitComparator {
185 unsigned BitBegin, BitEnd;
186 BitComparator(unsigned B, unsigned E) : BitBegin(B), BitEnd(E) {}
188 bool operator()(Record *R1, Record *R2) { // Return true if R1 is less than R2
189 for (unsigned i = BitBegin; i != BitEnd; ++i) {
190 bool V1 = getBitValue(R1, i), V2 = getBitValue(R2, i);
200 static void PrintRange(std::vector<Record*>::iterator I,
201 std::vector<Record*>::iterator E) {
202 while (I != E) std::cerr << **I++;
205 static bool getMemoryBit(unsigned char *M, unsigned i) {
206 return (M[i/8] & (1 << (i&7))) != 0;
209 static unsigned getFirstFixedBitInSequence(std::vector<Record*>::iterator IB,
210 std::vector<Record*>::iterator IE,
212 unsigned FirstFixedBit = 0;
213 for (std::vector<Record*>::iterator I = IB; I != IE; ++I)
214 FirstFixedBit = std::max(FirstFixedBit, getFirstFixedBit(*I, StartBit));
215 return FirstFixedBit;
218 // ParseMachineCode - Try to split the vector of instructions (which is
219 // intentionally taken by-copy) in half, narrowing down the possible
220 // instructions that we may have found. Eventually, this list will get pared
221 // down to zero or one instruction, in which case we have a match or failure.
223 static Record *ParseMachineCode(std::vector<Record*>::iterator InstsB,
224 std::vector<Record*>::iterator InstsE,
226 assert(InstsB != InstsE && "Empty range?");
227 if (InstsB+1 == InstsE) {
228 // Only a single instruction, see if we match it...
229 Record *Inst = *InstsB;
230 for (unsigned i = 0, e = getNumBits(Inst); i != e; ++i)
231 if (BitInit *BI = dynamic_cast<BitInit*>(getBit(Inst, i)))
232 if (getMemoryBit(M, i) != BI->getValue())
233 throw std::string("Parse failed!\n");
237 unsigned MaxBits = ~0;
238 for (std::vector<Record*>::iterator I = InstsB; I != InstsE; ++I)
239 MaxBits = std::min(MaxBits, getNumBits(*I));
241 unsigned FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, 0);
242 unsigned FirstVaryingBit, LastFixedBit;
244 FirstVaryingBit = ~0;
246 for (std::vector<Record*>::iterator I = InstsB+1; I != InstsE; ++I)
247 FindInstDifferences(*InstsB, *I, FirstFixedBit, MaxBits,
248 FirstVaryingBit, LastFixedBit);
249 if (FirstVaryingBit == MaxBits) {
250 std::cerr << "ERROR: Could not find bit to distinguish between "
251 << "the following entries!\n";
252 PrintRange(InstsB, InstsE);
256 std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
257 << ": " << InstsE-InstsB << "\n";
260 FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, FirstVaryingBit);
261 } while (FirstVaryingBit != FirstFixedBit);
263 //std::cerr << "\n\nXXXXXXXXXXXXXXXXX\n\n";
264 //PrintRange(InstsB, InstsE);
266 // Sort the Insts list so that the entries have all of the bits in the range
267 // [FirstVaryingBit,LastFixedBit) sorted. These bits are all guaranteed to be
268 // set to either 0 or 1 (BitInit values), which simplifies things.
270 std::sort(InstsB, InstsE, BitComparator(FirstVaryingBit, LastFixedBit));
272 // Once the list is sorted by these bits, split the bit list into smaller
273 // lists, and recurse on each one.
275 std::vector<Record*>::iterator RangeBegin = InstsB;
277 while (RangeBegin != InstsE) {
278 std::vector<Record*>::iterator RangeEnd = RangeBegin+1;
279 while (RangeEnd != InstsE &&
280 BitRangesEqual(*RangeBegin, *RangeEnd, FirstVaryingBit, LastFixedBit))
283 // We just identified a range of equal instructions. If this range is the
284 // input range, we were not able to distinguish between the instructions in
285 // the set. Print an error and exit!
287 if (RangeBegin == InstsB && RangeEnd == InstsE) {
288 std::cerr << "Error: Could not distinguish among the following insts!:\n";
289 PrintRange(InstsB, InstsE);
294 std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
295 << ": [" << RangeEnd-RangeBegin << "] - ";
296 for (int i = LastFixedBit-1; i >= (int)FirstVaryingBit; --i)
297 std::cerr << (int)((BitInit*)getBit(*RangeBegin, i))->getValue() << " ";
301 if (Record *R = ParseMachineCode(RangeBegin, RangeEnd, M)) {
303 std::cerr << "Error: Multiple matches found:\n";
304 PrintRange(InstsB, InstsE);
307 assert(Match == 0 && "Multiple matches??");
310 RangeBegin = RangeEnd;
316 static void PrintValue(Record *I, unsigned char *Ptr, const RecordVal &Val) {
317 assert(dynamic_cast<BitsInit*>(Val.getValue()) &&
318 "Can only handle undefined bits<> types!");
319 BitsInit *BI = (BitsInit*)Val.getValue();
320 assert(BI->getNumBits() <= 32 && "Can only handle fields up to 32 bits!");
323 const std::vector<RecordVal> &Vals = I->getValues();
325 // Start by filling in fixed values...
326 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
327 if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(i)))
328 Value |= B->getValue() << i;
330 // Loop over all of the fields in the instruction adding in any
331 // contributions to this value (due to bit references).
334 for (unsigned f = 0, e = Vals.size(); f != e; ++f)
335 if (Vals[f].getPrefix()) {
336 BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();
337 if (&Vals[f] == &Val) {
338 // Read the bits directly now...
339 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
340 Value |= getMemoryBit(Ptr, Offset+i) << i;
344 // Scan through the field looking for bit initializers of the current
346 for (unsigned i = 0, e = FieldInitializer->getNumBits(); i != e; ++i)
347 if (VarBitInit *VBI =
348 dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) {
349 TypedInit *TI = VBI->getVariable();
350 if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
351 if (VI->getName() == Val.getName())
352 Value |= getMemoryBit(Ptr, Offset+i) << VBI->getBitNum();
353 } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {
354 // FIXME: implement this!
355 std::cerr << "FIELD INIT not implemented yet!\n";
358 Offset += FieldInitializer->getNumBits();
361 std::cout << "0x" << std::hex << Value << std::dec;
364 static void PrintInstruction(Record *I, unsigned char *Ptr) {
365 std::cout << "Inst " << getNumBits(I)/8 << " bytes: "
366 << "\t" << I->getName() << "\t" << *I->getValue("Name")->getValue()
369 const std::vector<RecordVal> &Vals = I->getValues();
370 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
371 if (!Vals[i].getValue()->isComplete()) {
372 std::cout << Vals[i].getName() << "=";
373 PrintValue(I, Ptr, Vals[i]);
377 std::cout << "\n";// << *I;
380 static void ParseMachineCode() {
382 unsigned char Buffer[] = {
384 0x89, 0xE5, // mov EBP, ESP
385 //0x83, 0xEC, 0x08, // sub ESP, 0x8
386 0xE8, 1, 2, 3, 4, // call +0x04030201
387 0x89, 0xEC, // mov ESP, EBP
392 0x89, 0xF6, // mov ESI, ESI
393 0x68, 1, 2, 3, 4, // push 0x04030201
395 0xFF, 0xD0, // call EAX
396 0xB8, 1, 2, 3, 4, // mov EAX, 0x04030201
397 0x85, 0xC0, // test EAX, EAX
403 unsigned char Buffer[] = { 0xbf, 0xe0, 0x20, 0x1f, 0x1, 0x0, 0x0, 0x1,
404 0x0, 0x0, 0x0, 0x0, 0xc1, 0x0, 0x20, 0x1, 0x1,
405 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
406 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1,
407 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
408 0x0, 0x0, 0xaf, 0xe8, 0x20, 0x17
412 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
414 unsigned char *BuffPtr = Buffer;
416 Record *R = ParseMachineCode(Insts.begin(), Insts.end(), BuffPtr);
417 PrintInstruction(R, BuffPtr);
419 unsigned Bits = getNumBits(R);
420 assert((Bits & 7) == 0 && "Instruction is not an even number of bytes!");
425 int main(int argc, char **argv) {
426 cl::ParseCommandLineOptions(argc, argv);
427 ParseFile(InputFilename, IncludeDirs);
429 std::ostream *Out = &std::cout;
430 if (OutputFilename != "-") {
431 Out = new std::ofstream(OutputFilename.c_str());
434 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
438 // Make sure the file gets removed if *gasp* tablegen crashes...
439 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
445 *Out << Records; // No argument, dump all contents
451 CodeEmitterGen(Records).run(*Out);
454 case GenRegisterEnums:
455 RegisterInfoEmitter(Records).runEnums(*Out);
458 RegisterInfoEmitter(Records).run(*Out);
460 case GenRegisterHeader:
461 RegisterInfoEmitter(Records).runHeader(*Out);
465 InstrInfoEmitter(Records).runEnums(*Out);
468 InstrInfoEmitter(Records).run(*Out);
472 AsmWriterEmitter(Records).run(*Out);
476 DAGISelEmitter(Records).run(*Out);
479 SubtargetEmitter(Records).run(*Out);
482 IntrinsicEmitter(Records).run(*Out);
486 std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class);
487 for (unsigned i = 0, e = Recs.size(); i != e; ++i)
488 *Out << Recs[i]->getName() << ", ";
493 assert(1 && "Invalid Action");
496 } catch (const std::string &Error) {
497 std::cerr << argv[0] << ": " << Error << "\n";
498 if (Out != &std::cout) {
499 delete Out; // Close the file
500 std::remove(OutputFilename.c_str()); // Remove the file, it's broken
504 std::cerr << argv[0] << ": Unknown unexpected exception occurred.\n";
505 if (Out != &std::cout) {
506 delete Out; // Close the file
507 std::remove(OutputFilename.c_str()); // Remove the file, it's broken
512 if (Out != &std::cout) {
513 delete Out; // Close the file