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