remove some old hacky code that tried to infer whether a store
[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 static void PrintDefList(const std::vector<Record*> &Uses,
23                          unsigned Num, std::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 struct RecordNameComparator {
35   bool operator()(const Record *Rec1, const Record *Rec2) const {
36     return Rec1->getName() < Rec2->getName();
37   }
38 };
39
40 void InstrInfoEmitter::GatherItinClasses() {
41   std::vector<Record*> DefList =
42   Records.getAllDerivedDefinitions("InstrItinClass");
43   std::sort(DefList.begin(), DefList.end(), RecordNameComparator());
44   
45   for (unsigned i = 0, N = DefList.size(); i < N; i++)
46     ItinClassMap[DefList[i]->getName()] = i;
47 }  
48
49 unsigned InstrInfoEmitter::getItinClassNumber(const Record *InstRec) {
50   return ItinClassMap[InstRec->getValueAsDef("Itinerary")->getName()];
51 }
52
53 //===----------------------------------------------------------------------===//
54 // Operand Info Emission.
55 //===----------------------------------------------------------------------===//
56
57 std::vector<std::string>
58 InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
59   std::vector<std::string> Result;
60   
61   for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
62     // Handle aggregate operands and normal operands the same way by expanding
63     // either case into a list of operands for this op.
64     std::vector<CodeGenInstruction::OperandInfo> OperandList;
65
66     // This might be a multiple operand thing.  Targets like X86 have
67     // registers in their multi-operand operands.  It may also be an anonymous
68     // operand, which has a single operand, but no declared class for the
69     // operand.
70     DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
71     
72     if (!MIOI || MIOI->getNumArgs() == 0) {
73       // Single, anonymous, operand.
74       OperandList.push_back(Inst.OperandList[i]);
75     } else {
76       for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
77         OperandList.push_back(Inst.OperandList[i]);
78
79         Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
80         OperandList.back().Rec = OpR;
81       }
82     }
83
84     for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
85       Record *OpR = OperandList[j].Rec;
86       std::string Res;
87       
88       if (OpR->isSubClassOf("RegisterClass"))
89         Res += getQualifiedName(OpR) + "RegClassID, ";
90       else
91         Res += "0, ";
92       // Fill in applicable flags.
93       Res += "0";
94         
95       // Ptr value whose register class is resolved via callback.
96       if (OpR->getName() == "ptr_rc")
97         Res += "|M_LOOK_UP_PTR_REG_CLASS";
98
99       // Predicate operands.  Check to see if the original unexpanded operand
100       // was of type PredicateOperand.
101       if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
102         Res += "|M_PREDICATE_OPERAND";
103         
104       // Optional def operands.  Check to see if the original unexpanded operand
105       // was of type OptionalDefOperand.
106       if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
107         Res += "|M_OPTIONAL_DEF_OPERAND";
108
109       // Fill in constraint info.
110       Res += ", " + Inst.OperandList[i].Constraints[j];
111       Result.push_back(Res);
112     }
113   }
114
115   return Result;
116 }
117
118 void InstrInfoEmitter::EmitOperandInfo(std::ostream &OS, 
119                                        OperandInfoMapTy &OperandInfoIDs) {
120   // ID #0 is for no operand info.
121   unsigned OperandListNum = 0;
122   OperandInfoIDs[std::vector<std::string>()] = ++OperandListNum;
123   
124   OS << "\n";
125   const CodeGenTarget &Target = CDP.getTargetInfo();
126   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
127        E = Target.inst_end(); II != E; ++II) {
128     std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
129     unsigned &N = OperandInfoIDs[OperandInfo];
130     if (N != 0) continue;
131     
132     N = ++OperandListNum;
133     OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
134     for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
135       OS << "{ " << OperandInfo[i] << " }, ";
136     OS << "};\n";
137   }
138 }
139
140 //===----------------------------------------------------------------------===//
141 // Instruction Analysis
142 //===----------------------------------------------------------------------===//
143
144 class InstAnalyzer {
145   const CodeGenDAGPatterns &CDP;
146   bool &isStore;
147   bool &isLoad;
148   bool &NeverHasSideEffects;
149 public:
150   InstAnalyzer(const CodeGenDAGPatterns &cdp,
151                bool &isstore, bool &isload, bool &nhse)
152     : CDP(cdp), isStore(isstore), isLoad(isload), NeverHasSideEffects(nhse) {
153   }
154   
155   void Analyze(Record *InstRecord) {
156     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
157     if (Pattern == 0) return;  // No pattern.
158     
159     // Assume there is no side-effect unless we see one.
160     // FIXME: Enable this.
161     //NeverHasSideEffects = true;
162
163     
164     // FIXME: Assume only the first tree is the pattern. The others are clobber
165     // nodes.
166     AnalyzeNode(Pattern->getTree(0));
167   }
168   
169 private:
170   void AnalyzeNode(const TreePatternNode *N) {
171     if (N->isLeaf()) {
172       return;
173     }
174
175     if (N->getOperator()->getName() != "set") {
176       // Get information about the SDNode for the operator.
177       const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
178       
179       if (OpInfo.getEnumName() == "ISD::STORE")
180         isStore = true;
181     }
182
183     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
184       AnalyzeNode(N->getChild(i));
185   }
186   
187 };
188
189 void InstrInfoEmitter::InferFromPattern(const CodeGenInstruction &Inst, 
190                                         bool &isStore, bool &isLoad, 
191                                         bool &NeverHasSideEffects) {
192   isStore             = Inst.isStore;
193   isLoad              = Inst.isLoad;
194   NeverHasSideEffects = Inst.neverHasSideEffects;
195   
196   InstAnalyzer(CDP, isStore, isLoad, NeverHasSideEffects).Analyze(Inst.TheDef);
197   
198   // If the .td file explicitly says there is no side effect, believe it.
199   if (Inst.neverHasSideEffects)
200     NeverHasSideEffects = true;
201 }
202
203
204 //===----------------------------------------------------------------------===//
205 // Main Output.
206 //===----------------------------------------------------------------------===//
207
208 // run - Emit the main instruction description records for the target...
209 void InstrInfoEmitter::run(std::ostream &OS) {
210   GatherItinClasses();
211
212   EmitSourceFileHeader("Target Instruction Descriptors", OS);
213   OS << "namespace llvm {\n\n";
214
215   CodeGenTarget Target;
216   const std::string &TargetName = Target.getName();
217   Record *InstrInfo = Target.getInstructionSet();
218
219   // Keep track of all of the def lists we have emitted already.
220   std::map<std::vector<Record*>, unsigned> EmittedLists;
221   unsigned ListNumber = 0;
222  
223   // Emit all of the instruction's implicit uses and defs.
224   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
225          E = Target.inst_end(); II != E; ++II) {
226     Record *Inst = II->second.TheDef;
227     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
228     if (!Uses.empty()) {
229       unsigned &IL = EmittedLists[Uses];
230       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
231     }
232     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
233     if (!Defs.empty()) {
234       unsigned &IL = EmittedLists[Defs];
235       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
236     }
237   }
238
239   OperandInfoMapTy OperandInfoIDs;
240   
241   // Emit all of the operand info records.
242   EmitOperandInfo(OS, OperandInfoIDs);
243   
244   // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
245   //
246   OS << "\nstatic const TargetInstrDescriptor " << TargetName
247      << "Insts[] = {\n";
248   std::vector<const CodeGenInstruction*> NumberedInstructions;
249   Target.getInstructionsByEnumValue(NumberedInstructions);
250
251   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
252     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
253                OperandInfoIDs, OS);
254   OS << "};\n";
255   OS << "} // End llvm namespace \n";
256 }
257
258 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
259                                   Record *InstrInfo,
260                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
261                                   const OperandInfoMapTy &OpInfo,
262                                   std::ostream &OS) {
263   // Determine properties of the instruction from its pattern.
264   bool isStore, isLoad, NeverHasSideEffects;
265   InferFromPattern(Inst, isStore, isLoad, NeverHasSideEffects);
266   
267   if (NeverHasSideEffects && Inst.mayHaveSideEffects) {
268     std::cerr << "error: Instruction '" << Inst.getName()
269       << "' is marked with 'mayHaveSideEffects', but it can never have them!\n";
270     exit(1);
271   }
272   
273   int MinOperands = 0;
274   if (!Inst.OperandList.empty())
275     // Each logical operand can be multiple MI operands.
276     MinOperands = Inst.OperandList.back().MIOperandNo +
277                   Inst.OperandList.back().MINumOperands;
278   
279   OS << "  { ";
280   OS << Num << ",\t" << MinOperands << ",\t"
281      << Inst.NumDefs << ",\t\"" << Inst.getName();
282   OS << "\",\t" << getItinClassNumber(Inst.TheDef) << ", 0";
283
284   // Emit all of the target indepedent flags...
285   if (Inst.isReturn)     OS << "|M_RET_FLAG";
286   if (Inst.isBranch)     OS << "|M_BRANCH_FLAG";
287   if (Inst.isIndirectBranch) OS << "|M_INDIRECT_FLAG";
288   if (Inst.isBarrier)    OS << "|M_BARRIER_FLAG";
289   if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
290   if (Inst.isCall)       OS << "|M_CALL_FLAG";
291   if (isLoad)            OS << "|M_LOAD_FLAG";
292   if (isStore)           OS << "|M_STORE_FLAG";
293   if (Inst.isImplicitDef)OS << "|M_IMPLICIT_DEF_FLAG";
294   if (Inst.isPredicable) OS << "|M_PREDICABLE";
295   if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
296   if (Inst.isCommutable) OS << "|M_COMMUTABLE";
297   if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
298   if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
299   if (Inst.isNotDuplicable)    OS << "|M_NOT_DUPLICABLE";
300   if (Inst.hasOptionalDef)     OS << "|M_HAS_OPTIONAL_DEF";
301   if (Inst.usesCustomDAGSchedInserter)
302     OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
303   if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS";
304   if (Inst.mayHaveSideEffects)          OS << "|M_MAY_HAVE_SIDE_EFFECTS";
305   if (NeverHasSideEffects)              OS << "|M_NEVER_HAS_SIDE_EFFECTS";
306   OS << ", 0";
307
308   // Emit all of the target-specific flags...
309   ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
310   ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
311   if (LI->getSize() != Shift->getSize())
312     throw "Lengths of " + InstrInfo->getName() +
313           ":(TargetInfoFields, TargetInfoPositions) must be equal!";
314
315   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
316     emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
317                      dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
318
319   OS << ", ";
320
321   // Emit the implicit uses and defs lists...
322   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
323   if (UseList.empty())
324     OS << "NULL, ";
325   else
326     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
327
328   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
329   if (DefList.empty())
330     OS << "NULL, ";
331   else
332     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
333
334   // Emit the operand info.
335   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
336   if (OperandInfo.empty())
337     OS << "0";
338   else
339     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
340   
341   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
342 }
343
344
345 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
346                                         IntInit *ShiftInt, std::ostream &OS) {
347   if (Val == 0 || ShiftInt == 0)
348     throw std::string("Illegal value or shift amount in TargetInfo*!");
349   RecordVal *RV = R->getValue(Val->getValue());
350   int Shift = ShiftInt->getValue();
351
352   if (RV == 0 || RV->getValue() == 0) {
353     // This isn't an error if this is a builtin instruction.
354     if (R->getName() != "PHI" &&
355         R->getName() != "INLINEASM" &&
356         R->getName() != "LABEL" &&
357         R->getName() != "EXTRACT_SUBREG" &&
358         R->getName() != "INSERT_SUBREG")
359       throw R->getName() + " doesn't have a field named '" + 
360             Val->getValue() + "'!";
361     return;
362   }
363
364   Init *Value = RV->getValue();
365   if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
366     if (BI->getValue()) OS << "|(1<<" << Shift << ")";
367     return;
368   } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
369     // Convert the Bits to an integer to print...
370     Init *I = BI->convertInitializerTo(new IntRecTy());
371     if (I)
372       if (IntInit *II = dynamic_cast<IntInit*>(I)) {
373         if (II->getValue()) {
374           if (Shift)
375             OS << "|(" << II->getValue() << "<<" << Shift << ")";
376           else
377             OS << "|" << II->getValue();
378         }
379         return;
380       }
381
382   } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
383     if (II->getValue()) {
384       if (Shift)
385         OS << "|(" << II->getValue() << "<<" << Shift << ")";
386       else
387         OS << II->getValue();
388     }
389     return;
390   }
391
392   std::cerr << "Unhandled initializer: " << *Val << "\n";
393   throw "In record '" + R->getName() + "' for TSFlag emission.";
394 }
395