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