major surgery on tblgen: generalize TreePatternNode
[oota-llvm.git] / utils / TableGen / DAGISelMatcherGen.cpp
index 693c4ccf8d3cbc4f274f2ad1a1e6f04d39cd8ff2..da6f6afd82dd88f1bbb03c67f3d2257f622c1be1 100644 (file)
@@ -36,12 +36,9 @@ static MVT::SimpleValueType getRegisterValueType(Record *R,
       VT = RC.getValueTypeNum(0);
       continue;
     }
-    
-    // In multiple RC's.  If the Types of the RC's do not agree, return
-    // MVT::Other. The target is responsible for handling this.
-    if (VT != RC.getValueTypeNum(0))
-      // FIXME2: when does this happen?  Abort?
-      return MVT::Other;
+
+    // If this occurs in multiple register classes, they all have to agree.
+    assert(VT == RC.getValueTypeNum(0));
   }
   return VT;
 }
@@ -70,22 +67,30 @@ namespace {
     /// MatchedChainNodes - This maintains the position in the recorded nodes
     /// array of all of the recorded input nodes that have chains.
     SmallVector<unsigned, 2> MatchedChainNodes;
+
+    /// MatchedFlagResultNodes - This maintains the position in the recorded
+    /// nodes array of all of the recorded input nodes that have flag results.
+    SmallVector<unsigned, 2> MatchedFlagResultNodes;
+    
+    /// MatchedComplexPatterns - This maintains a list of all of the
+    /// ComplexPatterns that we need to check.  The patterns are known to have
+    /// names which were recorded.  The second element of each pair is the first
+    /// slot number that the OPC_CheckComplexPat opcode drops the matched
+    /// results into.
+    SmallVector<std::pair<const TreePatternNode*,
+                          unsigned>, 2> MatchedComplexPatterns;
     
     /// PhysRegInputs - List list has an entry for each explicitly specified
     /// physreg input to the pattern.  The first elt is the Register node, the
     /// second is the recorded slot number the input pattern match saved it in.
     SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
     
-    /// EmittedMergeInputChains - For nodes that match patterns involving
-    /// chains, is set to true if we emitted the "MergeInputChains" operation.
-    bool EmittedMergeInputChains;
-    
     /// Matcher - This is the top level of the generated matcher, the result.
-    MatcherNode *Matcher;
+    Matcher *TheMatcher;
     
     /// CurPredicate - As we emit matcher nodes, this points to the latest check
     /// which should have future checks stuck into its Next position.
-    MatcherNode *CurPredicate;
+    Matcher *CurPredicate;
   public:
     MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
     
@@ -93,13 +98,13 @@ namespace {
       delete PatWithNoTypes;
     }
     
-    void EmitMatcherCode();
+    bool EmitMatcherCode(unsigned Variant);
     void EmitResultCode();
     
-    MatcherNode *GetMatcher() const { return Matcher; }
-    MatcherNode *GetCurPredicate() const { return CurPredicate; }
+    Matcher *GetMatcher() const { return TheMatcher; }
+    Matcher *GetCurPredicate() const { return CurPredicate; }
   private:
-    void AddMatcherNode(MatcherNode *NewNode);
+    void AddMatcher(Matcher *NewNode);
     void InferPossibleTypes();
     
     // Matcher Generation.
@@ -137,7 +142,7 @@ namespace {
 MatcherGen::MatcherGen(const PatternToMatch &pattern,
                        const CodeGenDAGPatterns &cgp)
 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
-  EmittedMergeInputChains(false), Matcher(0), CurPredicate(0) {
+  TheMatcher(0), CurPredicate(0) {
   // We need to produce the matcher tree for the patterns source pattern.  To do
   // this we need to match the structure as well as the types.  To do the type
   // matching, we want to figure out the fewest number of type checks we need to
@@ -178,12 +183,12 @@ void MatcherGen::InferPossibleTypes() {
 }
 
 
-/// AddMatcherNode - Add a matcher node to the current graph we're building. 
-void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
+/// AddMatcher - Add a matcher node to the current graph we're building. 
+void MatcherGen::AddMatcher(Matcher *NewNode) {
   if (CurPredicate != 0)
     CurPredicate->setNext(NewNode);
   else
-    Matcher = NewNode;
+    TheMatcher = NewNode;
   CurPredicate = NewNode;
 }
 
@@ -196,13 +201,18 @@ void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
   assert(N->isLeaf() && "Not a leaf?");
   
-  // If there are node predicates for this node, generate their checks.
-  for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
-    AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
-  
   // Direct match against an integer constant.
-  if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
-    return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
+  if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
+    // If this is the root of the dag we're matching, we emit a redundant opcode
+    // check to ensure that this gets folded into the normal top-level
+    // OpcodeSwitch.
+    if (N == Pattern.getSrcPattern()) {
+      const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
+      AddMatcher(new CheckOpcodeMatcher(NI));
+    }
+
+    return AddMatcher(new CheckIntegerMatcher(II->getValue()));
+  }
   
   DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
   if (DI == 0) {
@@ -221,16 +231,17 @@ void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
   // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
   // record the register 
   if (LeafRec->isSubClassOf("Register")) {
-    AddMatcherNode(new RecordMatcherNode("physreg input "+LeafRec->getName()));
+    AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
+                                 NextRecordedOperandNo));
     PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
     return;
   }
   
   if (LeafRec->isSubClassOf("ValueType"))
-    return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
+    return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
   
   if (LeafRec->isSubClassOf("CondCode"))
-    return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
+    return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
   
   if (LeafRec->isSubClassOf("ComplexPattern")) {
     // We can't model ComplexPattern uses that don't have their name taken yet.
@@ -239,30 +250,10 @@ void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
       errs() << "We expect complex pattern uses to have names: " << *N << "\n";
       exit(1);
     }
-    
-    // Handle complex pattern.
-    const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
-    AddMatcherNode(new CheckComplexPatMatcherNode(CP));
-    
-    // If the complex pattern has a chain, then we need to keep track of the
-    // fact that we just recorded a chain input.  The chain input will be
-    // matched as the last operand of the predicate if it was successful.
-    if (CP.hasProperty(SDNPHasChain)) {
-      // It is the last operand recorded.
-      assert(NextRecordedOperandNo > 1 &&
-             "Should have recorded input/result chains at least!");
-      MatchedChainNodes.push_back(NextRecordedOperandNo-1);
 
-      // If we need to check chains, do so, see comment for
-      // "NodeHasProperty(SDNPHasChain" below.
-      if (MatchedChainNodes.size() > 1) {
-        // FIXME2: This is broken, we should eliminate this nonsense completely,
-        // but we want to produce the same selections that the old matcher does
-        // for now.
-        unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
-        AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
-      }
-    }
+    // Remember this ComplexPattern so that we can emit it after all the other
+    // structural matches are done.
+    MatchedComplexPatterns.push_back(std::make_pair(N, 0));
     return;
   }
   
@@ -291,56 +282,46 @@ void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
       N->getPredicateFns().empty()) {
     if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
       if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
+        // If this is at the root of the pattern, we emit a redundant
+        // CheckOpcode so that the following checks get factored properly under
+        // a single opcode check.
+        if (N == Pattern.getSrcPattern())
+          AddMatcher(new CheckOpcodeMatcher(CInfo));
+
+        // Emit the CheckAndImm/CheckOrImm node.
         if (N->getOperator()->getName() == "and")
-          AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
+          AddMatcher(new CheckAndImmMatcher(II->getValue()));
         else
-          AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
+          AddMatcher(new CheckOrImmMatcher(II->getValue()));
 
         // Match the LHS of the AND as appropriate.
-        AddMatcherNode(new MoveChildMatcherNode(0));
+        AddMatcher(new MoveChildMatcher(0));
         EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
-        AddMatcherNode(new MoveParentMatcherNode());
+        AddMatcher(new MoveParentMatcher());
         return;
       }
     }
   }
   
   // Check that the current opcode lines up.
