Use SequenceToOffsetTable to create instruction name table. Saves space particularly...
[oota-llvm.git] / utils / TableGen / InstrInfoEmitter.cpp
1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
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 // This tablegen backend is responsible for emitting a description of the target
11 // instruction set for the code generator.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstrInfoEmitter.h"
16 #include "CodeGenTarget.h"
17 #include "SequenceToOffsetTable.h"
18 #include "llvm/TableGen/Record.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include <algorithm>
21 #include <cstdio>
22 using namespace llvm;
23
24 static void PrintDefList(const std::vector<Record*> &Uses,
25                          unsigned Num, raw_ostream &OS) {
26   OS << "static const uint16_t ImplicitList" << Num << "[] = { ";
27   for (unsigned i = 0, e = Uses.size(); i != e; ++i)
28     OS << getQualifiedName(Uses[i]) << ", ";
29   OS << "0 };\n";
30 }
31
32 //===----------------------------------------------------------------------===//
33 // Instruction Itinerary Information.
34 //===----------------------------------------------------------------------===//
35
36 void InstrInfoEmitter::GatherItinClasses() {
37   std::vector<Record*> DefList =
38   Records.getAllDerivedDefinitions("InstrItinClass");
39   std::sort(DefList.begin(), DefList.end(), LessRecord());
40
41   for (unsigned i = 0, N = DefList.size(); i < N; i++)
42     ItinClassMap[DefList[i]->getName()] = i;
43 }
44
45 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
46   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
47 }
48
49 //===----------------------------------------------------------------------===//
50 // Operand Info Emission.
51 //===----------------------------------------------------------------------===//
52
53 std::vector<std::string>
54 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
55   std::vector<std::string> Result;
56
57   for (unsigned i = 0, e = Inst.Operands.size(); i != e; ++i) {
58     // Handle aggregate operands and normal operands the same way by expanding
59     // either case into a list of operands for this op.
60     std::vector<CGIOperandList::OperandInfo> OperandList;
61
62     // This might be a multiple operand thing.  Targets like X86 have
63     // registers in their multi-operand operands.  It may also be an anonymous
64     // operand, which has a single operand, but no declared class for the
65     // operand.
66     DagInit *MIOI = Inst.Operands[i].MIOperandInfo;
67
68     if (!MIOI || MIOI->getNumArgs() == 0) {
69       // Single, anonymous, operand.
70       OperandList.push_back(Inst.Operands[i]);
71     } else {
72       for (unsigned j = 0, e = Inst.Operands[i].MINumOperands; j != e; ++j) {
73         OperandList.push_back(Inst.Operands[i]);
74
75         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
76         OperandList.back().Rec = OpR;
77       }
78     }
79
80     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
81       Record *OpR = OperandList[j].Rec;
82       std::string Res;
83
84       if (OpR->isSubClassOf("RegisterOperand"))
85         OpR = OpR->getValueAsDef("RegClass");
86       if (OpR->isSubClassOf("RegisterClass"))
87         Res += getQualifiedName(OpR) + "RegClassID, ";
88       else if (OpR->isSubClassOf("PointerLikeRegClass"))
89         Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
90       else
91         // -1 means the operand does not have a fixed register class.
92         Res += "-1, ";
93
94       // Fill in applicable flags.
95       Res += "0";
96
97       // Ptr value whose register class is resolved via callback.
98       if (OpR->isSubClassOf("PointerLikeRegClass"))
99         Res += "|(1<<MCOI::LookupPtrRegClass)";
100
101       // Predicate operands.  Check to see if the original unexpanded operand
102       // was of type PredicateOperand.
103       if (Inst.Operands[i].Rec->isSubClassOf("PredicateOperand"))
104         Res += "|(1<<MCOI::Predicate)";
105
106       // Optional def operands.  Check to see if the original unexpanded operand
107       // was of type OptionalDefOperand.
108       if (Inst.Operands[i].Rec->isSubClassOf("OptionalDefOperand"))
109         Res += "|(1<<MCOI::OptionalDef)";
110
111       // Fill in operand type.
112       Res += ", MCOI::";
113       assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand type.");
114       Res += Inst.Operands[i].OperandType;
115
116       // Fill in constraint info.
117       Res += ", ";
118
119       const CGIOperandList::ConstraintInfo &Constraint =
120         Inst.Operands[i].Constraints[j];
121       if (Constraint.isNone())
122         Res += "0";
123       else if (Constraint.isEarlyClobber())
124         Res += "(1 << MCOI::EARLY_CLOBBER)";
125       else {
126         assert(Constraint.isTied());
127         Res += "((" + utostr(Constraint.getTiedOperand()) +
128                     " << 16) | (1 << MCOI::TIED_TO))";
129       }
130
131       Result.push_back(Res);
132     }
133   }
134
135   return Result;
136 }
137
138 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS,
139                                        OperandInfoMapTy &OperandInfoIDs) {
140   // ID #0 is for no operand info.
141   unsigned OperandListNum = 0;
142   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
143
144   OS << "\n";
145   const CodeGenTarget &Target = CDP.getTargetInfo();
146   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
147        E = Target.inst_end(); II != E; ++II) {
148     std::vector<std::string> OperandInfo = GetOperandInfo(**II);
149     unsigned &N = OperandInfoIDs[OperandInfo];
150     if (N != 0) continue;
151
152     N = ++OperandListNum;
153     OS << "static const MCOperandInfo OperandInfo" << N << "[] = { ";
154     for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
155       OS << "{ " << OperandInfo[i] << " }, ";
156     OS << "};\n";
157   }
158 }
159
160 //===----------------------------------------------------------------------===//
161 // Main Output.
162 //===----------------------------------------------------------------------===//
163
164 // run - Emit the main instruction description records for the target...
165 void InstrInfoEmitter::run(raw_ostream &OS) {
166   emitEnums(OS);
167
168   GatherItinClasses();
169
170   EmitSourceFileHeader("Target Instruction Descriptors", OS);
171
172   OS << "\n#ifdef GET_INSTRINFO_MC_DESC\n";
173   OS << "#undef GET_INSTRINFO_MC_DESC\n";
174
175   OS << "namespace llvm {\n\n";
176
177   CodeGenTarget &Target = CDP.getTargetInfo();
178   const std::string &TargetName = Target.getName();
179   Record *InstrInfo = Target.getInstructionSet();
180
181   // Keep track of all of the def lists we have emitted already.
182   std::map<std::vector<Record*>, unsigned> EmittedLists;
183   unsigned ListNumber = 0;
184
185   // Emit all of the instruction's implicit uses and defs.
186   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
187          E = Target.inst_end(); II != E; ++II) {
188     Record *Inst = (*II)->TheDef;
189     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
190     if (!Uses.empty()) {
191       unsigned &IL = EmittedLists[Uses];
192       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
193     }
194     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
195     if (!Defs.empty()) {
196       unsigned &IL = EmittedLists[Defs];
197       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
198     }
199   }
200
201   OperandInfoMapTy OperandInfoIDs;
202
203   // Emit all of the operand info records.
204   EmitOperandInfo(OS, OperandInfoIDs);
205
206   // Emit all of the MCInstrDesc records in their ENUM ordering.
207   //
208   OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] = {\n";
209   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
210     Target.getInstructionsByEnumValue();
211
212   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
213     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
214                OperandInfoIDs, OS);
215   OS << "};\n\n";
216
217   // Build an array of instruction names
218   SequenceToOffsetTable<std::string> InstrNames;
219   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
220     const CodeGenInstruction *Instr = NumberedInstructions[i];
221     InstrNames.add(Instr->TheDef->getName());
222   }
223
224   InstrNames.layout();
225   OS << "extern const char " << TargetName << "InstrNameData[] = {\n";
226   InstrNames.emit(OS, printChar);
227   OS << "};\n\n";
228
229   OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] = {";
230   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
231     if (i % 8 == 0)
232       OS << "\n    ";
233     const CodeGenInstruction *Instr = NumberedInstructions[i];
234     OS << InstrNames.get(Instr->TheDef->getName()) << "U, ";
235   }
236
237   OS << "\n};\n\n";
238
239   // MCInstrInfo initialization routine.
240   OS << "static inline void Init" << TargetName
241      << "MCInstrInfo(MCInstrInfo *II) {\n";
242   OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, "
243      << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
244      << NumberedInstructions.size() << ");\n}\n\n";
245
246   OS << "} // End llvm namespace \n";
247
248   OS << "#endif // GET_INSTRINFO_MC_DESC\n\n";
249
250   // Create a TargetInstrInfo subclass to hide the MC layer initialization.
251   OS << "\n#ifdef GET_INSTRINFO_HEADER\n";
252   OS << "#undef GET_INSTRINFO_HEADER\n";
253
254   std::string ClassName = TargetName + "GenInstrInfo";
255   OS << "namespace llvm {\n";
256   OS << "struct " << ClassName << " : public TargetInstrInfoImpl {\n"
257      << "  explicit " << ClassName << "(int SO = -1, int DO = -1);\n"
258      << "};\n";
259   OS << "} // End llvm namespace \n";
260
261   OS << "#endif // GET_INSTRINFO_HEADER\n\n";
262
263   OS << "\n#ifdef GET_INSTRINFO_CTOR\n";
264   OS << "#undef GET_INSTRINFO_CTOR\n";
265
266   OS << "namespace llvm {\n";
267   OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
268   OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
269   OS << "extern const char " << TargetName << "InstrNameData[];\n";
270   OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
271      << "  : TargetInstrInfoImpl(SO, DO) {\n"
272      << "  InitMCInstrInfo(" << TargetName << "Insts, "
273      << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData, "
274      << NumberedInstructions.size() << ");\n}\n";
275   OS << "} // End llvm namespace \n";
276
277   OS << "#endif // GET_INSTRINFO_CTOR\n\n";
278 }
279
280 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
281                                   Record *InstrInfo,
282                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
283                                   const OperandInfoMapTy &OpInfo,
284                                   raw_ostream &OS) {
285   int MinOperands = 0;
286   if (!Inst.Operands.size() == 0)
287     // Each logical operand can be multiple MI operands.
288     MinOperands = Inst.Operands.back().MIOperandNo +
289                   Inst.Operands.back().MINumOperands;
290
291   OS << "  { ";
292   OS << Num << ",\t" << MinOperands << ",\t"
293      << Inst.Operands.NumDefs << ",\t"
294      << getItinClassNumber(Inst.TheDef) << ",\t"
295      << Inst.TheDef->getValueAsInt("Size") << ",\t0";
296
297   // Emit all of the target indepedent flags...
298   if (Inst.isPseudo)           OS << "|(1<<MCID::Pseudo)";
299   if (Inst.isReturn)           OS << "|(1<<MCID::Return)";
300   if (Inst.isBranch)           OS << "|(1<<MCID::Branch)";
301   if (Inst.isIndirectBranch)   OS << "|(1<<MCID::IndirectBranch)";
302   if (Inst.isCompare)          OS << "|(1<<MCID::Compare)";
303   if (Inst.isMoveImm)          OS << "|(1<<MCID::MoveImm)";
304   if (Inst.isBitcast)          OS << "|(1<<MCID::Bitcast)";
305   if (Inst.isBarrier)          OS << "|(1<<MCID::Barrier)";
306   if (Inst.hasDelaySlot)       OS << "|(1<<MCID::DelaySlot)";
307   if (Inst.isCall)             OS << "|(1<<MCID::Call)";
308   if (Inst.canFoldAsLoad)      OS << "|(1<<MCID::FoldableAsLoad)";
309   if (Inst.mayLoad)            OS << "|(1<<MCID::MayLoad)";
310   if (Inst.mayStore)           OS << "|(1<<MCID::MayStore)";
311   if (Inst.isPredicable)       OS << "|(1<<MCID::Predicable)";
312   if (Inst.isConvertibleToThreeAddress) OS << "|(1<<MCID::ConvertibleTo3Addr)";
313   if (Inst.isCommutable)       OS << "|(1<<MCID::Commutable)";
314   if (Inst.isTerminator)       OS << "|(1<<MCID::Terminator)";
315   if (Inst.isReMaterializable) OS << "|(1<<MCID::Rematerializable)";
316   if (Inst.isNotDuplicable)    OS << "|(1<<MCID::NotDuplicable)";
317   if (Inst.Operands.hasOptionalDef) OS << "|(1<<MCID::HasOptionalDef)";
318   if (Inst.usesCustomInserter) OS << "|(1<<MCID::UsesCustomInserter)";
319   if (Inst.hasPostISelHook)    OS << "|(1<<MCID::HasPostISelHook)";
320   if (Inst.Operands.isVariadic)OS << "|(1<<MCID::Variadic)";
321   if (Inst.hasSideEffects)     OS << "|(1<<MCID::UnmodeledSideEffects)";
322   if (Inst.isAsCheapAsAMove)   OS << "|(1<<MCID::CheapAsAMove)";
323   if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<MCID::ExtraSrcRegAllocReq)";
324   if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<MCID::ExtraDefRegAllocReq)";
325
326   // Emit all of the target-specific flags...
327   BitsInit *TSF = Inst.TheDef->getValueAsBitsInit("TSFlags");
328   if (!TSF) throw "no TSFlags?";
329   uint64_t Value = 0;
330   for (unsigned i = 0, e = TSF->getNumBits(); i != e; ++i) {
331     if (BitInit *Bit = dynamic_cast<BitInit*>(TSF->getBit(i)))
332       Value |= uint64_t(Bit->getValue()) << i;
333     else
334       throw "Invalid TSFlags bit in " + Inst.TheDef->getName();
335   }
336   OS << ", 0x";
337   OS.write_hex(Value);
338   OS << "ULL, ";
339
340   // Emit the implicit uses and defs lists...
341   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
342   if (UseList.empty())
343     OS << "NULL, ";
344   else
345     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
346
347   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
348   if (DefList.empty())
349     OS << "NULL, ";
350   else
351     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
352
353   // Emit the operand info.
354   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
355   if (OperandInfo.empty())
356     OS << "0";
357   else
358     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
359
360   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
361 }
362
363 // emitEnums - Print out enum values for all of the instructions.
364 void InstrInfoEmitter::emitEnums(raw_ostream &OS) {
365   EmitSourceFileHeader("Target Instruction Enum Values", OS);
366
367   OS << "\n#ifdef GET_INSTRINFO_ENUM\n";
368   OS << "#undef GET_INSTRINFO_ENUM\n";
369
370   OS << "namespace llvm {\n\n";
371
372   CodeGenTarget Target(Records);
373
374   // We must emit the PHI opcode first...
375   std::string Namespace = Target.getInstNamespace();
376   
377   if (Namespace.empty()) {
378     fprintf(stderr, "No instructions defined!\n");
379     exit(1);
380   }
381
382   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
383     Target.getInstructionsByEnumValue();
384
385   OS << "namespace " << Namespace << " {\n";
386   OS << "  enum {\n";
387   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
388     OS << "    " << NumberedInstructions[i]->TheDef->getName()
389        << "\t= " << i << ",\n";
390   }
391   OS << "    INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
392   OS << "  };\n}\n";
393   OS << "} // End llvm namespace \n";
394
395   OS << "#endif // GET_INSTRINFO_ENUM\n\n";
396 }