How about ULL...
[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 void InstrInfoEmitter::GatherItinClasses() {
43   std::vector<Record*> DefList =
44   Records.getAllDerivedDefinitions("InstrItinClass");
45   std::sort(DefList.begin(), DefList.end(), LessRecord());
46   
47   for (unsigned i = 0, N = DefList.size(); i < N; i++)
48     ItinClassMap[DefList[i]->getName()] = i;
49 }  
50
51 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
52   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
53 }
54
55 //===----------------------------------------------------------------------===//
56 // Operand Info Emission.
57 //===----------------------------------------------------------------------===//
58
59 std::vector<std::string>
60 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
61   std::vector<std::string> Result;
62   
63   for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
64     // Handle aggregate operands and normal operands the same way by expanding
65     // either case into a list of operands for this op.
66     std::vector<CodeGenInstruction::OperandInfo> OperandList;
67
68     // This might be a multiple operand thing.  Targets like X86 have
69     // registers in their multi-operand operands.  It may also be an anonymous
70     // operand, which has a single operand, but no declared class for the
71     // operand.
72     DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
73     
74     if (!MIOI || MIOI->getNumArgs() == 0) {
75       // Single, anonymous, operand.
76       OperandList.push_back(Inst.OperandList[i]);
77     } else {
78       for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
79         OperandList.push_back(Inst.OperandList[i]);
80
81         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
82         OperandList.back().Rec = OpR;
83       }
84     }
85
86     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
87       Record *OpR = OperandList[j].Rec;
88       std::string Res;
89       
90       if (OpR->isSubClassOf("RegisterClass"))
91         Res += getQualifiedName(OpR) + "RegClassID, ";
92       else if (OpR->isSubClassOf("PointerLikeRegClass"))
93         Res += utostr(OpR->getValueAsInt("RegClassKind")) + ", ";
94       else
95         Res += "0, ";
96       
97       // Fill in applicable flags.
98       Res += "0";
99         
100       // Ptr value whose register class is resolved via callback.
101       if (OpR->isSubClassOf("PointerLikeRegClass"))
102         Res += "|(1<<TOI::LookupPtrRegClass)";
103
104       // Predicate operands.  Check to see if the original unexpanded operand
105       // was of type PredicateOperand.
106       if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
107         Res += "|(1<<TOI::Predicate)";
108         
109       // Optional def operands.  Check to see if the original unexpanded operand
110       // was of type OptionalDefOperand.
111       if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
112         Res += "|(1<<TOI::OptionalDef)";
113
114       // Fill in constraint info.
115       Res += ", ";
116       
117       const CodeGenInstruction::ConstraintInfo &Constraint =
118         Inst.OperandList[i].Constraints[j];
119       if (Constraint.isNone())
120         Res += "0";
121       else if (Constraint.isEarlyClobber())
122         Res += "(1 << TOI::EARLY_CLOBBER)";
123       else {
124         assert(Constraint.isTied());
125         Res += "((" + utostr(Constraint.getTiedOperand()) +
126                     " << 16) | (1 << TOI::TIED_TO))";
127       }
128         
129       Result.push_back(Res);
130     }
131   }
132
133   return Result;
134 }
135
136 void InstrInfoEmitter::EmitOperandInfo(raw_ostream &OS, 
137                                        OperandInfoMapTy &OperandInfoIDs) {
138   // ID #0 is for no operand info.
139   unsigned OperandListNum = 0;
140   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
141   
142   OS << "\n";
143   const CodeGenTarget &Target = CDP.getTargetInfo();
144   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
145        E = Target.inst_end(); II != E; ++II) {
146     std::vector<std::string> OperandInfo = GetOperandInfo(**II);
147     unsigned &N = OperandInfoIDs[OperandInfo];
148     if (N != 0) continue;
149     
150     N = ++OperandListNum;
151     OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
152     for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
153       OS << "{ " << OperandInfo[i] << " }, ";
154     OS << "};\n";
155   }
156 }
157
158 void InstrInfoEmitter::DetectRegisterClassBarriers(std::vector<Record*> &Defs,
159                                   const std::vector<CodeGenRegisterClass> &RCs,
160                                   std::vector<Record*> &Barriers) {
161   std::set<Record*> DefSet;
162   unsigned NumDefs = Defs.size();
163   for (unsigned i = 0; i < NumDefs; ++i)
164     DefSet.insert(Defs[i]);
165
166   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
167     const CodeGenRegisterClass &RC = RCs[i];
168     unsigned NumRegs = RC.Elements.size();
169     if (NumRegs > NumDefs)
170       continue; // Can't possibly clobber this RC.
171
172     bool Clobber = true;
173     for (unsigned j = 0; j < NumRegs; ++j) {
174       Record *Reg = RC.Elements[j];
175       if (!DefSet.count(Reg)) {
176         Clobber = false;
177         break;
178       }
179     }
180     if (Clobber)
181       Barriers.push_back(RC.TheDef);
182   }
183 }
184
185 //===----------------------------------------------------------------------===//
186 // Main Output.
187 //===----------------------------------------------------------------------===//
188
189 // run - Emit the main instruction description records for the target...
190 void InstrInfoEmitter::run(raw_ostream &OS) {
191   GatherItinClasses();
192
193   EmitSourceFileHeader("Target Instruction Descriptors", OS);
194   OS << "namespace llvm {\n\n";
195
196   CodeGenTarget &Target = CDP.getTargetInfo();
197   const std::string &TargetName = Target.getName();
198   Record *InstrInfo = Target.getInstructionSet();
199   const std::vector<CodeGenRegisterClass> &RCs = Target.getRegisterClasses();
200
201   // Keep track of all of the def lists we have emitted already.
202   std::map<std::vector<Record*>, unsigned> EmittedLists;
203   unsigned ListNumber = 0;
204   std::map<std::vector<Record*>, unsigned> EmittedBarriers;
205   unsigned BarrierNumber = 0;
206   std::map<Record*, unsigned> BarriersMap;
207  
208   // Emit all of the instruction's implicit uses and defs.
209   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
210          E = Target.inst_end(); II != E; ++II) {
211     Record *Inst = (*II)->TheDef;
212     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
213     if (!Uses.empty()) {
214       unsigned &IL = EmittedLists[Uses];
215       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
216     }
217     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
218     if (!Defs.empty()) {
219       std::vector<Record*> RCBarriers;
220       DetectRegisterClassBarriers(Defs, RCs, RCBarriers);
221       if (!RCBarriers.empty()) {
222         unsigned &IB = EmittedBarriers[RCBarriers];
223         if (!IB) PrintBarriers(RCBarriers, IB = ++BarrierNumber, OS);
224         BarriersMap.insert(std::make_pair(Inst, IB));
225       }
226
227       unsigned &IL = EmittedLists[Defs];
228       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
229     }
230   }
231
232   OperandInfoMapTy OperandInfoIDs;
233   
234   // Emit all of the operand info records.
235   EmitOperandInfo(OS, OperandInfoIDs);
236   
237   // Emit all of the TargetInstrDesc records in their ENUM ordering.
238   //
239   OS << "\nstatic const TargetInstrDesc " << TargetName
240      << "Insts[] = {\n";
241   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
242     Target.getInstructionsByEnumValue();
243
244   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
245     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
246                BarriersMap, OperandInfoIDs, OS);
247   OS << "};\n";
248   OS << "} // End llvm namespace \n";
249 }
250
251 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
252                                   Record *InstrInfo,
253                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
254                                   std::map<Record*, unsigned> &BarriersMap,
255                                   const OperandInfoMapTy &OpInfo,
256                                   raw_ostream &OS) {
257   int MinOperands = 0;
258   if (!Inst.OperandList.empty())
259     // Each logical operand can be multiple MI operands.
260     MinOperands = Inst.OperandList.back().MIOperandNo +
261                   Inst.OperandList.back().MINumOperands;
262
263   OS << "  { ";
264   OS << Num << ",\t" << MinOperands << ",\t"
265      << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
266      << ",\t\"" << Inst.TheDef->getName() << "\", 0";
267
268   // Emit all of the target indepedent flags...
269   if (Inst.isReturn)           OS << "|(1<<TID::Return)";
270   if (Inst.isBranch)           OS << "|(1<<TID::Branch)";
271   if (Inst.isIndirectBranch)   OS << "|(1<<TID::IndirectBranch)";
272   if (Inst.isBarrier)          OS << "|(1<<TID::Barrier)";
273   if (Inst.hasDelaySlot)       OS << "|(1<<TID::DelaySlot)";
274   if (Inst.isCall)             OS << "|(1<<TID::Call)";
275   if (Inst.canFoldAsLoad)      OS << "|(1<<TID::FoldableAsLoad)";
276   if (Inst.mayLoad)            OS << "|(1<<TID::MayLoad)";
277   if (Inst.mayStore)           OS << "|(1<<TID::MayStore)";
278   if (Inst.isPredicable)       OS << "|(1<<TID::Predicable)";
279   if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
280   if (Inst.isCommutable)       OS << "|(1<<TID::Commutable)";
281   if (Inst.isTerminator)       OS << "|(1<<TID::Terminator)";
282   if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
283   if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
284   if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
285   if (Inst.usesCustomInserter) OS << "|(1<<TID::UsesCustomInserter)";
286   if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
287   if (Inst.hasSideEffects)     OS << "|(1<<TID::UnmodeledSideEffects)";
288   if (Inst.isAsCheapAsAMove)   OS << "|(1<<TID::CheapAsAMove)";
289   if (Inst.hasExtraSrcRegAllocReq) OS << "|(1<<TID::ExtraSrcRegAllocReq)";
290   if (Inst.hasExtraDefRegAllocReq) OS << "|(1<<TID::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   std::map<Record*, unsigned>::iterator BI = BarriersMap.find(Inst.TheDef);
320   if (BI == BarriersMap.end())
321     OS << "NULL, ";
322   else
323     OS << "Barriers" << BI->second << ", ";
324
325   // Emit the operand info.
326   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
327   if (OperandInfo.empty())
328     OS << "0";
329   else
330     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
331
332   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
333 }