-  AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
-  
-  // If there are node predicates for this node, generate their checks.
-  for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
-    AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
-  
+  AddMatcher(new CheckOpcodeMatcher(CInfo));
   
   // If this node has memory references (i.e. is a load or store), tell the
   // interpreter to capture them in the memref array.
   if (N->NodeHasProperty(SDNPMemOperand, CGP))
-    AddMatcherNode(new RecordMemRefMatcherNode());
+    AddMatcher(new RecordMemRefMatcher());
   
   // If this node has a chain, then the chain is operand #0 is the SDNode, and
   // the child numbers of the node are all offset by one.
   unsigned OpNo = 0;
   if (N->NodeHasProperty(SDNPHasChain, CGP)) {
     // Record the node and remember it in our chained nodes list.
-    AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
-                                         "' chained node"));
+    AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
+                                         "' chained node",
+                                 NextRecordedOperandNo));
     // Remember all of the input chains our pattern will match.
     MatchedChainNodes.push_back(NextRecordedOperandNo++);
     
-    // If this is the second (e.g. indbr(load) or store(add(load))) or third
-    // input chain (e.g. (store (add (load, load))) from msp430) we need to make
-    // sure that folding the chain won't induce cycles in the DAG.  This could
-    // happen if there were an intermediate node between the indbr and load, for
-    // example.
-    if (MatchedChainNodes.size() > 1) {
-      // FIXME2: This is broken, we should eliminate this nonsense completely,
-      // but we want to produce the same selections that the old matcher does
-      // for now.
-      unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
-      AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
-    }
-    
     // Don't look at the input chain when matching the tree pattern to the
     // SDNode.
     OpNo = 1;
