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