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 /// 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;
32 Record *Op = P->getOperator();
33 if (Op->isSubClassOf("Instruction")) {
35 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
36 if (II.usesCustomInserter)
39 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
40 Cost += getResultPatternCost(P->getChild(i), CGP);
44 /// getResultPatternCodeSize - Compute the code size of instructions for this
46 static unsigned getResultPatternSize(TreePatternNode *P,
47 CodeGenDAGPatterns &CGP) {
48 if (P->isLeaf()) return 0;
51 Record *Op = P->getOperator();
52 if (Op->isSubClassOf("Instruction")) {
53 Cost += Op->getValueAsInt("CodeSize");
55 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
56 Cost += getResultPatternSize(P->getChild(i), CGP);
60 //===----------------------------------------------------------------------===//
61 // Predicate emitter implementation.
64 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
65 OS << "\n// Predicate functions.\n";
67 // Walk the pattern fragments, adding them to a map, which sorts them by
69 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
70 PFsByNameTy PFsByName;
72 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
74 PFsByName.insert(std::make_pair(I->first->getName(), *I));
77 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
79 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
80 TreePattern *P = I->second.second;
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;
86 if (P->getOnlyTree()->isLeaf())
87 OS << "inline bool Predicate_" << PatFragRecord->getName()
88 << "(SDNode *N) const {\n";
90 std::string ClassName =
91 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
92 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
94 OS << "inline bool Predicate_" << PatFragRecord->getName()
95 << "(SDNode *" << C2 << ") const {\n";
96 if (ClassName != "SDNode")
97 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
99 OS << Code << "\n}\n";
105 /// CouldMatchSameInput - Return true if it is possible for these two patterns
106 /// to match the same input. For example, (add reg, reg) and
107 /// (add reg, (mul ...)) could both match the same input. Where this is
108 /// conservative, it falls back to returning true.
109 static bool CouldMatchSameInput(const TreePatternNode *N1,
110 const TreePatternNode *N2) {
111 // If the types of the two nodes differ, they can't match the same thing.
112 if (N1->getNumTypes() != N2->getNumTypes()) return false;
113 for (unsigned i = 0, e = N1->getNumTypes(); i != e; ++i)
114 if (N1->getType(i) != N2->getType(i))
117 // Handle the case when at least one is a leaf.
120 // Handle leaf/leaf cases. Register operands can match just about
121 // anything, so we can only disambiguate a few things here.
123 // If both operands are leaf integer nodes with different values, they
124 // can't match the same thing.
125 if (IntInit *II1 = dynamic_cast<IntInit*>(N1->getLeafValue()))
126 if (IntInit *II2 = dynamic_cast<IntInit*>(N2->getLeafValue()))
127 return II1->getValue() == II2->getValue();
129 DefInit *DI1 = dynamic_cast<DefInit*>(N1->getLeafValue());
130 DefInit *DI2 = dynamic_cast<DefInit*>(N2->getLeafValue());
131 if (DI1 != 0 && DI2 != 0) {
132 if (DI1->getDef()->isSubClassOf("ValueType") &&
133 DI2->getDef()->isSubClassOf("ValueType"))
135 if (DI1->getDef()->isSubClassOf("CondCode") &&
136 DI2->getDef()->isSubClassOf("CondCode"))
140 // TODO: Regclass cannot match a condcode etc.
142 // Otherwise, complex pattern could match anything, so just return a
143 // conservative response.
147 // Conservatively return true. (imm) could match "7" for example, and GPR
148 // can match anything.
149 // TODO: could handle (add ...) != "1" if we cared.
153 // If N2 is a leaf and N1 isn't, check the other way.
155 return CouldMatchSameInput(N2, N1);
157 // Now we know neither node is a leaf. If the two patterns have different
158 // number of children or different operators, they can't both match.
159 Record *Op1 = N1->getOperator(), *Op2 = N1->getOperator();
161 if (Op1 != Op2 || N1->getNumChildren() != N2->getNumChildren())
164 // If a child prevents the two patterns from matching, use that.
165 for (unsigned i = 0, e = N1->getNumChildren(); i != e; ++i)
166 if (!CouldMatchSameInput(N1->getChild(i), N2->getChild(i)))
169 // Otherwise, it looks like they could both match the same thing.
173 /// GetSourceMatchPreferenceOrdering - The two input patterns are guaranteed to
174 /// not match the same input. Decide which pattern we'd prefer to match first
175 /// in order to reduce compile time. This sorting predicate is used to improve
176 /// compile time so that we try to match scalar operations before vector
177 /// operations since scalar operations are much more common in practice.
179 /// This returns -1 if we prefer to match N1 before N2, 1 if we prefer to match
180 /// N2 before N1 or 0 if no preference.
182 static int GetSourceMatchPreferenceOrdering(const TreePatternNode *N1,
183 const TreePatternNode *N2) {
184 // The primary thing we sort on here is to get ints before floats and scalars
186 for (unsigned i = 0, e = std::min(N1->getNumTypes(), N2->getNumTypes());
188 if (N1->getType(i) != N2->getType(i)) {
189 MVT::SimpleValueType V1 = N1->getType(i), V2 = N2->getType(i);
190 if (MVT(V1).isVector() != MVT(V2).isVector())
191 return MVT(V1).isVector() ? 1 : -1;
193 if (MVT(V1).isFloatingPoint() != MVT(V2).isFloatingPoint())
194 return MVT(V1).isFloatingPoint() ? 1 : -1;
197 for (unsigned i = 0, e = std::min(N1->getNumChildren(), N2->getNumChildren());
199 if (int Res = GetSourceMatchPreferenceOrdering(N1->getChild(i),
207 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
208 // In particular, we want to match maximal patterns first and lowest cost within
209 // a particular complexity first.
210 struct PatternSortingPredicate {
211 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
212 CodeGenDAGPatterns &CGP;
214 bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) {
215 const TreePatternNode *LHSSrc = LHS->getSrcPattern();
216 const TreePatternNode *RHSSrc = RHS->getSrcPattern();
218 // If the patterns are guaranteed to not match at the same time and we
219 // prefer to match one before the other (for compile time reasons) use this
220 // preference as our discriminator.
221 if (0 && !CouldMatchSameInput(LHSSrc, RHSSrc)) {
222 int Ordering = GetSourceMatchPreferenceOrdering(LHSSrc, RHSSrc);
224 if (Ordering == -1) {
225 errs() << "SORT: " << *LHSSrc << "\n";
226 errs() << "NEXT: " << *RHSSrc << "\n\n";
228 errs() << "SORT: " << *RHSSrc << "\n";
229 errs() << "NEXT: " << *LHSSrc << "\n\n";
233 if (Ordering == -1) return true;
234 if (Ordering == 1) return false;
237 // Otherwise, if the patterns might both match, sort based on complexity,
238 // which means that we prefer to match patterns that cover more nodes in the
239 // input over nodes that cover fewer.
240 unsigned LHSSize = LHS->getPatternComplexity(CGP);
241 unsigned RHSSize = RHS->getPatternComplexity(CGP);
242 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
243 if (LHSSize < RHSSize) return false;
245 // If the patterns have equal complexity, compare generated instruction cost
246 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
247 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
248 if (LHSCost < RHSCost) return true;
249 if (LHSCost > RHSCost) return false;
251 unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP);
252 unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP);
253 if (LHSPatSize < RHSPatSize) return true;
254 if (LHSPatSize > RHSPatSize) return false;
256 // Sort based on the UID of the pattern, giving us a deterministic ordering
257 // if all other sorting conditions fail.
258 assert(LHS == RHS || LHS->ID != RHS->ID);
259 return LHS->ID < RHS->ID;
265 void DAGISelEmitter::run(raw_ostream &OS) {
266 EmitSourceFileHeader("DAG Instruction Selector for the " +
267 CGP.getTargetInfo().getName() + " target", OS);
269 OS << "// *** NOTE: This file is #included into the middle of the target\n"
270 << "// *** instruction selector class. These functions are really "
273 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
274 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
275 E = CGP.ptm_end(); I != E; ++I) {
276 errs() << "PATTERN: "; I->getSrcPattern()->dump();
277 errs() << "\nRESULT: "; I->getDstPattern()->dump();
281 // FIXME: These are being used by hand written code, gross.
282 EmitPredicateFunctions(OS);
284 // Add all the patterns to a temporary list so we can sort them.
285 std::vector<const PatternToMatch*> Patterns;
286 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
288 Patterns.push_back(&*I);
290 // We want to process the matches in order of minimal cost. Sort the patterns
291 // so the least cost one is at the start.
292 std::sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(CGP));
295 // Convert each variant of each pattern into a Matcher.
296 std::vector<Matcher*> PatternMatchers;
297 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
298 for (unsigned Variant = 0; ; ++Variant) {
299 if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP))
300 PatternMatchers.push_back(M);
306 Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
307 PatternMatchers.size());
309 TheMatcher = OptimizeMatcher(TheMatcher, CGP);
311 EmitMatcherTable(TheMatcher, CGP, OS);