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