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