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