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((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()))
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);
48 Size += AM->getNumOperands() * 3;
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())
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())
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;
81 Record *Op = P->getOperator();
82 if (Op->isSubClassOf("Instruction")) {
84 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
85 if (II.usesCustomInserter)
88 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
89 Cost += getResultPatternCost(P->getChild(i), CGP);
93 /// getResultPatternCodeSize - Compute the code size of instructions for this
95 static unsigned getResultPatternSize(TreePatternNode *P,
96 CodeGenDAGPatterns &CGP) {
97 if (P->isLeaf()) return 0;
100 Record *Op = P->getOperator();
101 if (Op->isSubClassOf("Instruction")) {
102 Cost += Op->getValueAsInt("CodeSize");
104 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
105 Cost += getResultPatternSize(P->getChild(i), CGP);
109 //===----------------------------------------------------------------------===//
110 // Predicate emitter implementation.
113 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
114 OS << "\n// Predicate functions.\n";
116 // Walk the pattern fragments, adding them to a map, which sorts them by
118 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
119 PFsByNameTy PFsByName;
121 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
123 PFsByName.insert(std::make_pair(I->first->getName(), *I));
126 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
128 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
129 TreePattern *P = I->second.second;
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;
135 if (P->getOnlyTree()->isLeaf())
136 OS << "inline bool Predicate_" << PatFragRecord->getName()
137 << "(SDNode *N) const {\n";
139 std::string ClassName =
140 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
141 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
143 OS << "inline bool Predicate_" << PatFragRecord->getName()
144 << "(SDNode *" << C2 << ") const {\n";
145 if (ClassName != "SDNode")
146 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
148 OS << Code << "\n}\n";
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;
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;
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;
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;
182 // Sort based on the UID of the pattern, giving us a deterministic ordering.
183 assert(LHS == RHS || LHS->ID != RHS->ID);
184 return LHS->ID < RHS->ID;
190 void DAGISelEmitter::run(raw_ostream &OS) {
191 EmitSourceFileHeader("DAG Instruction Selector for the " +
192 CGP.getTargetInfo().getName() + " target", OS);
194 OS << "// *** NOTE: This file is #included into the middle of the target\n"
195 << "// *** instruction selector class. These functions are really "
198 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
199 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
200 E = CGP.ptm_end(); I != E; ++I) {
201 errs() << "PATTERN: "; I->getSrcPattern()->dump();
202 errs() << "\nRESULT: "; I->getDstPattern()->dump();
206 // FIXME: These are being used by hand written code, gross.
207 EmitPredicateFunctions(OS);
209 // Add all the patterns to a temporary list so we can sort them.
210 std::vector<const PatternToMatch*> Patterns;
211 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
213 Patterns.push_back(&*I);
215 // We want to process the matches in order of minimal cost. Sort the patterns
216 // so the least cost one is at the start.
217 std::stable_sort(Patterns.begin(), Patterns.end(),
218 PatternSortingPredicate(CGP));
221 // Convert each variant of each pattern into a Matcher.
222 std::vector<Matcher*> PatternMatchers;
223 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
224 for (unsigned Variant = 0; ; ++Variant) {
225 if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP))
226 PatternMatchers.push_back(M);
232 Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
233 PatternMatchers.size());
235 TheMatcher = OptimizeMatcher(TheMatcher, CGP);
237 EmitMatcherTable(TheMatcher, CGP, OS);