@@ -389,22 +370,35 @@ void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
       }
       
       if (NeedCheck)
-        AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
+        AddMatcher(new CheckFoldableChainNodeMatcher());
     }
   }
+
+  // If this node has an output flag and isn't the root, remember it.
+  if (N->NodeHasProperty(SDNPOutFlag, CGP) && 
+      N != Pattern.getSrcPattern()) {
+    // TODO: This redundantly records nodes with both flags and chains.
+    
+    // Record the node and remember it in our chained nodes list.
+    AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
+                                         "' flag output node",
+                                 NextRecordedOperandNo));
+    // Remember all of the nodes with output flags our pattern will match.
+    MatchedFlagResultNodes.push_back(NextRecordedOperandNo++);
+  }
   
   // If this node is known to have an input flag or if it *might* have an input
   // flag, capture it as the flag input of the pattern.
   if (N->NodeHasProperty(SDNPOptInFlag, CGP) ||
       N->NodeHasProperty(SDNPInFlag, CGP))
-    AddMatcherNode(new CaptureFlagInputMatcherNode());
+    AddMatcher(new CaptureFlagInputMatcher());
       
   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
     // Get the code suitable for matching this child.  Move to the child, check
     // it then move back to the parent.
-    AddMatcherNode(new MoveChildMatcherNode(OpNo));
+    AddMatcher(new MoveChildMatcher(OpNo));
     EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
-    AddMatcherNode(new MoveParentMatcherNode());
+    AddMatcher(new MoveParentMatcher());
   }
 }
 
