xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/DAGISelMatcherOpt.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 //===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the DAG Matcher optimizer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenDAGPatterns.h"
14 #include "DAGISelMatcher.h"
15 #include "SDNodeProperties.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm;
20 
21 #define DEBUG_TYPE "isel-opt"
22 
23 /// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
24 /// into single compound nodes like RecordChild.
25 static void ContractNodes(std::unique_ptr<Matcher> &MatcherPtr,
26                           const CodeGenDAGPatterns &CGP) {
27   // If we reached the end of the chain, we're done.
28   Matcher *N = MatcherPtr.get();
29   if (!N)
30     return;
31 
32   // If we have a scope node, walk down all of the children.
33   if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
34     for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
35       std::unique_ptr<Matcher> Child(Scope->takeChild(i));
36       ContractNodes(Child, CGP);
37       Scope->resetChild(i, Child.release());
38     }
39     return;
40   }
41 
42   // If we found a movechild node with a node that comes in a 'foochild' form,
43   // transform it.
44   if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
45     Matcher *New = nullptr;
46     if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
47       if (MC->getChildNo() < 8) // Only have RecordChild0...7
48         New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
49                                      RM->getResultNo());
50 
51     if (CheckTypeMatcher *CT = dyn_cast<CheckTypeMatcher>(MC->getNext()))
52       if (MC->getChildNo() < 8 && // Only have CheckChildType0...7
53           CT->getResNo() == 0)    // CheckChildType checks res #0
54         New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
55 
56     if (CheckSameMatcher *CS = dyn_cast<CheckSameMatcher>(MC->getNext()))
57       if (MC->getChildNo() < 4) // Only have CheckChildSame0...3
58         New = new CheckChildSameMatcher(MC->getChildNo(), CS->getMatchNumber());
59 
60     if (CheckIntegerMatcher *CI = dyn_cast<CheckIntegerMatcher>(MC->getNext()))
61       if (MC->getChildNo() < 5) // Only have CheckChildInteger0...4
62         New = new CheckChildIntegerMatcher(MC->getChildNo(), CI->getValue());
63 
64     if (auto *CCC = dyn_cast<CheckCondCodeMatcher>(MC->getNext()))
65       if (MC->getChildNo() == 2) // Only have CheckChild2CondCode
66         New = new CheckChild2CondCodeMatcher(CCC->getCondCodeName());
67 
68     if (New) {
69       // Insert the new node.
70       New->setNext(MatcherPtr.release());
71       MatcherPtr.reset(New);
72       // Remove the old one.
73       MC->setNext(MC->getNext()->takeNext());
74       return ContractNodes(MatcherPtr, CGP);
75     }
76   }
77 
78   // Zap movechild -> moveparent.
79   if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
80     if (MoveParentMatcher *MP = dyn_cast<MoveParentMatcher>(MC->getNext())) {
81       MatcherPtr.reset(MP->takeNext());
82       return ContractNodes(MatcherPtr, CGP);
83     }
84 
85   // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
86   if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
87     if (CompleteMatchMatcher *CM =
88             dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
89       // We can only use MorphNodeTo if the result values match up.
90       unsigned RootResultFirst = EN->getFirstResultSlot();
91       bool ResultsMatch = true;
92       for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
93         if (CM->getResult(i) != RootResultFirst + i)
94           ResultsMatch = false;
95 
96       // If the selected node defines a subset of the glue/chain results, we
97       // can't use MorphNodeTo.  For example, we can't use MorphNodeTo if the
98       // matched pattern has a chain but the root node doesn't.
99       const PatternToMatch &Pattern = CM->getPattern();
100 
101       if (!EN->hasChain() &&
102           Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
103         ResultsMatch = false;
104 
105       // If the matched node has glue and the output root doesn't, we can't
106       // use MorphNodeTo.
107       //
108       // NOTE: Strictly speaking, we don't have to check for glue here
109       // because the code in the pattern generator doesn't handle it right.  We
110       // do it anyway for thoroughness.
111       if (!EN->hasOutGlue() &&
112           Pattern.getSrcPattern()->NodeHasProperty(SDNPOutGlue, CGP))
113         ResultsMatch = false;
114 
115 #if 0
116       // If the root result node defines more results than the source root node
117       // *and* has a chain or glue input, then we can't match it because it
118       // would end up replacing the extra result with the chain/glue.
119       if ((EN->hasGlue() || EN->hasChain()) &&
120           EN->getNumNonChainGlueVTs() > ... need to get no results reliably ...)
121         ResultMatch = false;
122 #endif
123 
124       if (ResultsMatch) {
125         const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
126         const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
127         MatcherPtr.reset(new MorphNodeToMatcher(
128             EN->getInstruction(), VTs, Operands, EN->hasChain(),
129             EN->hasInGlue(), EN->hasOutGlue(), EN->hasMemRefs(),
130             EN->getNumFixedArityOperands(), Pattern));
131         return;
132       }
133 
134       // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
135       // variants.
136     }
137 
138   ContractNodes(N->getNextPtr(), CGP);
139 
140   // If we have a CheckType/CheckChildType/Record node followed by a
141   // CheckOpcode, invert the two nodes.  We prefer to do structural checks
142   // before type checks, as this opens opportunities for factoring on targets
143   // like X86 where many operations are valid on multiple types.
144   if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
145        isa<RecordMatcher>(N)) &&
146       isa<CheckOpcodeMatcher>(N->getNext())) {
147     // Unlink the two nodes from the list.
148     Matcher *CheckType = MatcherPtr.release();
149     Matcher *CheckOpcode = CheckType->takeNext();
150     Matcher *Tail = CheckOpcode->takeNext();
151 
152     // Relink them.
153     MatcherPtr.reset(CheckOpcode);
154     CheckOpcode->setNext(CheckType);
155     CheckType->setNext(Tail);
156     return ContractNodes(MatcherPtr, CGP);
157   }
158 }
159 
160 /// FindNodeWithKind - Scan a series of matchers looking for a matcher with a
161 /// specified kind.  Return null if we didn't find one otherwise return the
162 /// matcher.
163 static Matcher *FindNodeWithKind(Matcher *M, Matcher::KindTy Kind) {
164   for (; M; M = M->getNext())
165     if (M->getKind() == Kind)
166       return M;
167   return nullptr;
168 }
169 
170 /// FactorNodes - Turn matches like this:
171 ///   Scope
172 ///     OPC_CheckType i32
173 ///       ABC
174 ///     OPC_CheckType i32
175 ///       XYZ
176 /// into:
177 ///   OPC_CheckType i32
178 ///     Scope
179 ///       ABC
180 ///       XYZ
181 ///
182 static void FactorNodes(std::unique_ptr<Matcher> &InputMatcherPtr) {
183   // Look for a push node. Iterates instead of recurses to reduce stack usage.
184   ScopeMatcher *Scope = nullptr;
185   std::unique_ptr<Matcher> *RebindableMatcherPtr = &InputMatcherPtr;
186   while (!Scope) {
187     // If we reached the end of the chain, we're done.
188     Matcher *N = RebindableMatcherPtr->get();
189     if (!N)
190       return;
191 
192     // If this is not a push node, just scan for one.
193     Scope = dyn_cast<ScopeMatcher>(N);
194     if (!Scope)
195       RebindableMatcherPtr = &(N->getNextPtr());
196   }
197   std::unique_ptr<Matcher> &MatcherPtr = *RebindableMatcherPtr;
198 
199   // Okay, pull together the children of the scope node into a vector so we can
200   // inspect it more easily.
201   SmallVector<Matcher *, 32> OptionsToMatch;
202 
203   for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
204     // Factor the subexpression.
205     std::unique_ptr<Matcher> Child(Scope->takeChild(i));
206     FactorNodes(Child);
207 
208     // If the child is a ScopeMatcher we can just merge its contents.
209     if (auto *SM = dyn_cast<ScopeMatcher>(Child.get())) {
210       for (unsigned j = 0, e = SM->getNumChildren(); j != e; ++j)
211         OptionsToMatch.push_back(SM->takeChild(j));
212     } else {
213       OptionsToMatch.push_back(Child.release());
214     }
215   }
216 
217   // Loop over options to match, merging neighboring patterns with identical
218   // starting nodes into a shared matcher.
219   auto E = OptionsToMatch.end();
220   for (auto I = OptionsToMatch.begin(); I != E; ++I) {
221     // If there are no other matchers left, there's nothing to merge with.
222     auto J = std::next(I);
223     if (J == E)
224       break;
225 
226     // Remember where we started. We'll use this to move non-equal elements.
227     auto K = J;
228 
229     // Find the set of matchers that start with this node.
230     Matcher *Optn = *I;
231 
232     // See if the next option starts with the same matcher.  If the two
233     // neighbors *do* start with the same matcher, we can factor the matcher out
234     // of at least these two patterns.  See what the maximal set we can merge
235     // together is.
236     SmallVector<Matcher *, 8> EqualMatchers;
237     EqualMatchers.push_back(Optn);
238 
239     // Factor all of the known-equal matchers after this one into the same
240     // group.
241     while (J != E && (*J)->isEqual(Optn))
242       EqualMatchers.push_back(*J++);
243 
244     // If we found a non-equal matcher, see if it is contradictory with the
245     // current node.  If so, we know that the ordering relation between the
246     // current sets of nodes and this node don't matter.  Look past it to see if
247     // we can merge anything else into this matching group.
248     while (J != E) {
249       Matcher *ScanMatcher = *J;
250 
251       // If we found an entry that matches out matcher, merge it into the set to
252       // handle.
253       if (Optn->isEqual(ScanMatcher)) {
254         // It is equal after all, add the option to EqualMatchers.
255         EqualMatchers.push_back(ScanMatcher);
256         ++J;
257         continue;
258       }
259 
260       // If the option we're checking for contradicts the start of the list,
261       // move it earlier in OptionsToMatch for the next iteration of the outer
262       // loop. Then continue searching for equal or contradictory matchers.
263       if (Optn->isContradictory(ScanMatcher)) {
264         *K++ = *J++;
265         continue;
266       }
267 
268       // If we're scanning for a simple node, see if it occurs later in the
269       // sequence.  If so, and if we can move it up, it might be contradictory
270       // or the same as what we're looking for.  If so, reorder it.
271       if (Optn->isSimplePredicateOrRecordNode()) {
272         Matcher *M2 = FindNodeWithKind(ScanMatcher, Optn->getKind());
273         if (M2 && M2 != ScanMatcher && M2->canMoveBefore(ScanMatcher) &&
274             (M2->isEqual(Optn) || M2->isContradictory(Optn))) {
275           Matcher *MatcherWithoutM2 = ScanMatcher->unlinkNode(M2);
276           M2->setNext(MatcherWithoutM2);
277           *J = M2;
278           continue;
279         }
280       }
281 
282       // Otherwise, we don't know how to handle this entry, we have to bail.
283       break;
284     }
285 
286     if (J != E &&
287         // Don't print if it's obvious nothing extract could be merged anyway.
288         std::next(J) != E) {
289       LLVM_DEBUG(errs() << "Couldn't merge this:\n"; Optn->print(errs(), 4);
290                  errs() << "into this:\n";
291                  (*J)->print(errs(), 4);
292                  (*std::next(J))->printOne(errs());
293                  if (std::next(J, 2) != E) (*std::next(J, 2))->printOne(errs());
294                  errs() << "\n");
295     }
296 
297     // If we removed any equal matchers, we may need to slide the rest of the
298     // elements down for the next iteration of the outer loop.
299     if (J != K) {
300       while (J != E)
301         *K++ = *J++;
302 
303       // Update end pointer for outer loop.
304       E = K;
305     }
306 
307     // If we only found one option starting with this matcher, no factoring is
308     // possible. Put the Matcher back in OptionsToMatch.
309     if (EqualMatchers.size() == 1) {
310       *I = EqualMatchers[0];
311       continue;
312     }
313 
314     // Factor these checks by pulling the first node off each entry and
315     // discarding it.  Take the first one off the first entry to reuse.
316     Matcher *Shared = Optn;
317     Optn = Optn->takeNext();
318     EqualMatchers[0] = Optn;
319 
320     // Remove and delete the first node from the other matchers we're factoring.
321     for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
322       Matcher *Tmp = EqualMatchers[i]->takeNext();
323       delete EqualMatchers[i];
324       EqualMatchers[i] = Tmp;
325       assert(!Optn == !Tmp && "Expected all to be null if any are null");
326     }
327 
328     if (EqualMatchers[0]) {
329       Shared->setNext(new ScopeMatcher(std::move(EqualMatchers)));
330 
331       // Recursively factor the newly created node.
332       FactorNodes(Shared->getNextPtr());
333     }
334 
335     // Put the new Matcher where we started in OptionsToMatch.
336     *I = Shared;
337   }
338 
339   // Trim the array to match the updated end.
340   if (E != OptionsToMatch.end())
341     OptionsToMatch.erase(E, OptionsToMatch.end());
342 
343   // If we're down to a single pattern to match, then we don't need this scope
344   // anymore.
345   if (OptionsToMatch.size() == 1) {
346     MatcherPtr.reset(OptionsToMatch[0]);
347     return;
348   }
349 
350   if (OptionsToMatch.empty()) {
351     MatcherPtr.reset();
352     return;
353   }
354 
355   // If our factoring failed (didn't achieve anything) see if we can simplify in
356   // other ways.
357 
358   // Check to see if all of the leading entries are now opcode checks.  If so,
359   // we can convert this Scope to be a OpcodeSwitch instead.
360   bool AllOpcodeChecks = true, AllTypeChecks = true;
361   for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {
362     // Check to see if this breaks a series of CheckOpcodeMatchers.
363     if (AllOpcodeChecks && !isa<CheckOpcodeMatcher>(OptionsToMatch[i])) {
364 #if 0
365       if (i > 3) {
366         errs() << "FAILING OPC #" << i << "\n";
367         OptionsToMatch[i]->dump();
368       }
369 #endif
370       AllOpcodeChecks = false;
371     }
372 
373     // Check to see if this breaks a series of CheckTypeMatcher's.
374     if (AllTypeChecks) {
375       CheckTypeMatcher *CTM = cast_or_null<CheckTypeMatcher>(
376           FindNodeWithKind(OptionsToMatch[i], Matcher::CheckType));
377       if (!CTM ||
378           // iPTR checks could alias any other case without us knowing, don't
379           // bother with them.
380           CTM->getType() == MVT::iPTR ||
381           // SwitchType only works for result #0.
382           CTM->getResNo() != 0 ||
383           // If the CheckType isn't at the start of the list, see if we can move
384           // it there.
385           !CTM->canMoveBefore(OptionsToMatch[i])) {
386 #if 0
387         if (i > 3 && AllTypeChecks) {
388           errs() << "FAILING TYPE #" << i << "\n";
389           OptionsToMatch[i]->dump();
390         }
391 #endif
392         AllTypeChecks = false;
393       }
394     }
395   }
396 
397   // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
398   if (AllOpcodeChecks) {
399     StringSet<> Opcodes;
400     SmallVector<std::pair<const SDNodeInfo *, Matcher *>, 8> Cases;
401     for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {
402       CheckOpcodeMatcher *COM = cast<CheckOpcodeMatcher>(OptionsToMatch[i]);
403       assert(Opcodes.insert(COM->getOpcode().getEnumName()).second &&
404              "Duplicate opcodes not factored?");
405       Cases.push_back(std::make_pair(&COM->getOpcode(), COM->takeNext()));
406       delete COM;
407     }
408 
409     MatcherPtr.reset(new SwitchOpcodeMatcher(std::move(Cases)));
410     return;
411   }
412 
413   // If all the options are CheckType's, we can form the SwitchType, woot.
414   if (AllTypeChecks) {
415     DenseMap<unsigned, unsigned> TypeEntry;
416     SmallVector<std::pair<MVT::SimpleValueType, Matcher *>, 8> Cases;
417     for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {
418       Matcher *M = FindNodeWithKind(OptionsToMatch[i], Matcher::CheckType);
419       assert(M && isa<CheckTypeMatcher>(M) && "Unknown Matcher type");
420 
421       auto *CTM = cast<CheckTypeMatcher>(M);
422       Matcher *MatcherWithoutCTM = OptionsToMatch[i]->unlinkNode(CTM);
423       MVT::SimpleValueType CTMTy = CTM->getType();
424       delete CTM;
425 
426       unsigned &Entry = TypeEntry[CTMTy];
427       if (Entry != 0) {
428         // If we have unfactored duplicate types, then we should factor them.
429         Matcher *PrevMatcher = Cases[Entry - 1].second;
430         if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(PrevMatcher)) {
431           SM->setNumChildren(SM->getNumChildren() + 1);
432           SM->resetChild(SM->getNumChildren() - 1, MatcherWithoutCTM);
433           continue;
434         }
435 
436         SmallVector<Matcher *, 2> Entries = {PrevMatcher, MatcherWithoutCTM};
437         Cases[Entry - 1].second = new ScopeMatcher(std::move(Entries));
438         continue;
439       }
440 
441       Entry = Cases.size() + 1;
442       Cases.push_back(std::make_pair(CTMTy, MatcherWithoutCTM));
443     }
444 
445     // Make sure we recursively factor any scopes we may have created.
446     for (auto &M : Cases) {
447       if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M.second)) {
448         std::unique_ptr<Matcher> Scope(SM);
449         FactorNodes(Scope);
450         M.second = Scope.release();
451         assert(M.second && "null matcher");
452       }
453     }
454 
455     if (Cases.size() != 1) {
456       MatcherPtr.reset(new SwitchTypeMatcher(std::move(Cases)));
457     } else {
458       // If we factored and ended up with one case, create it now.
459       MatcherPtr.reset(new CheckTypeMatcher(Cases[0].first, 0));
460       MatcherPtr->setNext(Cases[0].second);
461     }
462     return;
463   }
464 
465   // Reassemble the Scope node with the adjusted children.
466   Scope->setNumChildren(OptionsToMatch.size());
467   for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i)
468     Scope->resetChild(i, OptionsToMatch[i]);
469 }
470 
471 void llvm::OptimizeMatcher(std::unique_ptr<Matcher> &MatcherPtr,
472                            const CodeGenDAGPatterns &CGP) {
473   ContractNodes(MatcherPtr, CGP);
474   FactorNodes(MatcherPtr);
475 }
476