1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
15 #include "DAGISelMatcher.h"
17 #include "llvm/Support/Debug.h"
20 //===----------------------------------------------------------------------===//
21 // DAGISelEmitter Helper methods
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
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()))
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);
42 Size += AM->getNumOperands() * 3;
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())
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())
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;
75 Record *Op = P->getOperator();
76 if (Op->isSubClassOf("Instruction")) {
78 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
79 if (II.usesCustomInserter)
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
83 Cost += getResultPatternCost(P->getChild(i), CGP);
87 /// getResultPatternCodeSize - Compute the code size of instructions for this
89 static unsigned getResultPatternSize(TreePatternNode *P,
90 CodeGenDAGPatterns &CGP) {
91 if (P->isLeaf()) return 0;
94 Record *Op = P->getOperator();
95 if (Op->isSubClassOf("Instruction")) {
96 Cost += Op->getValueAsInt("CodeSize");
98 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
99 Cost += getResultPatternSize(P->getChild(i), CGP);
103 //===----------------------------------------------------------------------===//
104 // Predicate emitter implementation.
107 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
108 OS << "\n// Predicate functions.\n";
110 // Walk the pattern fragments, adding them to a map, which sorts them by
112 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
113 PFsByNameTy PFsByName;
115 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
117 PFsByName.insert(std::make_pair(I->first->getName(), *I));
120 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
122 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
123 TreePattern *P = I->second.second;
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;
129 if (P->getOnlyTree()->isLeaf())
130 OS << "inline bool Predicate_" << PatFragRecord->getName()
131 << "(SDNode *N) const {\n";
133 std::string ClassName =
134 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
135 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
137 OS << "inline bool Predicate_" << PatFragRecord->getName()
138 << "(SDNode *" << C2 << ") const {\n";
139 if (ClassName != "SDNode")
140 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
142 OS << Code << "\n}\n";
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;
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;
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;
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;
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;
184 void DAGISelEmitter::run(raw_ostream &OS) {
185 EmitSourceFileHeader("DAG Instruction Selector for the " +
186 CGP.getTargetInfo().getName() + " target", OS);
188 OS << "// *** NOTE: This file is #included into the middle of the target\n"
189 << "// *** instruction selector class. These functions are really "
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();
200 // FIXME: These are being used by hand written code, gross.
201 EmitPredicateFunctions(OS);
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();
207 Patterns.push_back(&*I);
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));
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);
226 Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
227 PatternMatchers.size());
229 TheMatcher = OptimizeMatcher(TheMatcher, CGP);
231 EmitMatcherTable(TheMatcher, CGP, OS);