@@ -414,10 +408,13 @@ void MatcherGen::EmitMatchCode(const TreePatternNode *N,
   // If N and NodeNoTypes don't agree on a type, then this is a case where we
   // need to do a type check.  Emit the check, apply the tyep to NodeNoTypes and
   // reinfer any correlated types.
-  if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
-    AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
-    NodeNoTypes->setTypes(N->getExtTypes());
+  bool DoTypeCheck = false;
+  if (NodeNoTypes->getNumTypes() != 0 &&
+      NodeNoTypes->getExtType(0) != N->getExtType(0)) {
+    assert(NodeNoTypes->getNumTypes() == 1 && "FIXME: Handle multiple results");
+    NodeNoTypes->setType(0, N->getExtType(0));
     InferPossibleTypes();
+    DoTypeCheck = true;
   }
   
   // If this node has a name associated with it, capture it in VariableMap. If
@@ -425,32 +422,15 @@ void MatcherGen::EmitMatchCode(const TreePatternNode *N,
   if (!N->getName().empty()) {
     unsigned &VarMapEntry = VariableMap[N->getName()];
     if (VarMapEntry == 0) {
-      VarMapEntry = NextRecordedOperandNo+1;
-      
-      unsigned NumRecorded;
-      
-      // If this is a complex pattern, the match operation for it will
-      // implicitly record all of the outputs of it (which may be more than
-      // one).
-      if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
-        // Record the right number of operands.
-        NumRecorded = CP->getNumOperands();
-        
-        if (CP->hasProperty(SDNPHasChain))
-          ++NumRecorded; // Chained node operand.
-      } else {
-        // If it is a normal named node, we must emit a 'Record' opcode.
-        AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
-        NumRecorded = 1;
-      }
-      NextRecordedOperandNo += NumRecorded;
-      
+      // If it is a named node, we must emit a 'Record' opcode.
+      AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
+      VarMapEntry = ++NextRecordedOperandNo;
     } else {
       // If we get here, this is a second reference to a specific name.  Since
       // we already have checked that the first reference is valid, we don't
       // have to recursively match it, just check that it's the same as the
       // previously named thing.
-      AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
+      AddMatcher(new CheckSameMatcher(VarMapEntry-1));
       return;
     }
   }
@@ -459,17 +439,87 @@ void MatcherGen::EmitMatchCode(const TreePatternNode *N,
     EmitLeafMatchCode(N);
   else
     EmitOperatorMatchCode(N, NodeNoTypes);
+  
+  // If there are node predicates for this node, generate their checks.
+  for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
+    AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
+  
+  if (DoTypeCheck) {
+    assert(N->getNumTypes() == 1);
+    AddMatcher(new CheckTypeMatcher(N->getType(0)));
+  }
 }
 
-void MatcherGen::EmitMatcherCode() {
+/// EmitMatcherCode - Generate the code that matches the predicate of this
+/// pattern for the specified Variant.  If the variant is invalid this returns
+/// true and does not generate code, if it is valid, it returns false.
+bool MatcherGen::EmitMatcherCode(unsigned Variant) {
+  // If the root of the pattern is a ComplexPattern and if it is specified to
+  // match some number of root opcodes, these are considered to be our variants.
+  // Depending on which variant we're generating code for, emit the root opcode
+  // check.
+  if (const ComplexPattern *CP =
+                   Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
+    const std::vector<Record*> &OpNodes = CP->getRootNodes();
+    assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
+    if (Variant >= OpNodes.size()) return true;
+    
+    AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
+  } else {
+    if (Variant != 0) return true;
+  }
+    
+  // Emit the matcher for the pattern structure and types.
+  EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
+  
   // If the pattern has a predicate on it (e.g. only enabled when a subtarget
   // feature is around, do the check).
   if (!Pattern.getPredicateCheck().empty())
-    AddMatcherNode(new 
-                 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
+    AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
+  
+  // Now that we've completed the structural type match, emit any ComplexPattern
+  // checks (e.g. addrmode matches).  We emit this after the structural match
+  // because they are generally more expensive to evaluate and more difficult to
+  // factor.
+  for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
+    const TreePatternNode *N = MatchedComplexPatterns[i].first;
+    
+    // Remember where the results of this match get stuck.
+    MatchedComplexPatterns[i].second = NextRecordedOperandNo;
+
+    // Get the slot we recorded the value in from the name on the node.
+    unsigned RecNodeEntry = VariableMap[N->getName()];
+    assert(!N->getName().empty() && RecNodeEntry &&
+           "Complex pattern should have a name and slot");
+    --RecNodeEntry;  // Entries in VariableMap are biased.
+    
+    const ComplexPattern &CP =
+      CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
+    
+    // Emit a CheckComplexPat operation, which does the match (aborting if it
+    // fails) and pushes the matched operands onto the recorded nodes list.
+    AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
+                                          N->getName(), NextRecordedOperandNo));
+    
+    // Record the right number of operands.
+    NextRecordedOperandNo += CP.getNumOperands();
+    if (CP.hasProperty(SDNPHasChain)) {
+      // If the complex pattern has a chain, then we need to keep track of the
+      // fact that we just recorded a chain input.  The chain input will be
+      // matched as the last operand of the predicate if it was successful.
+      ++NextRecordedOperandNo; // Chained node operand.
+    
+      // It is the last operand recorded.
+      assert(NextRecordedOperandNo > 1 &&
+             "Should have recorded input/result chains at least!");
+      MatchedChainNodes.push_back(NextRecordedOperandNo-1);
+    }
+    
+    // TODO: Complex patterns can't have output flags, if they did, we'd want
+    // to record them.
+  }
   
-  // Emit the matcher for the pattern structure and types.
-  EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
+  return false;
 }
 
 
