1 //===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
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 file implements the DAG Matcher optimizer.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel-opt"
15 #include "DAGISelMatcher.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
22 /// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
23 /// into single compound nodes like RecordChild.
24 static void ContractNodes(OwningPtr<Matcher> &MatcherPtr) {
25 // If we reached the end of the chain, we're done.
26 Matcher *N = MatcherPtr.get();
29 // If we have a scope node, walk down all of the children.
30 if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
31 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
32 OwningPtr<Matcher> Child(Scope->takeChild(i));
34 Scope->resetChild(i, Child.take());
39 // If we found a movechild node with a node that comes in a 'foochild' form,
41 if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
43 if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
44 New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor());
46 if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
47 New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
50 // Insert the new node.
51 New->setNext(MatcherPtr.take());
52 MatcherPtr.reset(New);
53 // Remove the old one.
54 MC->setNext(MC->getNext()->takeNext());
55 return ContractNodes(MatcherPtr);
59 // Zap movechild -> moveparent.
60 if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
61 if (MoveParentMatcher *MP =
62 dyn_cast<MoveParentMatcher>(MC->getNext())) {
63 MatcherPtr.reset(MP->takeNext());
64 return ContractNodes(MatcherPtr);
67 // Turn EmitNode->CompleteMatch into SelectNodeTo if we can.
68 if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
69 if (CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(EN->getNext())) {
75 ContractNodes(N->getNextPtr());
78 /// SinkPatternPredicates - Pattern predicates can be checked at any level of
79 /// the matching tree. The generator dumps them at the top level of the pattern
80 /// though, which prevents factoring from being able to see past them. This
81 /// optimization sinks them as far down into the pattern as possible.
83 /// Conceptually, we'd like to sink these predicates all the way to the last
84 /// matcher predicate in the series. However, it turns out that some
85 /// ComplexPatterns have side effects on the graph, so we really don't want to
86 /// run a the complex pattern if the pattern predicate will fail. For this
87 /// reason, we refuse to sink the pattern predicate past a ComplexPattern.
89 static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
90 // Recursively scan for a PatternPredicate.
91 // If we reached the end of the chain, we're done.
92 Matcher *N = MatcherPtr.get();
95 // Walk down all members of a scope node.
96 if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
97 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
98 OwningPtr<Matcher> Child(Scope->takeChild(i));
99 SinkPatternPredicates(Child);
100 Scope->resetChild(i, Child.take());
105 // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
107 CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
109 return SinkPatternPredicates(N->getNextPtr());
111 // Ok, we found one, lets try to sink it. Check if we can sink it past the
112 // next node in the chain. If not, we won't be able to change anything and
113 // might as well bail.
114 if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
117 // Okay, we know we can sink it past at least one node. Unlink it from the
118 // chain and scan for the new insertion point.
119 MatcherPtr.take(); // Don't delete CPPM.
120 MatcherPtr.reset(CPPM->takeNext());
122 N = MatcherPtr.get();
123 while (N->getNext()->isSafeToReorderWithPatternPredicate())
126 // At this point, we want to insert CPPM after N.
127 CPPM->setNext(N->takeNext());
131 /// FactorNodes - Turn matches like this:
133 /// OPC_CheckType i32
135 /// OPC_CheckType i32
138 /// OPC_CheckType i32
143 static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
144 // If we reached the end of the chain, we're done.
145 Matcher *N = MatcherPtr.get();
148 // If this is not a push node, just scan for one.
149 ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
151 return FactorNodes(N->getNextPtr());
153 // Okay, pull together the children of the scope node into a vector so we can
154 // inspect it more easily. While we're at it, bucket them up by the hash
155 // code of their first predicate.
156 SmallVector<Matcher*, 32> OptionsToMatch;
158 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
159 // Factor the subexpression.
160 OwningPtr<Matcher> Child(Scope->takeChild(i));
163 if (Matcher *N = Child.take())
164 OptionsToMatch.push_back(N);
167 SmallVector<Matcher*, 32> NewOptionsToMatch;
169 // Loop over options to match, merging neighboring patterns with identical
170 // starting nodes into a shared matcher.
171 for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
172 // Find the set of matchers that start with this node.
173 Matcher *Optn = OptionsToMatch[OptionIdx++];
175 if (OptionIdx == e) {
176 NewOptionsToMatch.push_back(Optn);
180 // See if the next option starts with the same matcher. If the two
181 // neighbors *do* start with the same matcher, we can factor the matcher out
182 // of at least these two patterns. See what the maximal set we can merge
184 SmallVector<Matcher*, 8> EqualMatchers;
185 EqualMatchers.push_back(Optn);
187 // Factor all of the known-equal matchers after this one into the same
189 while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
190 EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
192 // If we found a non-equal matcher, see if it is contradictory with the
193 // current node. If so, we know that the ordering relation between the
194 // current sets of nodes and this node don't matter. Look past it to see if
195 // we can merge anything else into this matching group.
196 unsigned Scan = OptionIdx;
198 while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
201 // Ok, we found something that isn't known to be contradictory. If it is
202 // equal, we can merge it into the set of nodes to factor, if not, we have
203 // to cease factoring.
204 if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
206 // If is equal after all, add the option to EqualMatchers and remove it
207 // from OptionsToMatch.
208 EqualMatchers.push_back(OptionsToMatch[Scan]);
209 OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
214 // Don't print it's obvious nothing extra could be merged anyway.
216 DEBUG(errs() << "Couldn't merge this:\n";
217 Optn->print(errs(), 4);
218 errs() << "into this:\n";
219 OptionsToMatch[Scan]->print(errs(), 4);
221 OptionsToMatch[Scan+1]->printOne(errs());
223 OptionsToMatch[Scan+2]->printOne(errs());
227 // If we only found one option starting with this matcher, no factoring is
229 if (EqualMatchers.size() == 1) {
230 NewOptionsToMatch.push_back(EqualMatchers[0]);
234 // Factor these checks by pulling the first node off each entry and
235 // discarding it. Take the first one off the first entry to reuse.
236 Matcher *Shared = Optn;
237 Optn = Optn->takeNext();
238 EqualMatchers[0] = Optn;
240 // Remove and delete the first node from the other matchers we're factoring.
241 for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
242 Matcher *Tmp = EqualMatchers[i]->takeNext();
243 delete EqualMatchers[i];
244 EqualMatchers[i] = Tmp;
247 Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
249 // Recursively factor the newly created node.
250 FactorNodes(Shared->getNextPtr());
252 NewOptionsToMatch.push_back(Shared);
255 // Reassemble a new Scope node.
256 assert(!NewOptionsToMatch.empty() && "where'd all our children go?");
257 if (NewOptionsToMatch.size() == 1)
258 MatcherPtr.reset(NewOptionsToMatch[0]);
260 Scope->setNumChildren(NewOptionsToMatch.size());
261 for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
262 Scope->resetChild(i, NewOptionsToMatch[i]);
266 Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher) {
267 OwningPtr<Matcher> MatcherPtr(TheMatcher);
268 ContractNodes(MatcherPtr);
269 SinkPatternPredicates(MatcherPtr);
270 FactorNodes(MatcherPtr);
271 return MatcherPtr.take();