1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
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 #include "CodeGenDAGPatterns.h"
10 #include "CodeGenInstruction.h"
11 #include "CodeGenRegisters.h"
12 #include "DAGISelMatcher.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/TableGen/Error.h"
16 #include "llvm/TableGen/Record.h"
17 #include <utility>
18 using namespace llvm;
19 
20 
21 /// getRegisterValueType - Look up and return the ValueType of the specified
22 /// register. If the register is a member of multiple register classes which
23 /// have different associated types, return MVT::Other.
24 static MVT::SimpleValueType getRegisterValueType(Record *R,
25                                                  const CodeGenTarget &T) {
26   bool FoundRC = false;
27   MVT::SimpleValueType VT = MVT::Other;
28   const CodeGenRegister *Reg = T.getRegBank().getReg(R);
29 
30   for (const auto &RC : T.getRegBank().getRegClasses()) {
31     if (!RC.contains(Reg))
32       continue;
33 
34     if (!FoundRC) {
35       FoundRC = true;
36       const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
37       if (VVT.isSimple())
38         VT = VVT.getSimple().SimpleTy;
39       continue;
40     }
41 
42 #ifndef NDEBUG
43     // If this occurs in multiple register classes, they all have to agree.
44     const ValueTypeByHwMode &T = RC.getValueTypeNum(0);
45     assert((!T.isSimple() || T.getSimple().SimpleTy == VT) &&
46            "ValueType mismatch between register classes for this register");
47 #endif
48   }
49   return VT;
50 }
51 
52 
53 namespace {
54   class MatcherGen {
55     const PatternToMatch &Pattern;
56     const CodeGenDAGPatterns &CGP;
57 
58     /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
59     /// out with all of the types removed.  This allows us to insert type checks
60     /// as we scan the tree.
61     TreePatternNodePtr PatWithNoTypes;
62 
63     /// VariableMap - A map from variable names ('$dst') to the recorded operand
64     /// number that they were captured as.  These are biased by 1 to make
65     /// insertion easier.
66     StringMap<unsigned> VariableMap;
67 
68     /// This maintains the recorded operand number that OPC_CheckComplexPattern
69     /// drops each sub-operand into. We don't want to insert these into
70     /// VariableMap because that leads to identity checking if they are
71     /// encountered multiple times. Biased by 1 like VariableMap for
72     /// consistency.
73     StringMap<unsigned> NamedComplexPatternOperands;
74 
75     /// NextRecordedOperandNo - As we emit opcodes to record matched values in
76     /// the RecordedNodes array, this keeps track of which slot will be next to
77     /// record into.
78     unsigned NextRecordedOperandNo;
79 
80     /// MatchedChainNodes - This maintains the position in the recorded nodes
81     /// array of all of the recorded input nodes that have chains.
82     SmallVector<unsigned, 2> MatchedChainNodes;
83 
84     /// MatchedComplexPatterns - This maintains a list of all of the
85     /// ComplexPatterns that we need to check. The second element of each pair
86     /// is the recorded operand number of the input node.
87     SmallVector<std::pair<const TreePatternNode*,
88                           unsigned>, 2> MatchedComplexPatterns;
89 
90     /// PhysRegInputs - List list has an entry for each explicitly specified
91     /// physreg input to the pattern.  The first elt is the Register node, the
92     /// second is the recorded slot number the input pattern match saved it in.
93     SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
94 
95     /// Matcher - This is the top level of the generated matcher, the result.
96     Matcher *TheMatcher;
97 
98     /// CurPredicate - As we emit matcher nodes, this points to the latest check
99     /// which should have future checks stuck into its Next position.
100     Matcher *CurPredicate;
101   public:
102     MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
103 
104     bool EmitMatcherCode(unsigned Variant);
105     void EmitResultCode();
106 
107     Matcher *GetMatcher() const { return TheMatcher; }
108   private:
109     void AddMatcher(Matcher *NewNode);
110     void InferPossibleTypes(unsigned ForceMode);
111 
112     // Matcher Generation.
113     void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes,
114                        unsigned ForceMode);
115     void EmitLeafMatchCode(const TreePatternNode *N);
116     void EmitOperatorMatchCode(const TreePatternNode *N,
117                                TreePatternNode *NodeNoTypes,
118                                unsigned ForceMode);
119 
120     /// If this is the first time a node with unique identifier Name has been
121     /// seen, record it. Otherwise, emit a check to make sure this is the same
122     /// node. Returns true if this is the first encounter.
123     bool recordUniqueNode(ArrayRef<std::string> Names);
124 
125     // Result Code Generation.
126     unsigned getNamedArgumentSlot(StringRef Name) {
127       unsigned VarMapEntry = VariableMap[Name];
128       assert(VarMapEntry != 0 &&
129              "Variable referenced but not defined and not caught earlier!");
130       return VarMapEntry-1;
131     }
132 
133     void EmitResultOperand(const TreePatternNode *N,
134                            SmallVectorImpl<unsigned> &ResultOps);
135     void EmitResultOfNamedOperand(const TreePatternNode *N,
136                                   SmallVectorImpl<unsigned> &ResultOps);
137     void EmitResultLeafAsOperand(const TreePatternNode *N,
138                                  SmallVectorImpl<unsigned> &ResultOps);
139     void EmitResultInstructionAsOperand(const TreePatternNode *N,
140                                         SmallVectorImpl<unsigned> &ResultOps);
141     void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
142                                         SmallVectorImpl<unsigned> &ResultOps);
143     };
144 
145 } // end anonymous namespace
146 
147 MatcherGen::MatcherGen(const PatternToMatch &pattern,
148                        const CodeGenDAGPatterns &cgp)
149 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
150   TheMatcher(nullptr), CurPredicate(nullptr) {
151   // We need to produce the matcher tree for the patterns source pattern.  To do
152   // this we need to match the structure as well as the types.  To do the type
153   // matching, we want to figure out the fewest number of type checks we need to
154   // emit.  For example, if there is only one integer type supported by a
155   // target, there should be no type comparisons at all for integer patterns!
156   //
157   // To figure out the fewest number of type checks needed, clone the pattern,
158   // remove the types, then perform type inference on the pattern as a whole.
159   // If there are unresolved types, emit an explicit check for those types,
160   // apply the type to the tree, then rerun type inference.  Iterate until all
161   // types are resolved.
162   //
163   PatWithNoTypes = Pattern.getSrcPattern()->clone();
164   PatWithNoTypes->RemoveAllTypes();
165 
166   // If there are types that are manifestly known, infer them.
167   InferPossibleTypes(Pattern.getForceMode());
168 }
169 
170 /// InferPossibleTypes - As we emit the pattern, we end up generating type
171 /// checks and applying them to the 'PatWithNoTypes' tree.  As we do this, we
172 /// want to propagate implied types as far throughout the tree as possible so
173 /// that we avoid doing redundant type checks.  This does the type propagation.
174 void MatcherGen::InferPossibleTypes(unsigned ForceMode) {
175   // TP - Get *SOME* tree pattern, we don't care which.  It is only used for
176   // diagnostics, which we know are impossible at this point.
177   TreePattern &TP = *CGP.pf_begin()->second;
178   TP.getInfer().CodeGen = true;
179   TP.getInfer().ForceMode = ForceMode;
180 
181   bool MadeChange = true;
182   while (MadeChange)
183     MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
184                                               true/*Ignore reg constraints*/);
185 }
186 
187 
188 /// AddMatcher - Add a matcher node to the current graph we're building.
189 void MatcherGen::AddMatcher(Matcher *NewNode) {
190   if (CurPredicate)
191     CurPredicate->setNext(NewNode);
192   else
193     TheMatcher = NewNode;
194   CurPredicate = NewNode;
195 }
196 
197 
198 //===----------------------------------------------------------------------===//
199 // Pattern Match Generation
200 //===----------------------------------------------------------------------===//
201 
202 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
203 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
204   assert(N->isLeaf() && "Not a leaf?");
205 
206   // Direct match against an integer constant.
207   if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
208     // If this is the root of the dag we're matching, we emit a redundant opcode
209     // check to ensure that this gets folded into the normal top-level
210     // OpcodeSwitch.
211     if (N == Pattern.getSrcPattern()) {
212       const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
213       AddMatcher(new CheckOpcodeMatcher(NI));
214     }
215 
216     return AddMatcher(new CheckIntegerMatcher(II->getValue()));
217   }
218 
219   // An UnsetInit represents a named node without any constraints.
220   if (isa<UnsetInit>(N->getLeafValue())) {
221     assert(N->hasName() && "Unnamed ? leaf");
222     return;
223   }
224 
225   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
226   if (!DI) {
227     errs() << "Unknown leaf kind: " << *N << "\n";
228     abort();
229   }
230 
231   Record *LeafRec = DI->getDef();
232 
233   // A ValueType leaf node can represent a register when named, or itself when
234   // unnamed.
235   if (LeafRec->isSubClassOf("ValueType")) {
236     // A named ValueType leaf always matches: (add i32:$a, i32:$b).
237     if (N->hasName())
238       return;
239     // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
240     return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
241   }
242 
243   if (// Handle register references.  Nothing to do here, they always match.
244       LeafRec->isSubClassOf("RegisterClass") ||
245       LeafRec->isSubClassOf("RegisterOperand") ||
246       LeafRec->isSubClassOf("PointerLikeRegClass") ||
247       LeafRec->isSubClassOf("SubRegIndex") ||
248       // Place holder for SRCVALUE nodes. Nothing to do here.
249       LeafRec->getName() == "srcvalue")
250     return;
251 
252   // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
253   // record the register
254   if (LeafRec->isSubClassOf("Register")) {
255     AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
256                                  NextRecordedOperandNo));
257     PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
258     return;
259   }
260 
261   if (LeafRec->isSubClassOf("CondCode"))
262     return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
263 
264   if (LeafRec->isSubClassOf("ComplexPattern")) {
265     // We can't model ComplexPattern uses that don't have their name taken yet.
266     // The OPC_CheckComplexPattern operation implicitly records the results.
267     if (N->getName().empty()) {
268       std::string S;
269       raw_string_ostream OS(S);
270       OS << "We expect complex pattern uses to have names: " << *N;
271       PrintFatalError(S);
272     }
273 
274     // Remember this ComplexPattern so that we can emit it after all the other
275     // structural matches are done.
276     unsigned InputOperand = VariableMap[N->getName()] - 1;
277     MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
278     return;
279   }
280 
281   if (LeafRec->getName() == "immAllOnesV") {
282     // If this is the root of the dag we're matching, we emit a redundant opcode
283     // check to ensure that this gets folded into the normal top-level
284     // OpcodeSwitch.
285     if (N == Pattern.getSrcPattern()) {
286       MVT VT = N->getSimpleType(0);
287       StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
288       const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
289       AddMatcher(new CheckOpcodeMatcher(NI));
290     }
291     return AddMatcher(new CheckImmAllOnesVMatcher());
292   }
293   if (LeafRec->getName() == "immAllZerosV") {
294     // If this is the root of the dag we're matching, we emit a redundant opcode
295     // check to ensure that this gets folded into the normal top-level
296     // OpcodeSwitch.
297     if (N == Pattern.getSrcPattern()) {
298       MVT VT = N->getSimpleType(0);
299       StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
300       const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
301       AddMatcher(new CheckOpcodeMatcher(NI));
302     }
303     return AddMatcher(new CheckImmAllZerosVMatcher());
304   }
305 
306   errs() << "Unknown leaf kind: " << *N << "\n";
307   abort();
308 }
309 
310 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
311                                        TreePatternNode *NodeNoTypes,
312                                        unsigned ForceMode) {
313   assert(!N->isLeaf() && "Not an operator?");
314 
315   if (N->getOperator()->isSubClassOf("ComplexPattern")) {
316     // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
317     // "MY_PAT:op1:op2". We should already have validated that the uses are
318     // consistent.
319     std::string PatternName = std::string(N->getOperator()->getName());
320     for (unsigned i = 0; i < N->getNumChildren(); ++i) {
321       PatternName += ":";
322       PatternName += N->getChild(i)->getName();
323     }
324 
325     if (recordUniqueNode(PatternName)) {
326       auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
327       MatchedComplexPatterns.push_back(NodeAndOpNum);
328     }
329 
330     return;
331   }
332 
333   const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
334 
335   // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
336   // a constant without a predicate fn that has more than one bit set, handle
337   // this as a special case.  This is usually for targets that have special
338   // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
339   // handling stuff).  Using these instructions is often far more efficient
340   // than materializing the constant.  Unfortunately, both the instcombiner
341   // and the dag combiner can often infer that bits are dead, and thus drop
342   // them from the mask in the dag.  For example, it might turn 'AND X, 255'
343   // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
344   // to handle this.
345   if ((N->getOperator()->getName() == "and" ||
346        N->getOperator()->getName() == "or") &&
347       N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() &&
348       N->getPredicateCalls().empty()) {
349     if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
350       if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
351         // If this is at the root of the pattern, we emit a redundant
352         // CheckOpcode so that the following checks get factored properly under
353         // a single opcode check.
354         if (N == Pattern.getSrcPattern())
355           AddMatcher(new CheckOpcodeMatcher(CInfo));
356 
357         // Emit the CheckAndImm/CheckOrImm node.
358         if (N->getOperator()->getName() == "and")
359           AddMatcher(new CheckAndImmMatcher(II->getValue()));
360         else
361           AddMatcher(new CheckOrImmMatcher(II->getValue()));
362 
363         // Match the LHS of the AND as appropriate.
364         AddMatcher(new MoveChildMatcher(0));
365         EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0), ForceMode);
366         AddMatcher(new MoveParentMatcher());
367         return;
368       }
369     }
370   }
371 
372   // Check that the current opcode lines up.
373   AddMatcher(new CheckOpcodeMatcher(CInfo));
374 
375   // If this node has memory references (i.e. is a load or store), tell the
376   // interpreter to capture them in the memref array.
377   if (N->NodeHasProperty(SDNPMemOperand, CGP))
378     AddMatcher(new RecordMemRefMatcher());
379 
380   // If this node has a chain, then the chain is operand #0 is the SDNode, and
381   // the child numbers of the node are all offset by one.
382   unsigned OpNo = 0;
383   if (N->NodeHasProperty(SDNPHasChain, CGP)) {
384     // Record the node and remember it in our chained nodes list.
385     AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
386                                          "' chained node",
387                                  NextRecordedOperandNo));
388     // Remember all of the input chains our pattern will match.
389     MatchedChainNodes.push_back(NextRecordedOperandNo++);
390 
391     // Don't look at the input chain when matching the tree pattern to the
392     // SDNode.
393     OpNo = 1;
394 
395     // If this node is not the root and the subtree underneath it produces a
396     // chain, then the result of matching the node is also produce a chain.
397     // Beyond that, this means that we're also folding (at least) the root node
398     // into the node that produce the chain (for example, matching
399     // "(add reg, (load ptr))" as a add_with_memory on X86).  This is
400     // problematic, if the 'reg' node also uses the load (say, its chain).
401     // Graphically:
402     //
403     //         [LD]
404     //         ^  ^
405     //         |  \                              DAG's like cheese.
406     //        /    |
407     //       /    [YY]
408     //       |     ^
409     //      [XX]--/
410     //
411     // It would be invalid to fold XX and LD.  In this case, folding the two
412     // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
413     // To prevent this, we emit a dynamic check for legality before allowing
414     // this to be folded.
415     //
416     const TreePatternNode *Root = Pattern.getSrcPattern();
417     if (N != Root) {                             // Not the root of the pattern.
418       // If there is a node between the root and this node, then we definitely
419       // need to emit the check.
420       bool NeedCheck = !Root->hasChild(N);
421 
422       // If it *is* an immediate child of the root, we can still need a check if
423       // the root SDNode has multiple inputs.  For us, this means that it is an
424       // intrinsic, has multiple operands, or has other inputs like chain or
425       // glue).
426       if (!NeedCheck) {
427         const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
428         NeedCheck =
429           Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
430           Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
431           Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
432           PInfo.getNumOperands() > 1 ||
433           PInfo.hasProperty(SDNPHasChain) ||
434           PInfo.hasProperty(SDNPInGlue) ||
435           PInfo.hasProperty(SDNPOptInGlue);
436       }
437 
438       if (NeedCheck)
439         AddMatcher(new CheckFoldableChainNodeMatcher());
440     }
441   }
442 
443   // If this node has an output glue and isn't the root, remember it.
444   if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
445       N != Pattern.getSrcPattern()) {
446     // TODO: This redundantly records nodes with both glues and chains.
447 
448     // Record the node and remember it in our chained nodes list.
449     AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
450                                          "' glue output node",
451                                  NextRecordedOperandNo));
452   }
453 
454   // If this node is known to have an input glue or if it *might* have an input
455   // glue, capture it as the glue input of the pattern.
456   if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
457       N->NodeHasProperty(SDNPInGlue, CGP))
458     AddMatcher(new CaptureGlueInputMatcher());
459 
460   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
461     // Get the code suitable for matching this child.  Move to the child, check
462     // it then move back to the parent.
463     AddMatcher(new MoveChildMatcher(OpNo));
464     EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i), ForceMode);
465     AddMatcher(new MoveParentMatcher());
466   }
467 }
468 
469 bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {
470   unsigned Entry = 0;
471   for (const std::string &Name : Names) {
472     unsigned &VarMapEntry = VariableMap[Name];
473     if (!Entry)
474       Entry = VarMapEntry;
475     assert(Entry == VarMapEntry);
476   }
477 
478   bool NewRecord = false;
479   if (Entry == 0) {
480     // If it is a named node, we must emit a 'Record' opcode.
481     std::string WhatFor;
482     for (const std::string &Name : Names) {
483       if (!WhatFor.empty())
484         WhatFor += ',';
485       WhatFor += "$" + Name;
486     }
487     AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));
488     Entry = ++NextRecordedOperandNo;
489     NewRecord = true;
490   } else {
491     // If we get here, this is a second reference to a specific name.  Since
492     // we already have checked that the first reference is valid, we don't
493     // have to recursively match it, just check that it's the same as the
494     // previously named thing.
495     AddMatcher(new CheckSameMatcher(Entry-1));
496   }
497 
498   for (const std::string &Name : Names)
499     VariableMap[Name] = Entry;
500 
501   return NewRecord;
502 }
503 
504 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
505                                TreePatternNode *NodeNoTypes,
506                                unsigned ForceMode) {
507   // If N and NodeNoTypes don't agree on a type, then this is a case where we
508   // need to do a type check.  Emit the check, apply the type to NodeNoTypes and
509   // reinfer any correlated types.
510   SmallVector<unsigned, 2> ResultsToTypeCheck;
511 
512   for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
513     if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
514     NodeNoTypes->setType(i, N->getExtType(i));
515     InferPossibleTypes(ForceMode);
516     ResultsToTypeCheck.push_back(i);
517   }
518 
519   // If this node has a name associated with it, capture it in VariableMap. If
520   // we already saw this in the pattern, emit code to verify dagness.
521   SmallVector<std::string, 4> Names;
522   if (!N->getName().empty())
523     Names.push_back(N->getName());
524 
525   for (const ScopedName &Name : N->getNamesAsPredicateArg()) {
526     Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());
527   }
528 
529   if (!Names.empty()) {
530     if (!recordUniqueNode(Names))
531       return;
532   }
533 
534   if (N->isLeaf())
535     EmitLeafMatchCode(N);
536   else
537     EmitOperatorMatchCode(N, NodeNoTypes, ForceMode);
538 
539   // If there are node predicates for this node, generate their checks.
540   for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) {
541     const TreePredicateCall &Pred = N->getPredicateCalls()[i];
542     SmallVector<unsigned, 4> Operands;
543     if (Pred.Fn.usesOperands()) {
544       TreePattern *TP = Pred.Fn.getOrigPatFragRecord();
545       for (unsigned i = 0; i < TP->getNumArgs(); ++i) {
546         std::string Name =
547             ("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();
548         Operands.push_back(getNamedArgumentSlot(Name));
549       }
550     }
551     AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));
552   }
553 
554   for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
555     AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
556                                     ResultsToTypeCheck[i]));
557 }
558 
559 /// EmitMatcherCode - Generate the code that matches the predicate of this
560 /// pattern for the specified Variant.  If the variant is invalid this returns
561 /// true and does not generate code, if it is valid, it returns false.
562 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
563   // If the root of the pattern is a ComplexPattern and if it is specified to
564   // match some number of root opcodes, these are considered to be our variants.
565   // Depending on which variant we're generating code for, emit the root opcode
566   // check.
567   if (const ComplexPattern *CP =
568                    Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
569     const std::vector<Record*> &OpNodes = CP->getRootNodes();
570     assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
571     if (Variant >= OpNodes.size()) return true;
572 
573     AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
574   } else {
575     if (Variant != 0) return true;
576   }
577 
578   // Emit the matcher for the pattern structure and types.
579   EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get(),
580                 Pattern.getForceMode());
581 
582   // If the pattern has a predicate on it (e.g. only enabled when a subtarget
583   // feature is around, do the check).
584   if (!Pattern.getPredicateCheck().empty())
585     AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
586 
587   // Now that we've completed the structural type match, emit any ComplexPattern
588   // checks (e.g. addrmode matches).  We emit this after the structural match
589   // because they are generally more expensive to evaluate and more difficult to
590   // factor.
591   for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
592     auto N = MatchedComplexPatterns[i].first;
593 
594     // Remember where the results of this match get stuck.
595     if (N->isLeaf()) {
596       NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
597     } else {
598       unsigned CurOp = NextRecordedOperandNo;
599       for (unsigned i = 0; i < N->getNumChildren(); ++i) {
600         NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
601         CurOp += N->getChild(i)->getNumMIResults(CGP);
602       }
603     }
604 
605     // Get the slot we recorded the value in from the name on the node.
606     unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
607 
608     const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
609 
610     // Emit a CheckComplexPat operation, which does the match (aborting if it
611     // fails) and pushes the matched operands onto the recorded nodes list.
612     AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
613                                           N->getName(), NextRecordedOperandNo));
614 
615     // Record the right number of operands.
616     NextRecordedOperandNo += CP.getNumOperands();
617     if (CP.hasProperty(SDNPHasChain)) {
618       // If the complex pattern has a chain, then we need to keep track of the
619       // fact that we just recorded a chain input.  The chain input will be
620       // matched as the last operand of the predicate if it was successful.
621       ++NextRecordedOperandNo; // Chained node operand.
622 
623       // It is the last operand recorded.
624       assert(NextRecordedOperandNo > 1 &&
625              "Should have recorded input/result chains at least!");
626       MatchedChainNodes.push_back(NextRecordedOperandNo-1);
627     }
628 
629     // TODO: Complex patterns can't have output glues, if they did, we'd want
630     // to record them.
631   }
632 
633   return false;
634 }
635 
636 
637 //===----------------------------------------------------------------------===//
638 // Node Result Generation
639 //===----------------------------------------------------------------------===//
640 
641 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
642                                           SmallVectorImpl<unsigned> &ResultOps){
643   assert(!N->getName().empty() && "Operand not named!");
644 
645   if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
646     // Complex operands have already been completely selected, just find the
647     // right slot ant add the arguments directly.
648     for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
649       ResultOps.push_back(SlotNo - 1 + i);
650 
651     return;
652   }
653 
654   unsigned SlotNo = getNamedArgumentSlot(N->getName());
655 
656   // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
657   // version of the immediate so that it doesn't get selected due to some other
658   // node use.
659   if (!N->isLeaf()) {
660     StringRef OperatorName = N->getOperator()->getName();
661     if (OperatorName == "imm" || OperatorName == "fpimm") {
662       AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
663       ResultOps.push_back(NextRecordedOperandNo++);
664       return;
665     }
666   }
667 
668   for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
669     ResultOps.push_back(SlotNo + i);
670 }
671 
672 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
673                                          SmallVectorImpl<unsigned> &ResultOps) {
674   assert(N->isLeaf() && "Must be a leaf");
675 
676   if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
677     AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
678     ResultOps.push_back(NextRecordedOperandNo++);
679     return;
680   }
681 
682   // If this is an explicit register reference, handle it.
683   if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
684     Record *Def = DI->getDef();
685     if (Def->isSubClassOf("Register")) {
686       const CodeGenRegister *Reg =
687         CGP.getTargetInfo().getRegBank().getReg(Def);
688       AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
689       ResultOps.push_back(NextRecordedOperandNo++);
690       return;
691     }
692 
693     if (Def->getName() == "zero_reg") {
694       AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
695       ResultOps.push_back(NextRecordedOperandNo++);
696       return;
697     }
698 
699     if (Def->getName() == "undef_tied_input") {
700       std::array<MVT::SimpleValueType, 1> ResultVTs = {{ N->getSimpleType(0) }};
701       std::array<unsigned, 0> InstOps;
702       auto IDOperandNo = NextRecordedOperandNo++;
703       AddMatcher(new EmitNodeMatcher("TargetOpcode::IMPLICIT_DEF",
704                                      ResultVTs, InstOps, false, false, false,
705                                      false, -1, IDOperandNo));
706       ResultOps.push_back(IDOperandNo);
707       return;
708     }
709 
710     // Handle a reference to a register class. This is used
711     // in COPY_TO_SUBREG instructions.
712     if (Def->isSubClassOf("RegisterOperand"))
713       Def = Def->getValueAsDef("RegClass");
714     if (Def->isSubClassOf("RegisterClass")) {
715       // If the register class has an enum integer value greater than 127, the
716       // encoding overflows the limit of 7 bits, which precludes the use of
717       // StringIntegerMatcher. In this case, fallback to using IntegerMatcher.
718       const CodeGenRegisterClass &RC =
719           CGP.getTargetInfo().getRegisterClass(Def);
720       if (RC.EnumValue <= 127) {
721         std::string Value = getQualifiedName(Def) + "RegClassID";
722         AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
723         ResultOps.push_back(NextRecordedOperandNo++);
724       } else {
725         AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32));
726         ResultOps.push_back(NextRecordedOperandNo++);
727       }
728       return;
729     }
730 
731     // Handle a subregister index. This is used for INSERT_SUBREG etc.
732     if (Def->isSubClassOf("SubRegIndex")) {
733       const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank();
734       // If we have more than 127 subreg indices the encoding can overflow
735       // 7 bit and we cannot use StringInteger.
736       if (RB.getSubRegIndices().size() > 127) {
737         const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def);
738         assert(I && "Cannot find subreg index by name!");
739         if (I->EnumValue > 127) {
740           AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32));
741           ResultOps.push_back(NextRecordedOperandNo++);
742           return;
743         }
744       }
745       std::string Value = getQualifiedName(Def);
746       AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
747       ResultOps.push_back(NextRecordedOperandNo++);
748       return;
749     }
750   }
751 
752   errs() << "unhandled leaf node:\n";
753   N->dump();
754 }
755 
756 static bool
757 mayInstNodeLoadOrStore(const TreePatternNode *N,
758                        const CodeGenDAGPatterns &CGP) {
759   Record *Op = N->getOperator();
760   const CodeGenTarget &CGT = CGP.getTargetInfo();
761   CodeGenInstruction &II = CGT.getInstruction(Op);
762   return II.mayLoad || II.mayStore;
763 }
764 
765 static unsigned
766 numNodesThatMayLoadOrStore(const TreePatternNode *N,
767                            const CodeGenDAGPatterns &CGP) {
768   if (N->isLeaf())
769     return 0;
770 
771   Record *OpRec = N->getOperator();
772   if (!OpRec->isSubClassOf("Instruction"))
773     return 0;
774 
775   unsigned Count = 0;
776   if (mayInstNodeLoadOrStore(N, CGP))
777     ++Count;
778 
779   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
780     Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
781 
782   return Count;
783 }
784 
785 void MatcherGen::
786 EmitResultInstructionAsOperand(const TreePatternNode *N,
787                                SmallVectorImpl<unsigned> &OutputOps) {
788   Record *Op = N->getOperator();
789   const CodeGenTarget &CGT = CGP.getTargetInfo();
790   CodeGenInstruction &II = CGT.getInstruction(Op);
791   const DAGInstruction &Inst = CGP.getInstruction(Op);
792 
793   bool isRoot = N == Pattern.getDstPattern();
794 
795   // TreeHasOutGlue - True if this tree has glue.
796   bool TreeHasInGlue = false, TreeHasOutGlue = false;
797   if (isRoot) {
798     const TreePatternNode *SrcPat = Pattern.getSrcPattern();
799     TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
800                     SrcPat->TreeHasProperty(SDNPInGlue, CGP);
801 
802     // FIXME2: this is checking the entire pattern, not just the node in
803     // question, doing this just for the root seems like a total hack.
804     TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
805   }
806 
807   // NumResults - This is the number of results produced by the instruction in
808   // the "outs" list.
809   unsigned NumResults = Inst.getNumResults();
810 
811   // Number of operands we know the output instruction must have. If it is
812   // variadic, we could have more operands.
813   unsigned NumFixedOperands = II.Operands.size();
814 
815   SmallVector<unsigned, 8> InstOps;
816 
817   // Loop over all of the fixed operands of the instruction pattern, emitting
818   // code to fill them all in. The node 'N' usually has number children equal to
819   // the number of input operands of the instruction.  However, in cases where
820   // there are predicate operands for an instruction, we need to fill in the
821   // 'execute always' values. Match up the node operands to the instruction
822   // operands to do this.
823   unsigned ChildNo = 0;
824 
825   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
826   // number of operands at the end of the list which have default values.
827   // Those can come from the pattern if it provides enough arguments, or be
828   // filled in with the default if the pattern hasn't provided them. But any
829   // operand with a default value _before_ the last mandatory one will be
830   // filled in with their defaults unconditionally.
831   unsigned NonOverridableOperands = NumFixedOperands;
832   while (NonOverridableOperands > NumResults &&
833          CGP.operandHasDefault(II.Operands[NonOverridableOperands-1].Rec))
834     --NonOverridableOperands;
835 
836   for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
837        InstOpNo != e; ++InstOpNo) {
838     // Determine what to emit for this operand.
839     Record *OperandNode = II.Operands[InstOpNo].Rec;
840     if (CGP.operandHasDefault(OperandNode) &&
841         (InstOpNo < NonOverridableOperands || ChildNo >= N->getNumChildren())) {
842       // This is a predicate or optional def operand which the pattern has not
843       // overridden, or which we aren't letting it override; emit the 'default
844       // ops' operands.
845       const DAGDefaultOperand &DefaultOp
846         = CGP.getDefaultOperand(OperandNode);
847       for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
848         EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps);
849       continue;
850     }
851 
852     // Otherwise this is a normal operand or a predicate operand without
853     // 'execute always'; emit it.
854 
855     // For operands with multiple sub-operands we may need to emit
856     // multiple child patterns to cover them all.  However, ComplexPattern
857     // children may themselves emit multiple MI operands.
858     unsigned NumSubOps = 1;
859     if (OperandNode->isSubClassOf("Operand")) {
860       DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
861       if (unsigned NumArgs = MIOpInfo->getNumArgs())
862         NumSubOps = NumArgs;
863     }
864 
865     unsigned FinalNumOps = InstOps.size() + NumSubOps;
866     while (InstOps.size() < FinalNumOps) {
867       const TreePatternNode *Child = N->getChild(ChildNo);
868       unsigned BeforeAddingNumOps = InstOps.size();
869       EmitResultOperand(Child, InstOps);
870       assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
871 
872       // If the operand is an instruction and it produced multiple results, just
873       // take the first one.
874       if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
875         InstOps.resize(BeforeAddingNumOps+1);
876 
877       ++ChildNo;
878     }
879   }
880 
881   // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
882   // expand suboperands, use default operands, or other features determined from
883   // the CodeGenInstruction after the fixed operands, which were handled
884   // above. Emit the remaining instructions implicitly added by the use for
885   // variable_ops.
886   if (II.Operands.isVariadic) {
887     for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
888       EmitResultOperand(N->getChild(I), InstOps);
889   }
890 
891   // If this node has input glue or explicitly specified input physregs, we
892   // need to add chained and glued copyfromreg nodes and materialize the glue
893   // input.
894   if (isRoot && !PhysRegInputs.empty()) {
895     // Emit all of the CopyToReg nodes for the input physical registers.  These
896     // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
897     for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) {
898       const CodeGenRegister *Reg =
899         CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first);
900       AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
901                                           Reg));
902     }
903 
904     // Even if the node has no other glue inputs, the resultant node must be
905     // glued to the CopyFromReg nodes we just generated.
906     TreeHasInGlue = true;
907   }
908 
909   // Result order: node results, chain, glue
910 
911   // Determine the result types.
912   SmallVector<MVT::SimpleValueType, 4> ResultVTs;
913   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
914     ResultVTs.push_back(N->getSimpleType(i));
915 
916   // If this is the root instruction of a pattern that has physical registers in
917   // its result pattern, add output VTs for them.  For example, X86 has:
918   //   (set AL, (mul ...))
919   // This also handles implicit results like:
920   //   (implicit EFLAGS)
921   if (isRoot && !Pattern.getDstRegs().empty()) {
922     // If the root came from an implicit def in the instruction handling stuff,
923     // don't re-add it.
924     Record *HandledReg = nullptr;
925     if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
926       HandledReg = II.ImplicitDefs[0];
927 
928     for (Record *Reg : Pattern.getDstRegs()) {
929       if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
930       ResultVTs.push_back(getRegisterValueType(Reg, CGT));
931     }
932   }
933 
934   // If this is the root of the pattern and the pattern we're matching includes
935   // a node that is variadic, mark the generated node as variadic so that it
936   // gets the excess operands from the input DAG.
937   int NumFixedArityOperands = -1;
938   if (isRoot &&
939       Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
940     NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
941 
942   // If this is the root node and multiple matched nodes in the input pattern
943   // have MemRefs in them, have the interpreter collect them and plop them onto
944   // this node. If there is just one node with MemRefs, leave them on that node
945   // even if it is not the root.
946   //
947   // FIXME3: This is actively incorrect for result patterns with multiple
948   // memory-referencing instructions.
949   bool PatternHasMemOperands =
950     Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
951 
952   bool NodeHasMemRefs = false;
953   if (PatternHasMemOperands) {
954     unsigned NumNodesThatLoadOrStore =
955       numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
956     bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
957                                    NumNodesThatLoadOrStore == 1;
958     NodeHasMemRefs =
959       NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
960                                              NumNodesThatLoadOrStore != 1));
961   }
962 
963   // Determine whether we need to attach a chain to this node.
964   bool NodeHasChain = false;
965   if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) {
966     // For some instructions, we were able to infer from the pattern whether
967     // they should have a chain.  Otherwise, attach the chain to the root.
968     //
969     // FIXME2: This is extremely dubious for several reasons, not the least of
970     // which it gives special status to instructions with patterns that Pat<>
971     // nodes can't duplicate.
972     if (II.hasChain_Inferred)
973       NodeHasChain = II.hasChain;
974     else
975       NodeHasChain = isRoot;
976     // Instructions which load and store from memory should have a chain,
977     // regardless of whether they happen to have a pattern saying so.
978     if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
979         II.hasSideEffects)
980       NodeHasChain = true;
981   }
982 
983   assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
984          "Node has no result");
985 
986   AddMatcher(new EmitNodeMatcher(II.Namespace.str()+"::"+II.TheDef->getName().str(),
987                                  ResultVTs, InstOps,
988                                  NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
989                                  NodeHasMemRefs, NumFixedArityOperands,
990                                  NextRecordedOperandNo));
991 
992   // The non-chain and non-glue results of the newly emitted node get recorded.
993   for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
994     if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
995     OutputOps.push_back(NextRecordedOperandNo++);
996   }
997 }
998 
999 void MatcherGen::
1000 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
1001                                SmallVectorImpl<unsigned> &ResultOps) {
1002   assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
1003 
1004   // Emit the operand.
1005   SmallVector<unsigned, 8> InputOps;
1006 
1007   // FIXME2: Could easily generalize this to support multiple inputs and outputs
1008   // to the SDNodeXForm.  For now we just support one input and one output like
1009   // the old instruction selector.
1010   assert(N->getNumChildren() == 1);
1011   EmitResultOperand(N->getChild(0), InputOps);
1012 
1013   // The input currently must have produced exactly one result.
1014   assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
1015 
1016   AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
1017   ResultOps.push_back(NextRecordedOperandNo++);
1018 }
1019 
1020 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
1021                                    SmallVectorImpl<unsigned> &ResultOps) {
1022   // This is something selected from the pattern we matched.
1023   if (!N->getName().empty())
1024     return EmitResultOfNamedOperand(N, ResultOps);
1025 
1026   if (N->isLeaf())
1027     return EmitResultLeafAsOperand(N, ResultOps);
1028 
1029   Record *OpRec = N->getOperator();
1030   if (OpRec->isSubClassOf("Instruction"))
1031     return EmitResultInstructionAsOperand(N, ResultOps);
1032   if (OpRec->isSubClassOf("SDNodeXForm"))
1033     return EmitResultSDNodeXFormAsOperand(N, ResultOps);
1034   errs() << "Unknown result node to emit code for: " << *N << '\n';
1035   PrintFatalError("Unknown node in result pattern!");
1036 }
1037 
1038 void MatcherGen::EmitResultCode() {
1039   // Patterns that match nodes with (potentially multiple) chain inputs have to
1040   // merge them together into a token factor.  This informs the generated code
1041   // what all the chained nodes are.
1042   if (!MatchedChainNodes.empty())
1043     AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
1044 
1045   // Codegen the root of the result pattern, capturing the resulting values.
1046   SmallVector<unsigned, 8> Ops;
1047   EmitResultOperand(Pattern.getDstPattern(), Ops);
1048 
1049   // At this point, we have however many values the result pattern produces.
1050   // However, the input pattern might not need all of these.  If there are
1051   // excess values at the end (such as implicit defs of condition codes etc)
1052   // just lop them off.  This doesn't need to worry about glue or chains, just
1053   // explicit results.
1054   //
1055   unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
1056 
1057   // If the pattern also has (implicit) results, count them as well.
1058   if (!Pattern.getDstRegs().empty()) {
1059     // If the root came from an implicit def in the instruction handling stuff,
1060     // don't re-add it.
1061     Record *HandledReg = nullptr;
1062     const TreePatternNode *DstPat = Pattern.getDstPattern();
1063     if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
1064       const CodeGenTarget &CGT = CGP.getTargetInfo();
1065       CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
1066 
1067       if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
1068         HandledReg = II.ImplicitDefs[0];
1069     }
1070 
1071     for (Record *Reg : Pattern.getDstRegs()) {
1072       if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
1073       ++NumSrcResults;
1074     }
1075   }
1076 
1077   SmallVector<unsigned, 8> Results(Ops);
1078 
1079   // Apply result permutation.
1080   for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults();
1081        ++ResNo) {
1082     Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)];
1083   }
1084 
1085   Results.resize(NumSrcResults);
1086   AddMatcher(new CompleteMatchMatcher(Results, Pattern));
1087 }
1088 
1089 
1090 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
1091 /// the specified variant.  If the variant number is invalid, this returns null.
1092 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
1093                                        unsigned Variant,
1094                                        const CodeGenDAGPatterns &CGP) {
1095   MatcherGen Gen(Pattern, CGP);
1096 
1097   // Generate the code for the matcher.
1098   if (Gen.EmitMatcherCode(Variant))
1099     return nullptr;
1100 
1101   // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
1102   // FIXME2: Split result code out to another table, and make the matcher end
1103   // with an "Emit <index>" command.  This allows result generation stuff to be
1104   // shared and factored?
1105 
1106   // If the match succeeds, then we generate Pattern.
1107   Gen.EmitResultCode();
1108 
1109   // Unconditional match.
1110   return Gen.GetMatcher();
1111 }
1112