@@ -481,23 +531,33 @@ void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
                                           SmallVectorImpl<unsigned> &ResultOps){
   assert(!N->getName().empty() && "Operand not named!");
   
-  unsigned SlotNo = getNamedArgumentSlot(N->getName());
-  
   // A reference to a complex pattern gets all of the results of the complex
   // pattern's match.
   if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
+    unsigned SlotNo = 0;
+    for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
+      if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
+        SlotNo = MatchedComplexPatterns[i].second;
+        break;
+      }
+    assert(SlotNo != 0 && "Didn't get a slot number assigned?");
+    
+    // The first slot entry is the node itself, the subsequent entries are the
+    // matched values.
     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
       ResultOps.push_back(SlotNo+i);
     return;
   }
 
+  unsigned SlotNo = getNamedArgumentSlot(N->getName());
+
   // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
   // version of the immediate so that it doesn't get selected due to some other
   // node use.
   if (!N->isLeaf()) {
     StringRef OperatorName = N->getOperator()->getName();
     if (OperatorName == "imm" || OperatorName == "fpimm") {
-      AddMatcherNode(new EmitConvertToTargetMatcherNode(SlotNo));
+      AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
       ResultOps.push_back(NextRecordedOperandNo++);
       return;
     }
@@ -511,7 +571,7 @@ void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
   assert(N->isLeaf() && "Must be a leaf");
   
   if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
-    AddMatcherNode(new EmitIntegerMatcherNode(II->getValue(),N->getTypeNum(0)));
+    AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
     ResultOps.push_back(NextRecordedOperandNo++);
     return;
   }
@@ -519,14 +579,13 @@ void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
   // If this is an explicit register reference, handle it.
   if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
     if (DI->getDef()->isSubClassOf("Register")) {
-      AddMatcherNode(new EmitRegisterMatcherNode(DI->getDef(),
-                                                 N->getTypeNum(0)));
+      AddMatcher(new EmitRegisterMatcher(DI->getDef(), N->getType(0)));
       ResultOps.push_back(NextRecordedOperandNo++);
       return;
     }
     
     if (DI->getDef()->getName() == "zero_reg") {
-      AddMatcherNode(new EmitRegisterMatcherNode(0, N->getTypeNum(0)));
+      AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
       ResultOps.push_back(NextRecordedOperandNo++);
       return;
     }
@@ -535,7 +594,7 @@ void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
     // in COPY_TO_SUBREG instructions.
     if (DI->getDef()->isSubClassOf("RegisterClass")) {
       std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
-      AddMatcherNode(new EmitStringIntegerMatcherNode(Value, N->getTypeNum(0)));
+      AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
       ResultOps.push_back(NextRecordedOperandNo++);
       return;
     }
@@ -572,7 +631,7 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
                                SmallVectorImpl<unsigned> &OutputOps) {
   Record *Op = N->getOperator();
   const CodeGenTarget &CGT = CGP.getTargetInfo();
-  CodeGenInstruction &II = CGT.getInstruction(Op->getName());
+  CodeGenInstruction &II = CGT.getInstruction(Op);
   const DAGInstruction &Inst = CGP.getInstruction(Op);
   
   // If we can, get the pattern for the instruction we're generating.  We derive
@@ -589,16 +648,16 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
   
   bool isRoot = N == Pattern.getDstPattern();
 
-  // NodeHasOutFlag - True if this node has a flag.
-  bool NodeHasInFlag = false, NodeHasOutFlag = false;
+  // TreeHasOutFlag - True if this tree has a flag.
+  bool TreeHasInFlag = false, TreeHasOutFlag = false;
   if (isRoot) {
     const TreePatternNode *SrcPat = Pattern.getSrcPattern();
-    NodeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
+    TreeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
                     SrcPat->TreeHasProperty(SDNPInFlag, CGP);
   
     // FIXME2: this is checking the entire pattern, not just the node in
     // question, doing this just for the root seems like a total hack.
-    NodeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
+    TreeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
   }
 
   // NumResults - This is the number of results produced by the instruction in
@@ -635,19 +694,6 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
     ++ChildNo;
   }
   
-  // Nodes that match patterns with (potentially multiple) chain inputs have to
-  // merge them together into a token factor.
-  if (NodeHasChain && !EmittedMergeInputChains) {
-    // FIXME2: Move this out of emitresult to a top level place.
-    assert(!MatchedChainNodes.empty() &&
-           "How can this node have chain if no inputs do?");
-    // Otherwise, we have to emit an operation to merge the input chains and
-    // set this as the current input chain.
-    AddMatcherNode(new EmitMergeInputChainsMatcherNode
-                        (MatchedChainNodes.data(), MatchedChainNodes.size()));
-    EmittedMergeInputChains = true;
-  }
-  
   // If this node has an input flag or explicitly specified input physregs, we
   // need to add chained and flagged copyfromreg nodes and materialize the flag
   // input.
