print the complexity of the pattern being matched in the
[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 /// getResultPatternCost - Compute the number of instructions for this pattern.
25 /// This is a temporary hack.  We should really include the instruction
26 /// latencies in this calculation.
27 static unsigned getResultPatternCost(TreePatternNode *P,
28                                      CodeGenDAGPatterns &CGP) {
29   if (P->isLeaf()) return 0;
30   
31   unsigned Cost = 0;
32   Record *Op = P->getOperator();
33   if (Op->isSubClassOf("Instruction")) {
34     Cost++;
35     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
36     if (II.usesCustomInserter)
37       Cost += 10;
38   }
39   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
40     Cost += getResultPatternCost(P->getChild(i), CGP);
41   return Cost;
42 }
43
44 /// getResultPatternCodeSize - Compute the code size of instructions for this
45 /// pattern.
46 static unsigned getResultPatternSize(TreePatternNode *P, 
47                                      CodeGenDAGPatterns &CGP) {
48   if (P->isLeaf()) return 0;
49
50   unsigned Cost = 0;
51   Record *Op = P->getOperator();
52   if (Op->isSubClassOf("Instruction")) {
53     Cost += Op->getValueAsInt("CodeSize");
54   }
55   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
56     Cost += getResultPatternSize(P->getChild(i), CGP);
57   return Cost;
58 }
59
60 //===----------------------------------------------------------------------===//
61 // Predicate emitter implementation.
62 //
63
64 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
65   OS << "\n// Predicate functions.\n";
66
67   // Walk the pattern fragments, adding them to a map, which sorts them by
68   // name.
69   typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
70   PFsByNameTy PFsByName;
71
72   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
73        I != E; ++I)
74     PFsByName.insert(std::make_pair(I->first->getName(), *I));
75
76   
77   for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
78        I != E; ++I) {
79     Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
80     TreePattern *P = I->second.second;
81     
82     // If there is a code init for this fragment, emit the predicate code.
83     std::string Code = PatFragRecord->getValueAsCode("Predicate");
84     if (Code.empty()) continue;
85     
86     if (P->getOnlyTree()->isLeaf())
87       OS << "inline bool Predicate_" << PatFragRecord->getName()
88       << "(SDNode *N) const {\n";
89     else {
90       std::string ClassName =
91         CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
92       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
93       
94       OS << "inline bool Predicate_" << PatFragRecord->getName()
95          << "(SDNode *" << C2 << ") const {\n";
96       if (ClassName != "SDNode")
97         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
98     }
99     OS << Code << "\n}\n";
100   }
101   
102   OS << "\n\n";
103 }
104
105
106 namespace {
107 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
108 // In particular, we want to match maximal patterns first and lowest cost within
109 // a particular complexity first.
110 struct PatternSortingPredicate {
111   PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
112   CodeGenDAGPatterns &CGP;
113   
114   bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) {
115     // Otherwise, if the patterns might both match, sort based on complexity,
116     // which means that we prefer to match patterns that cover more nodes in the
117     // input over nodes that cover fewer.
118     unsigned LHSSize = LHS->getPatternComplexity(CGP);
119     unsigned RHSSize = RHS->getPatternComplexity(CGP);
120     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
121     if (LHSSize < RHSSize) return false;
122     
123     // If the patterns have equal complexity, compare generated instruction cost
124     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
125     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
126     if (LHSCost < RHSCost) return true;
127     if (LHSCost > RHSCost) return false;
128     
129     unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP);
130     unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP);
131     if (LHSPatSize < RHSPatSize) return true;
132     if (LHSPatSize > RHSPatSize) return false;
133     
134     // Sort based on the UID of the pattern, giving us a deterministic ordering
135     // if all other sorting conditions fail.
136     assert(LHS == RHS || LHS->ID != RHS->ID);
137     return LHS->ID < RHS->ID;
138   }
139 };
140 }
141
142
143 void DAGISelEmitter::run(raw_ostream &OS) {
144   EmitSourceFileHeader("DAG Instruction Selector for the " +
145                        CGP.getTargetInfo().getName() + " target", OS);
146   
147   OS << "// *** NOTE: This file is #included into the middle of the target\n"
148      << "// *** instruction selector class.  These functions are really "
149      << "methods.\n\n";
150
151   DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
152         for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
153              E = CGP.ptm_end(); I != E; ++I) {
154           errs() << "PATTERN: ";   I->getSrcPattern()->dump();
155           errs() << "\nRESULT:  "; I->getDstPattern()->dump();
156           errs() << "\n";
157         });
158
159   // FIXME: These are being used by hand written code, gross.
160   EmitPredicateFunctions(OS);
161
162   // Add all the patterns to a temporary list so we can sort them.
163   std::vector<const PatternToMatch*> Patterns;
164   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
165        I != E; ++I)
166     Patterns.push_back(&*I);
167
168   // We want to process the matches in order of minimal cost.  Sort the patterns
169   // so the least cost one is at the start.
170   std::stable_sort(Patterns.begin(), Patterns.end(),
171                    PatternSortingPredicate(CGP));
172   
173   
174   // Convert each variant of each pattern into a Matcher.
175   std::vector<Matcher*> PatternMatchers;
176   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
177     for (unsigned Variant = 0; ; ++Variant) {
178       if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP))
179         PatternMatchers.push_back(M);
180       else
181         break;
182     }
183   }
184           
185   Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
186                                          PatternMatchers.size());
187
188   TheMatcher = OptimizeMatcher(TheMatcher, CGP);
189   //Matcher->dump();
190   EmitMatcherTable(TheMatcher, CGP, OS);
191   delete TheMatcher;
192 }