start inferring 'no side effects'.
[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 += "|(1<<TOI::LookupPtrRegClass)";
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 += "|(1<<TOI::Predicate)";
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 += "|(1<<TOI::OptionalDef)";
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 &mayStore;
147   bool &mayLoad;
148   bool &HasSideEffects;
149 public:
150   InstAnalyzer(const CodeGenDAGPatterns &cdp,
151                bool &maystore, bool &mayload, bool &hse)
152     : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
153   }
154   
155   void Analyze(Record *InstRecord) {
156     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
157     if (Pattern == 0) return;  // No pattern.
158     
159     // FIXME: Assume only the first tree is the pattern. The others are clobber
160     // nodes.
161     AnalyzeNode(Pattern->getTree(0));
162   }
163   
164 private:
165   void AnalyzeNode(const TreePatternNode *N) {
166     if (N->isLeaf())
167       return;
168
169     // Analyze children.
170     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
171       AnalyzeNode(N->getChild(i));
172
173     // Ignore set nodes, which are not SDNodes.
174     if (N->getOperator()->getName() == "set")
175       return;
176     
177     // Get information about the SDNode for the operator.
178     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
179     
180     // If node writes to memory, it obviously stores to memory.
181     if (OpInfo.hasProperty(SDNPMayStore))
182       mayStore = true;
183     
184     // If it reads memory, remember this.
185     if (OpInfo.hasProperty(SDNPMayLoad))
186       mayLoad = true;
187
188     // If it reads memory, remember this.
189     if (OpInfo.hasProperty(SDNPSideEffect))
190       HasSideEffects = true;
191     
192     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
193       // If this is an intrinsic, analyze it.
194       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
195         mayLoad = true;// These may load memory.
196
197       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
198         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
199
200       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
201         // WriteMem intrinsics can have other strange effects.
202         HasSideEffects = true;
203     }
204   }
205   
206 };
207
208 void InstrInfoEmitter::InferFromPattern(const CodeGenInstruction &Inst, 
209                                         bool &MayStore, bool &MayLoad, 
210                                         bool &HasSideEffects) {
211   MayStore = MayLoad = HasSideEffects = false;
212   
213   InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
214
215   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
216   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
217     // If we decided that this is a store from the pattern, then the .td file
218     // entry is redundant.
219     if (MayStore)
220       fprintf(stderr, 
221               "Warning: mayStore flag explicitly set on instruction '%s'"
222               " but flag already inferred from pattern.\n", 
223               Inst.TheDef->getName().c_str());
224     MayStore = true;
225   }
226
227   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
228     // If we decided that this is a load from the pattern, then the .td file
229     // entry is redundant.
230     if (MayLoad)
231       fprintf(stderr, 
232               "Warning: mayLoad flag explicitly set on instruction '%s'"
233               " but flag already inferred from pattern.\n", 
234               Inst.TheDef->getName().c_str());
235     MayLoad = true;
236   }
237   
238   if (Inst.neverHasSideEffects) {
239     // If we already decided that this instruction has no side effects, then the
240     // .td file entry is redundant.
241     if (!HasSideEffects)
242       fprintf(stderr, 
243               "Warning: neverHasSideEffects flag explicitly set on instruction"
244               " '%s' but flag already inferred from pattern.\n", 
245               Inst.TheDef->getName().c_str());
246     HasSideEffects = false;
247   }
248 }
249
250
251 //===----------------------------------------------------------------------===//
252 // Main Output.
253 //===----------------------------------------------------------------------===//
254
255 // run - Emit the main instruction description records for the target...
256 void InstrInfoEmitter::run(std::ostream &OS) {
257   GatherItinClasses();
258
259   EmitSourceFileHeader("Target Instruction Descriptors", OS);
260   OS << "namespace llvm {\n\n";
261
262   CodeGenTarget Target;
263   const std::string &TargetName = Target.getName();
264   Record *InstrInfo = Target.getInstructionSet();
265
266   // Keep track of all of the def lists we have emitted already.
267   std::map<std::vector<Record*>, unsigned> EmittedLists;
268   unsigned ListNumber = 0;
269  
270   // Emit all of the instruction's implicit uses and defs.
271   for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
272          E = Target.inst_end(); II != E; ++II) {
273     Record *Inst = II->second.TheDef;
274     std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
275     if (!Uses.empty()) {
276       unsigned &IL = EmittedLists[Uses];
277       if (!IL) PrintDefList(Uses, IL = ++ListNumber, OS);
278     }
279     std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
280     if (!Defs.empty()) {
281       unsigned &IL = EmittedLists[Defs];
282       if (!IL) PrintDefList(Defs, IL = ++ListNumber, OS);
283     }
284   }
285
286   OperandInfoMapTy OperandInfoIDs;
287   
288   // Emit all of the operand info records.
289   EmitOperandInfo(OS, OperandInfoIDs);
290   
291   // Emit all of the TargetInstrDesc records in their ENUM ordering.
292   //
293   OS << "\nstatic const TargetInstrDesc " << TargetName
294      << "Insts[] = {\n";
295   std::vector<const CodeGenInstruction*> NumberedInstructions;
296   Target.getInstructionsByEnumValue(NumberedInstructions);
297
298   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
299     emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
300                OperandInfoIDs, OS);
301   OS << "};\n";
302   OS << "} // End llvm namespace \n";
303 }
304
305 void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
306                                   Record *InstrInfo,
307                          std::map<std::vector<Record*>, unsigned> &EmittedLists,
308                                   const OperandInfoMapTy &OpInfo,
309                                   std::ostream &OS) {
310   // Determine properties of the instruction from its pattern.
311   bool mayStore, mayLoad, HasSideEffects;
312   InferFromPattern(Inst, mayStore, mayLoad, HasSideEffects);
313   
314   int MinOperands = 0;
315   if (!Inst.OperandList.empty())
316     // Each logical operand can be multiple MI operands.
317     MinOperands = Inst.OperandList.back().MIOperandNo +
318                   Inst.OperandList.back().MINumOperands;
319   
320   OS << "  { ";
321   OS << Num << ",\t" << MinOperands << ",\t"
322      << Inst.NumDefs << ",\t" << getItinClassNumber(Inst.TheDef)
323      << ",\t\"" << Inst.TheDef->getName() << "\", 0";
324
325   // Emit all of the target indepedent flags...
326   if (Inst.isReturn)     OS << "|(1<<TID::Return)";
327   if (Inst.isBranch)     OS << "|(1<<TID::Branch)";
328   if (Inst.isIndirectBranch) OS << "|(1<<TID::IndirectBranch)";
329   if (Inst.isBarrier)    OS << "|(1<<TID::Barrier)";
330   if (Inst.hasDelaySlot) OS << "|(1<<TID::DelaySlot)";
331   if (Inst.isCall)       OS << "|(1<<TID::Call)";
332   if (Inst.isSimpleLoad) OS << "|(1<<TID::SimpleLoad)";
333   if (mayLoad)           OS << "|(1<<TID::MayLoad)";
334   if (mayStore)          OS << "|(1<<TID::MayStore)";
335   if (Inst.isImplicitDef)OS << "|(1<<TID::ImplicitDef)";
336   if (Inst.isPredicable) OS << "|(1<<TID::Predicable)";
337   if (Inst.isConvertibleToThreeAddress) OS << "|(1<<TID::ConvertibleTo3Addr)";
338   if (Inst.isCommutable) OS << "|(1<<TID::Commutable)";
339   if (Inst.isTerminator) OS << "|(1<<TID::Terminator)";
340   if (Inst.isReMaterializable) OS << "|(1<<TID::Rematerializable)";
341   if (Inst.isNotDuplicable)    OS << "|(1<<TID::NotDuplicable)";
342   if (Inst.hasOptionalDef)     OS << "|(1<<TID::HasOptionalDef)";
343   if (Inst.usesCustomDAGSchedInserter)
344     OS << "|(1<<TID::UsesCustomDAGSchedInserter)";
345   if (Inst.isVariadic)         OS << "|(1<<TID::Variadic)";
346   if (Inst.mayHaveSideEffects) OS << "|(1<<TID::MayHaveSideEffects)";
347   if (!HasSideEffects)         OS << "|(1<<TID::NeverHasSideEffects)";
348   OS << ", 0";
349
350   // Emit all of the target-specific flags...
351   ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
352   ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
353   if (LI->getSize() != Shift->getSize())
354     throw "Lengths of " + InstrInfo->getName() +
355           ":(TargetInfoFields, TargetInfoPositions) must be equal!";
356
357   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
358     emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
359                      dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
360
361   OS << ", ";
362
363   // Emit the implicit uses and defs lists...
364   std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
365   if (UseList.empty())
366     OS << "NULL, ";
367   else
368     OS << "ImplicitList" << EmittedLists[UseList] << ", ";
369
370   std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
371   if (DefList.empty())
372     OS << "NULL, ";
373   else
374     OS << "ImplicitList" << EmittedLists[DefList] << ", ";
375
376   // Emit the operand info.
377   std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
378   if (OperandInfo.empty())
379     OS << "0";
380   else
381     OS << "OperandInfo" << OpInfo.find(OperandInfo)->second;
382   
383   OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
384 }
385
386
387 void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
388                                         IntInit *ShiftInt, std::ostream &OS) {
389   if (Val == 0 || ShiftInt == 0)
390     throw std::string("Illegal value or shift amount in TargetInfo*!");
391   RecordVal *RV = R->getValue(Val->getValue());
392   int Shift = ShiftInt->getValue();
393
394   if (RV == 0 || RV->getValue() == 0) {
395     // This isn't an error if this is a builtin instruction.
396     if (R->getName() != "PHI" &&
397         R->getName() != "INLINEASM" &&
398         R->getName() != "LABEL" &&
399         R->getName() != "EXTRACT_SUBREG" &&
400         R->getName() != "INSERT_SUBREG")
401       throw R->getName() + " doesn't have a field named '" + 
402             Val->getValue() + "'!";
403     return;
404   }
405
406   Init *Value = RV->getValue();
407   if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
408     if (BI->getValue()) OS << "|(1<<" << Shift << ")";
409     return;
410   } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
411     // Convert the Bits to an integer to print...
412     Init *I = BI->convertInitializerTo(new IntRecTy());
413     if (I)
414       if (IntInit *II = dynamic_cast<IntInit*>(I)) {
415         if (II->getValue()) {
416           if (Shift)
417             OS << "|(" << II->getValue() << "<<" << Shift << ")";
418           else
419             OS << "|" << II->getValue();
420         }
421         return;
422       }
423
424   } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
425     if (II->getValue()) {
426       if (Shift)
427         OS << "|(" << II->getValue() << "<<" << Shift << ")";
428       else
429         OS << II->getValue();
430     }
431     return;
432   }
433
434   std::cerr << "Unhandled initializer: " << *Val << "\n";
435   throw "In record '" + R->getName() + "' for TSFlag emission.";
436 }
437