@@ -655,23 +701,23 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
     // Emit all of the CopyToReg nodes for the input physical registers.  These
     // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
     for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
-      AddMatcherNode(new EmitCopyToRegMatcherNode(PhysRegInputs[i].second,
-                                                  PhysRegInputs[i].first));
+      AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
+                                          PhysRegInputs[i].first));
     // Even if the node has no other flag inputs, the resultant node must be
     // flagged to the CopyFromReg nodes we just generated.
-    NodeHasInFlag = true;
+    TreeHasInFlag = true;
   }
   
   // Result order: node results, chain, flags
   
   // Determine the result types.
   SmallVector<MVT::SimpleValueType, 4> ResultVTs;
-  if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
+  if (N->getNumTypes()) {
     // FIXME2: If the node has multiple results, we should add them.  For now,
     // preserve existing behavior?!
-    ResultVTs.push_back(N->getTypeNum(0));
+    assert(N->getNumTypes() == 1);
+    ResultVTs.push_back(N->getType(0));
   }
-
   
   // If this is the root instruction of a pattern that has physical registers in
   // its result pattern, add output VTs for them.  For example, X86 has:
@@ -679,20 +725,26 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
   // This also handles implicit results like:
   //   (implicit EFLAGS)
   if (isRoot && Pattern.getDstRegs().size() != 0) {
-    for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i)
-      if (Pattern.getDstRegs()[i]->isSubClassOf("Register"))
-        ResultVTs.push_back(getRegisterValueType(Pattern.getDstRegs()[i], CGT));
+    // If the root came from an implicit def in the instruction handling stuff,
+    // don't re-add it.
+    Record *HandledReg = 0;
+    if (NumResults == 0 && N->getNumTypes() != 0 &&
+        !II.ImplicitDefs.empty())
+      HandledReg = II.ImplicitDefs[0];
+    
+    for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
+      Record *Reg = Pattern.getDstRegs()[i];
+      if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
+      ResultVTs.push_back(getRegisterValueType(Reg, CGT));
+    }
   }
-  if (NodeHasChain)
-    ResultVTs.push_back(MVT::Other);
-  if (NodeHasOutFlag)
-    ResultVTs.push_back(MVT::Flag);
-
-  // FIXME2: Instead of using the isVariadic flag on the instruction, we should
-  // have an SDNP that indicates variadicism.  The TargetInstrInfo isVariadic
-  // property should be inferred from this when an instruction has a pattern.
+
+  // If this is the root of the pattern and the pattern we're matching includes
+  // a node that is variadic, mark the generated node as variadic so that it
+  // gets the excess operands from the input DAG.
   int NumFixedArityOperands = -1;
-  if (isRoot && II.isVariadic)
+  if (isRoot &&
+      (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
     NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
   
   // If this is the root node and any of the nodes matched nodes in the input
@@ -711,23 +763,18 @@ EmitResultInstructionAsOperand(const TreePatternNode *N,
   bool NodeHasMemRefs =
     isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
 
-  // FIXME: Eventually add a SelectNodeTo form.  It works if the new node has a
-  // superset of the results of the old node, in the same places.  E.g. turning
-  // (add (load)) -> add32rm is ok because result #0 is the result and result #1
-  // is new.
-  AddMatcherNode(new EmitNodeMatcherNode(II.Namespace+"::"+II.TheDef->getName(),
-                                         ResultVTs.data(), ResultVTs.size(),
-                                         InstOps.data(), InstOps.size(),
-                                         NodeHasChain, NodeHasInFlag,
-                                         NodeHasMemRefs,NumFixedArityOperands));
-  
-  // The newly emitted node gets recorded.
-  // FIXME2: This should record all of the results except the (implicit) one.
-  OutputOps.push_back(NextRecordedOperandNo++);
-  
-  
-  // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
-  // variants.  Call MorphNodeTo instead of SelectNodeTo.
+  AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
+                                 ResultVTs.data(), ResultVTs.size(),
+                                 InstOps.data(), InstOps.size(),
+                                 NodeHasChain, TreeHasInFlag, TreeHasOutFlag,
+                                 NodeHasMemRefs, NumFixedArityOperands,
+                                 NextRecordedOperandNo));
+  
+  // The non-chain and non-flag results of the newly emitted node get recorded.
+  for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
+    if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break;
+    OutputOps.push_back(NextRecordedOperandNo++);
+  }
 }
 
 void MatcherGen::
