look up instructions by record, not by name.
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
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 emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "DAGISelMatcher.h"
16 #include "Record.h"
17 #include "llvm/Support/Debug.h"
18 using namespace llvm;
19
20 //===----------------------------------------------------------------------===//
21 // DAGISelEmitter Helper methods
22 //
23
24 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
25 /// patterns before small ones.  This is used to determine the size of a
26 /// pattern.
27 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
28   assert(P->hasTypeSet() && "Not a valid pattern node to size!");
29   unsigned Size = 3;  // The node itself.
30   // If the root node is a ConstantSDNode, increases its size.
31   // e.g. (set R32:$dst, 0).
32   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
33     Size += 2;
34
35   // FIXME: This is a hack to statically increase the priority of patterns
36   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
37   // Later we can allow complexity / cost for each pattern to be (optionally)
38   // specified. To get best possible pattern match we'll need to dynamically
39   // calculate the complexity of all patterns a dag can potentially map to.
40   const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
41   if (AM)
42     Size += AM->getNumOperands() * 3;
43
44   // If this node has some predicate function that must match, it adds to the
45   // complexity of this node.
46   if (!P->getPredicateFns().empty())
47     ++Size;
48   
49   // Count children in the count if they are also nodes.
50   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
51     TreePatternNode *Child = P->getChild(i);
52     if (!Child->isLeaf() && Child->getType() != MVT::Other)
53       Size += getPatternSize(Child, CGP);
54     else if (Child->isLeaf()) {
55       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
56         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
57       else if (Child->getComplexPatternInfo(CGP))
58         Size += getPatternSize(Child, CGP);
59       else if (!Child->getPredicateFns().empty())
60         ++Size;
61     }
62   }
63   
64   return Size;
65 }
66
67 /// getResultPatternCost - Compute the number of instructions for this pattern.
68 /// This is a temporary hack.  We should really include the instruction
69 /// latencies in this calculation.
70 static unsigned getResultPatternCost(TreePatternNode *P,
71                                      CodeGenDAGPatterns &CGP) {
72   if (P->isLeaf()) return 0;
73   
74   unsigned Cost = 0;
75   Record *Op = P->getOperator();
76   if (Op->isSubClassOf("Instruction")) {
77     Cost++;
78     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
79     if (II.usesCustomInserter)
80       Cost += 10;
81   }
82   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
83     Cost += getResultPatternCost(P->getChild(i), CGP);
84   return Cost;
85 }
86
87 /// getResultPatternCodeSize - Compute the code size of instructions for this
88 /// pattern.
89 static unsigned getResultPatternSize(TreePatternNode *P, 
90                                      CodeGenDAGPatterns &CGP) {
91   if (P->isLeaf()) return 0;
92
93   unsigned Cost = 0;
94   Record *Op = P->getOperator();
95   if (Op->isSubClassOf("Instruction")) {
96     Cost += Op->getValueAsInt("CodeSize");
97   }
98   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
99     Cost += getResultPatternSize(P->getChild(i), CGP);
100   return Cost;
101 }
102
103 //===----------------------------------------------------------------------===//
104 // Predicate emitter implementation.
105 //
106
107 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
108   OS << "\n// Predicate functions.\n";
109
110   // Walk the pattern fragments, adding them to a map, which sorts them by
111   // name.
112   typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
113   PFsByNameTy PFsByName;
114
115   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
116        I != E; ++I)
117     PFsByName.insert(std::make_pair(I->first->getName(), *I));
118
119   
120   for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
121        I != E; ++I) {
122     Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
123     TreePattern *P = I->second.second;
124     
125     // If there is a code init for this fragment, emit the predicate code.
126     std::string Code = PatFragRecord->getValueAsCode("Predicate");
127     if (Code.empty()) continue;
128     
129     if (P->getOnlyTree()->isLeaf())
130       OS << "inline bool Predicate_" << PatFragRecord->getName()
131       << "(SDNode *N) const {\n";
132     else {
133       std::string ClassName =
134         CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
135       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
136       
137       OS << "inline bool Predicate_" << PatFragRecord->getName()
138          << "(SDNode *" << C2 << ") const {\n";
139       if (ClassName != "SDNode")
140         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
141     }
142     OS << Code << "\n}\n";
143   }
144   
145   OS << "\n\n";
146 }
147
148 namespace {
149 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
150 // In particular, we want to match maximal patterns first and lowest cost within
151 // a particular complexity first.
152 struct PatternSortingPredicate {
153   PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
154   CodeGenDAGPatterns &CGP;
155   
156   bool operator()(const PatternToMatch *LHS,
157                   const PatternToMatch *RHS) {
158     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
159     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
160     LHSSize += LHS->getAddedComplexity();
161     RHSSize += RHS->getAddedComplexity();
162     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
163     if (LHSSize < RHSSize) return false;
164     
165     // If the patterns have equal complexity, compare generated instruction cost
166     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
167     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
168     if (LHSCost < RHSCost) return true;
169     if (LHSCost > RHSCost) return false;
170     
171     unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP);
172     unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP);
173     if (LHSPatSize < RHSPatSize) return true;
174     if (LHSPatSize > RHSPatSize) return false;
175     
176     // Sort based on the UID of the pattern, giving us a deterministic ordering.
177     assert(LHS == RHS || LHS->ID != RHS->ID);
178     return LHS->ID < RHS->ID;
179   }
180 };
181 }
182
183
184 void DAGISelEmitter::run(raw_ostream &OS) {
185   EmitSourceFileHeader("DAG Instruction Selector for the " +
186                        CGP.getTargetInfo().getName() + " target", OS);
187   
188   OS << "// *** NOTE: This file is #included into the middle of the target\n"
189      << "// *** instruction selector class.  These functions are really "
190      << "methods.\n\n";
191
192   DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
193         for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
194              E = CGP.ptm_end(); I != E; ++I) {
195           errs() << "PATTERN: ";   I->getSrcPattern()->dump();
196           errs() << "\nRESULT:  "; I->getDstPattern()->dump();
197           errs() << "\n";
198         });
199
200   // FIXME: These are being used by hand written code, gross.
201   EmitPredicateFunctions(OS);
202
203   // Add all the patterns to a temporary list so we can sort them.
204   std::vector<const PatternToMatch*> Patterns;
205   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
206        I != E; ++I)
207     Patterns.push_back(&*I);
208
209   // We want to process the matches in order of minimal cost.  Sort the patterns
210   // so the least cost one is at the start.
211   std::stable_sort(Patterns.begin(), Patterns.end(),
212                    PatternSortingPredicate(CGP));
213   
214   
215   // Convert each variant of each pattern into a Matcher.
216   std::vector<Matcher*> PatternMatchers;
217   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
218     for (unsigned Variant = 0; ; ++Variant) {
219       if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP))
220         PatternMatchers.push_back(M);
221       else
222         break;
223     }
224   }
225           
226   Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
227                                          PatternMatchers.size());
228
229   TheMatcher = OptimizeMatcher(TheMatcher, CGP);
230   //Matcher->dump();
231   EmitMatcherTable(TheMatcher, CGP, OS);
232   delete TheMatcher;
233 }