simplify some code
[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 #include <iostream>
20 using namespace llvm;
21
22 void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
23                                     unsigned Num, std::ostream &OS) const {
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 std::vector<std::string>
31 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
32   std::vector<std::string> Result;
33   
34   for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
35     // Handle aggregate operands and normal operands the same way by expanding
36     // either case into a list of operands for this op.
37     std::vector<CodeGenInstruction::OperandInfo> OperandList;
38
39     // This might be a multiple operand thing.  Targets like X86 have
40     // registers in their multi-operand operands.  It may also be an anonymous
41     // operand, which has a single operand, but no declared class for the
42     // operand.
43     DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
44     
45     if (!MIOI || MIOI->getNumArgs() == 0) {
46       // Single, anonymous, operand.
47       OperandList.push_back(Inst.OperandList[i]);
48     } else {
49       for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
50         OperandList.push_back(Inst.OperandList[i]);
51
52         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
53         OperandList.back().Rec = OpR;
54       }
55     }
56
57     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
58       Record *OpR = OperandList[j].Rec;
59       std::string Res;
60       
61       if (OpR->isSubClassOf("RegisterClass"))
62         Res += getQualifiedName(OpR) + "RegClassID, ";
63       else
64         Res += "0, ";
65       // Fill in applicable flags.
66       Res += "0";
67         
68       // Ptr value whose register class is resolved via callback.
69       if (OpR->getName() == "ptr_rc")
70         Res += "|M_LOOK_UP_PTR_REG_CLASS";
71
72       // Predicate operands.  Check to see if the original unexpanded operand
73       // was of type PredicateOperand.
74       if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
75         Res += "|M_PREDICATE_OPERAND";
76         
77       // Optional def operands.  Check to see if the original unexpanded operand
78       // was of type OptionalDefOperand.
79       if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
80         Res += "|M_OPTIONAL_DEF_OPERAND";
81
82       // Fill in constraint info.
83       Res += ", " + Inst.OperandList[i].Constraints[j];
84       Result.push_back(Res);
85     }
86   }
87
88   return Result;
89 }
90
91
92 // run - Emit the main instruction description records for the target...
93 void InstrInfoEmitter::run(std::ostream &OS) {
94   GatherItinClasses();
95
96   EmitSourceFileHeader("Target Instruction Descriptors", OS);
97   OS << "namespace llvm {\n\n";
98
99   CodeGenTarget Target;
100   const std::string &TargetName = Target.getName();
101   Record *InstrInfo = Target.getInstructionSet();
102
103   // Keep track of all of the def lists we have emitted already.
104   std::map<std::vector<Record*>, unsigned> EmittedLists;
105   unsigned ListNumber = 0;
106  
107   // Emit all of the instruction's implicit uses and defs.
108   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
109          E = Target.inst_end(); II != E; ++II) {
110     Record *Inst = II->second.TheDef;
111     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
112     if (!Uses.empty()) {
113       unsigned &IL = EmittedLists[Uses];
114       if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
115     }
116     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
117     if (!Defs.empty()) {
118       unsigned &IL = EmittedLists[Defs];
119       if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
120     }
121   }
122
123   std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
124   unsigned OperandListNum = 0;
125   OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
126   
127   // Emit all of the operand info records.
128   OS << "\n";
129   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
130        E = Target.inst_end(); II != E; ++II) {
131     std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
132     unsigned &N = OperandInfosEmitted[OperandInfo];
133     if (N == 0) {
134       N = ++OperandListNum;
135       OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
136       for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
137         OS << "{ " << OperandInfo[i] << " }, ";
138       OS << "};\n";
139     }
140   }
141   
142   // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
143   //
144   OS << "\nstatic const TargetInstrDescriptor " << TargetName
145      << "Insts[] = {\n";
146   std::vector<const CodeGenInstruction*> NumberedInstructions;
147   Target.getInstructionsByEnumValue(NumberedInstructions);
148
149   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
150     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
151                OperandInfosEmitted, OS);
152   OS << "};\n";
153   OS << "} // End llvm namespace \n";
154 }
155
156 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
157                                   Record *InstrInfo,
158                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
159                            std::map<std::vector<std::string>, unsigned> &OpInfo,
160                                   std::ostream &OS) {
161   int MinOperands;
162   if (!Inst.OperandList.empty())
163     // Each logical operand can be multiple MI operands.
164     MinOperands = Inst.OperandList.back().MIOperandNo +
165                   Inst.OperandList.back().MINumOperands;
166   else
167     MinOperands = 0;
168   
169   OS << "  { ";
170   OS << Num << ",\t" << MinOperands << ",\t"
171      << Inst.NumDefs << ",\t\"";
172
173   if (Inst.Name.empty())
174     OS << Inst.TheDef->getName();
175   else
176     OS << Inst.Name;
177   
178   OS << "\",\t" << getItinClassNumber(Inst.TheDef) << ", 0";
179
180   // Try to determine (from the pattern), if the instruction is a store.
181   bool isStore = false;
182   if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
183     ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
184     if (LI && LI->getSize() > 0) {
185       DagInit *Dag = (DagInit *)LI->getElement(0);
186       DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
187       if (OpDef) {
188         Record *Operator = OpDef->getDef();
189         if (Operator->isSubClassOf("SDNode")) {
190           const std::string Opcode = Operator->getValueAsString("Opcode");
191           if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
192             isStore = true;
193         }
194       }
195     }
196   }
197
198   // Emit all of the target indepedent flags...
199   if (Inst.isReturn)     OS << "|M_RET_FLAG";
200   if (Inst.isBranch)     OS << "|M_BRANCH_FLAG";
201   if (Inst.isIndirectBranch) OS << "|M_INDIRECT_FLAG";
202   if (Inst.isBarrier)    OS << "|M_BARRIER_FLAG";
203   if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
204   if (Inst.isCall)       OS << "|M_CALL_FLAG";
205   if (Inst.isLoad)       OS << "|M_LOAD_FLAG";
206   if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
207   if (Inst.isImplicitDef)OS << "|M_IMPLICIT_DEF_FLAG";
208   if (Inst.isPredicable) OS << "|M_PREDICABLE";
209   if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
210   if (Inst.isCommutable) OS << "|M_COMMUTABLE";
211   if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
212   if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
213   if (Inst.isNotDuplicable) OS << "|M_NOT_DUPLICABLE";
214   if (Inst.hasOptionalDef) OS << "|M_HAS_OPTIONAL_DEF";
215   if (Inst.usesCustomDAGSchedInserter)
216     OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
217   if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS";
218   if (Inst.mayHaveSideEffects) OS << "|M_MAY_HAVE_SIDE_EFFECTS";
219   if (Inst.neverHasSideEffects) OS << "|M_NEVER_HAS_SIDE_EFFECTS";
220   OS << ", 0";
221
222   // Emit all of the target-specific flags...
223   ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
224   ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
225   if (LI->getSize() != Shift->getSize())
226     throw "Lengths of " + InstrInfo->getName() +
227           ":(TargetInfoFields, TargetInfoPositions) must be equal!";
228
229   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
230     emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
231                      dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
232
233   OS << ", ";
234
235   // Emit the implicit uses and defs lists...
236   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
237   if (UseList.empty())
238     OS << "NULL, ";
239   else
240     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
241
242   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
243   if (DefList.empty())
244     OS << "NULL, ";
245   else
246     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
247
248   // Emit the operand info.
249   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
250   if (OperandInfo.empty())
251     OS << "0";
252   else
253     OS << "OperandInfo" << OpInfo[OperandInfo];
254   
255   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
256 }
257
258 struct RecordNameComparator {
259   bool operator()(const Record *Rec1, const Record *Rec2) const {
260     return Rec1->getName() < Rec2->getName();
261   }
262 };
263
264 void InstrInfoEmitter::GatherItinClasses() {
265   std::vector<Record*> DefList =
266                           Records.getAllDerivedDefinitions("InstrItinClass");
267   std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
268
269   for (unsigned i = 0, N = DefList.size(); i < N; i++)
270     ItinClassMap[DefList[i]->getName()] = i;
271 }  
272   
273 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
274   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
275 }
276
277 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
278                                         IntInit *ShiftInt, std::ostream &OS) {
279   if (Val == 0 || ShiftInt == 0)
280     throw std::string("Illegal value or shift amount in TargetInfo*!");
281   RecordVal *RV = R->getValue(Val->getValue());
282   int Shift = ShiftInt->getValue();
283
284   if (RV == 0 || RV->getValue() == 0) {
285     // This isn't an error if this is a builtin instruction.
286     if (R->getName() != "PHI" &&
287         R->getName() != "INLINEASM" &&
288         R->getName() != "LABEL" &&
289         R->getName() != "EXTRACT_SUBREG" &&
290         R->getName() != "INSERT_SUBREG")
291       throw R->getName() + " doesn't have a field named '" + 
292             Val->getValue() + "'!";
293     return;
294   }
295
296   Init *Value = RV->getValue();
297   if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
298     if (BI->getValue()) OS << "|(1<<" << Shift << ")";
299     return;
300   } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
301     // Convert the Bits to an integer to print...
302     Init *I = BI->convertInitializerTo(new IntRecTy());
303     if (I)
304       if (IntInit *II = dynamic_cast<IntInit*>(I)) {
305         if (II->getValue()) {
306           if (Shift)
307             OS << "|(" << II->getValue() << "<<" << Shift << ")";
308           else
309             OS << "|" << II->getValue();
310         }
311         return;
312       }
313
314   } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
315     if (II->getValue()) {
316       if (Shift)
317         OS << "|(" << II->getValue() << "<<" << Shift << ")";
318       else
319         OS << II->getValue();
320     }
321     return;
322   }
323
324   std::cerr << "Unhandled initializer: " << *Val << "\n";
325   throw "In record '" + R->getName() + "' for TSFlag emission.";
326 }
327