@@ -747,7 +794,7 @@ EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
   // The input currently must have produced exactly one result.
   assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
 
-  AddMatcherNode(new EmitNodeXFormMatcherNode(InputOps[0], N->getOperator()));
+  AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
   ResultOps.push_back(NextRecordedOperandNo++);
 }
 
@@ -770,27 +817,67 @@ void MatcherGen::EmitResultOperand(const TreePatternNode *N,
 }
 
 void MatcherGen::EmitResultCode() {
+  // Patterns that match nodes with (potentially multiple) chain inputs have to
+  // merge them together into a token factor.  This informs the generated code
+  // what all the chained nodes are.
+  if (!MatchedChainNodes.empty())
+    AddMatcher(new EmitMergeInputChainsMatcher
+               (MatchedChainNodes.data(), MatchedChainNodes.size()));
+  
+  // Codegen the root of the result pattern, capturing the resulting values.
   SmallVector<unsigned, 8> Ops;
   EmitResultOperand(Pattern.getDstPattern(), Ops);
 
-  // We know that the resulting pattern has exactly one result/
-  // FIXME2: why?  what about something like (set a,b,c, (complexpat))
-  // FIXME2: Implicit results should be pushed here I guess?
-  assert(Ops.size() == 1);
-  // FIXME: Handle Ops.
-  // FIXME: Handle (set EAX, (foo)) but not (implicit EFLAGS)
-  
-  AddMatcherNode(new PatternMarkerMatcherNode(Pattern));
+  // At this point, we have however many values the result pattern produces.
+  // However, the input pattern might not need all of these.  If there are
+  // excess values at the end (such as condition codes etc) just lop them off.
+  // This doesn't need to worry about flags or chains, just explicit results.
+  //
+  // FIXME2: This doesn't work because there is currently no way to get an
+  // accurate count of the # results the source pattern sets.  This is because
+  // of the "parallel" construct in X86 land, which looks like this:
+  //
+  //def : Pat<(parallel (X86and_flag GR8:$src1, GR8:$src2),
+  //           (implicit EFLAGS)),
+  //  (AND8rr GR8:$src1, GR8:$src2)>;
+  //
+  // This idiom means to match the two-result node X86and_flag (which is
+  // declared as returning a single result, because we can't match multi-result
+  // nodes yet).  In this case, we would have to know that the input has two
+  // results.  However, mul8r is modelled exactly the same way, but without
+  // implicit defs included.  The fix is to support multiple results directly
+  // and eliminate 'parallel'.
+  //
+  // FIXME2: When this is fixed, we should revert the terrible hack in the
+  // OPC_EmitNode code in the interpreter.
+#if 0
+  const TreePatternNode *Src = Pattern.getSrcPattern();
+  unsigned NumSrcResults = Src->getTypeNum(0) != MVT::isVoid ? 1 : 0;
+  NumSrcResults += Pattern.getDstRegs().size();
+  assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
+  Ops.resize(NumSrcResults);
+#endif
+
+  // If the matched pattern covers nodes which define a flag result, emit a node
+  // that tells the matcher about them so that it can update their results.
+  if (!MatchedFlagResultNodes.empty())
+    AddMatcher(new MarkFlagResultsMatcher(MatchedFlagResultNodes.data(),
+                                          MatchedFlagResultNodes.size()));
+  
+  AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
 }
 
 
-MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
-                                           const CodeGenDAGPatterns &CGP) {
+/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
+/// the specified variant.  If the variant number is invalid, this returns null.
+Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
+                                       unsigned Variant,
+                                       const CodeGenDAGPatterns &CGP) {
   MatcherGen Gen(Pattern, CGP);
 
   // Generate the code for the matcher.
-  Gen.EmitMatcherCode();
-  
+  if (Gen.EmitMatcherCode(Variant))
+    return 0;
   
   // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
   // FIXME2: Split result code out to another table, and make the matcher end