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