Privatize the StructType table, which unfortunately involves routing contexts through...
[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 <algorithm>
19 using namespace llvm;
20
21 static void PrintDefList(const std::vector<Record*> &Uses,
22                          unsigned Num, raw_ostream &OS) {
23   OS << "static const unsigned ImplicitList" << Num << "[] = { ";
24   for (unsigned i = 0, e = Uses.size(); i != e; ++i)
25     OS << getQualifiedName(Uses[i]) << ", ";
26   OS << "0 };\n";
27 }
28
29 static void PrintBarriers(std::vector<Record*> &Barriers,
30                           unsigned Num, raw_ostream &OS) {
31   OS << "static const TargetRegisterClass* Barriers" << Num << "[] = { ";
32   for (unsigned i = 0, e = Barriers.size(); i != e; ++i)
33     OS << "&" << getQualifiedName(Barriers[i]) << "RegClass, ";
34   OS << "NULL };\n";
35 }
36
37 //===----------------------------------------------------------------------===//
38 // Instruction Itinerary Information.
39 //===----------------------------------------------------------------------===//
40
41 struct RecordNameComparator {
42   bool operator()(const Record *Rec1, const Record *Rec2) const {
43     return Rec1->getName() < Rec2->getName();
44   }
45 };
46
47 void InstrInfoEmitter::GatherItinClasses() {
48   std::vector<Record*> DefList =
49   Records.getAllDerivedDefinitions("InstrItinClass");
50   std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
51   
52   for (unsigned i = 0, N = DefList.size(); i < N; i++)
53     ItinClassMap[DefList[i]->getName()] = i;
54 }  
55
56 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
57   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
58 }
59
60 //===----------------------------------------------------------------------===//
61 // Operand Info Emission.
62 //===----------------------------------------------------------------------===//
63
64 std::vector<std::string>
65 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
66   std::vector<std::string> Result;
67   
68   for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
69     // Handle aggregate operands and normal operands the same way by expanding
70     // either case into a list of operands for this op.
71     std::vector<CodeGenInstruction::OperandInfo> OperandList;
72
73     // This might be a multiple operand thing.  Targets like X86 have
74     // registers in their multi-operand operands.  It may also be an anonymous
75     // operand, which has a single operand, but no declared class for the
76     // operand.
77     DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
78     
79     if (!MIOI || MIOI->getNumArgs() == 0) {
80       // Single, anonymous, operand.
81       OperandList.push_back(Inst.OperandList[i]);
82     } else {
83       for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
84         OperandList.push_back(Inst.OperandList[i]);
85
86         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
87         OperandList.back().Rec = OpR;
88       }
89     }
90
91     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
92       Record *OpR = OperandList[j].Rec;
93       std::string Res;
94       
95       if (OpR->isSubClassOf("RegisterClass"))
96         Res += getQualifiedName(OpR) + "RegClassID, ";
97       else if (OpR->isSubClassOf("PointerLikeRegClass"))
98         Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
99       else
100         Res += "0, ";
101       
102       // Fill in applicable flags.
103       Res += "0";
104         
105       // Ptr value whose register class is resolved via callback.
106       if (OpR->isSubClassOf("PointerLikeRegClass"))
107         Res += "|(1<<TOI::LookupPtrRegClass)";
108
109       // Predicate operands.  Check to see if the original unexpanded operand
110       // was of type PredicateOperand.
111       if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
112         Res += "|(1<<TOI::Predicate)";
113         
114       // Optional def operands.  Check to see if the original unexpanded operand
115       // was of type OptionalDefOperand.
116       if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
117         Res += "|(1<<TOI::OptionalDef)";
118
119       // Fill in constraint info.
120       Res += ", " + Inst.OperandList[i].Constraints[j];
121       Result.push_back(Res);
122     }
123   }
124
125   return Result;
126 }
127
128 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS, 
129                                        OperandInfoMapTy &OperandInfoIDs) {
130   // ID #0 is for no operand info.
131   unsigned OperandListNum = 0;
132   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
133   
134   OS << "\n";
135   const CodeGenTarget &Target = CDP.getTargetInfo();
136   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
137        E = Target.inst_end(); II != E; ++II) {
138     std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
139     unsigned &N = OperandInfoIDs[OperandInfo];
140     if (N != 0) continue;
141     
142     N = ++OperandListNum;
143     OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
144     for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
145       OS << "{ " << OperandInfo[i] << " }, ";
146     OS << "};\n";
147   }
148 }
149
150 void InstrInfoEmitter::DetectRegisterClassBarriers(std::vector<Record*> &Defs,
151                                   const std::vector<CodeGenRegisterClass> &RCs,
152                                   std::vector<Record*> &Barriers) {
153   std::set<Record*> DefSet;
154   unsigned NumDefs = Defs.size();
155   for (unsigned i = 0; i < NumDefs; ++i)
156     DefSet.insert(Defs[i]);
157
158   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
159     const CodeGenRegisterClass &RC = RCs[i];
160     unsigned NumRegs = RC.Elements.size();
161     if (NumRegs > NumDefs)
162       continue; // Can't possibly clobber this RC.
163
164     bool Clobber = true;
165     for (unsigned j = 0; j < NumRegs; ++j) {
166       Record *Reg = RC.Elements[j];
167       if (!DefSet.count(Reg)) {
168         Clobber = false;
169         break;
170       }
171     }
172     if (Clobber)
173       Barriers.push_back(RC.TheDef);
174   }
175 }
176
177 //===----------------------------------------------------------------------===//
178 // Main Output.
179 //===----------------------------------------------------------------------===//
180
181 // run - Emit the main instruction description records for the target...
182 void InstrInfoEmitter::run(raw_ostream &OS) {
183   GatherItinClasses();
184
185   EmitSourceFileHeader("Target Instruction Descriptors", OS);
186   OS << "namespace llvm {\n\n";
187
188   CodeGenTarget &Target = CDP.getTargetInfo();
189   const std::string &TargetName = Target.getName();
190   Record *InstrInfo = Target.getInstructionSet();
191   const std::vector<CodeGenRegisterClass> &RCs = Target.getRegisterClasses();
192
193   // Keep track of all of the def lists we have emitted already.
194   std::map<std::vector<Record*>, unsigned> EmittedLists;
195   unsigned ListNumber = 0;
196   std::map<std::vector<Record*>, unsigned> EmittedBarriers;
197   unsigned BarrierNumber = 0;
198   std::map<Record*, unsigned> BarriersMap;
199  
200   // Emit all of the instruction's implicit uses and defs.
201   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
202          E = Target.inst_end(); II != E; ++II) {
203     Record *Inst = II->second.TheDef;
204     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
205     if (!Uses.empty()) {
206       unsigned &IL = EmittedLists[Uses];
207       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
208     }
209     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
210     if (!Defs.empty()) {
211       std::vector<Record*> RCBarriers;
212       DetectRegisterClassBarriers(Defs, RCs, RCBarriers);
213       if (!RCBarriers.empty()) {
214         unsigned &IB = EmittedBarriers[RCBarriers];
215         if (!IB) PrintBarriers(RCBarriers, IB = ++BarrierNumber, OS);
216         BarriersMap.insert(std::make_pair(Inst, IB));
217       }
218
219       unsigned &IL = EmittedLists[Defs];
220       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
221     }
222   }
223
224   OperandInfoMapTy OperandInfoIDs;
225   
226   // Emit all of the operand info records.
227   EmitOperandInfo(OS, OperandInfoIDs);
228   
229   // Emit all of the TargetInstrDesc records in their ENUM ordering.
230   //
231   OS << "\nstatic const TargetInstrDesc " << TargetName
232      << "Insts[] = {\n";
233   std::vector<const CodeGenInstruction*> NumberedInstructions;
234   Target.getInstructionsByEnumValue(NumberedInstructions);
235
236   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
237     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
238                BarriersMap, OperandInfoIDs, OS);
239   OS << "};\n";
240   OS << "} // End llvm namespace \n";
241 }
242
243 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
244                                   Record *InstrInfo,
245                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
246                                   std::map<Record*, unsigned> &BarriersMap,
247                                   const OperandInfoMapTy &OpInfo,
248                                   raw_ostream &OS) {
249   int MinOperands = 0;
250   if (!Inst.OperandList.empty())
251     // Each logical operand can be multiple MI operands.
252     MinOperands = Inst.OperandList.back().MIOperandNo +
253                   Inst.OperandList.back().MINumOperands;
254
255   OS << "  { ";
256   OS << Num << ",\t" << MinOperands << ",\t"
257      << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
258      << ",\t\"" << Inst.TheDef->getName() << "\", 0";
259
260   // Emit all of the target indepedent flags...
261   if (Inst.isReturn)           OS << "|(1<<TID::Return)";
262   if (Inst.isBranch)           OS << "|(1<<TID::Branch)";
263   if (Inst.isIndirectBranch)   OS << "|(1<<TID::IndirectBranch)";
264   if (Inst.isBarrier)          OS << "|(1<<TID::Barrier)";
265   if (Inst.hasDelaySlot)       OS << "|(1<<TID::DelaySlot)";
266   if (Inst.isCall)             OS << "|(1<<TID::Call)";
267   if (Inst.canFoldAsLoad)      OS << "|(1<<TID::FoldableAsLoad)";
268   if (Inst.mayLoad)            OS << "|(1<<TID::MayLoad)";
269   if (Inst.mayStore)           OS << "|(1<<TID::MayStore)";
270   if (Inst.isPredicable)       OS << "|(1<<TID::Predicable)";
271   if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
272   if (Inst.isCommutable)       OS << "|(1<<TID::Commutable)";
273   if (Inst.isTerminator)       OS << "|(1<<TID::Terminator)";
274   if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
275   if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
276   if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
277   if (Inst.usesCustomDAGSchedInserter)
278     OS << "|(1<<TID::UsesCustomDAGSchedInserter)";
279   if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
280   if (Inst.hasSideEffects)     OS << "|(1<<TID::UnmodeledSideEffects)";
281   if (Inst.isAsCheapAsAMove)   OS << "|(1<<TID::CheapAsAMove)";
282   OS << ", 0";
283
284   // Emit all of the target-specific flags...
285   ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
286   ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
287   if (LI->getSize() != Shift->getSize())
288     throw "Lengths of " + InstrInfo->getName() +
289           ":(TargetInfoFields, TargetInfoPositions) must be equal!";
290
291   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
292     emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
293                      dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
294
295   OS << ", ";
296
297   // Emit the implicit uses and defs lists...
298   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
299   if (UseList.empty())
300     OS << "NULL, ";
301   else
302     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
303
304   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
305   if (DefList.empty())
306     OS << "NULL, ";
307   else
308     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
309
310   std::map<Record*, unsigned>::iterator BI = BarriersMap.find(Inst.TheDef);
311   if (BI == BarriersMap.end())
312     OS << "NULL, ";
313   else
314     OS << "Barriers" << BI->second << ", ";
315
316   // Emit the operand info.
317   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
318   if (OperandInfo.empty())
319     OS << "0";
320   else
321     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
322   
323   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
324 }
325
326
327 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
328                                         IntInit *ShiftInt, raw_ostream &OS) {
329   if (Val == 0 || ShiftInt == 0)
330     throw std::string("Illegal value or shift amount in TargetInfo*!");
331   RecordVal *RV = R->getValue(Val->getValue());
332   int Shift = ShiftInt->getValue();
333
334   if (RV == 0 || RV->getValue() == 0) {
335     // This isn't an error if this is a builtin instruction.
336     if (R->getName() != "PHI" &&
337         R->getName() != "INLINEASM" &&
338         R->getName() != "DBG_LABEL" &&
339         R->getName() != "EH_LABEL" &&
340         R->getName() != "GC_LABEL" &&
341         R->getName() != "DECLARE" &&
342         R->getName() != "EXTRACT_SUBREG" &&
343         R->getName() != "INSERT_SUBREG" &&
344         R->getName() != "IMPLICIT_DEF" &&
345         R->getName() != "SUBREG_TO_REG" &&
346         R->getName() != "COPY_TO_REGCLASS")
347       throw R->getName() + " doesn't have a field named '" + 
348             Val->getValue() + "'!";
349     return;
350   }
351
352   Init *Value = RV->getValue();
353   if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
354     if (BI->getValue()) OS << "|(1<<" << Shift << ")";
355     return;
356   } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
357     // Convert the Bits to an integer to print...
358     Init *I = BI->convertInitializerTo(new IntRecTy());
359     if (I)
360       if (IntInit *II = dynamic_cast<IntInit*>(I)) {
361         if (II->getValue()) {
362           if (Shift)
363             OS << "|(" << II->getValue() << "<<" << Shift << ")";
364           else
365             OS << "|" << II->getValue();
366         }
367         return;
368       }
369
370   } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
371     if (II->getValue()) {
372       if (Shift)
373         OS << "|(" << II->getValue() << "<<" << Shift << ")";
374       else
375         OS << II->getValue();
376     }
377     return;
378   }
379
380   errs() << "Unhandled initializer: " << *Val << "\n";
381   throw "In record '" + R->getName() + "' for TSFlag emission.";
382 }
383