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