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