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