Now support instructions with implicit write to non-flag registers.
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
index 285c10f0f5db43f19cdfbe2f04e9cdafd236adbb..3b0d4eac1223bab1e456c9b08f823b55b76aff49 100644 (file)
@@ -296,6 +296,7 @@ bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
 
   if (isLeaf()) {
     dump();
+    std::cerr << " ";
     TP.error("Type inference contradiction found in node!");
   } else {
     TP.error("Type inference contradiction found in node " + 
@@ -485,7 +486,7 @@ static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
     return MVT::Other;
   } else if (R->isSubClassOf("ComplexPattern")) {
     return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
-  } else if (R->getName() == "node") {
+  } else if (R->getName() == "node" || R->getName() == "srcvalue") {
     // Placeholder.
     return MVT::isUnknown;
   }
@@ -951,14 +952,17 @@ void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
 /// instruction input.  Return true if this is a real use.
 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
-                      std::map<std::string, TreePatternNode*> &InstInputs) {
+                      std::map<std::string, TreePatternNode*> &InstInputs,
+                      std::vector<Record*> &InstImpInputs) {
   // No name -> not interesting.
   if (Pat->getName().empty()) {
     if (Pat->isLeaf()) {
       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
         I->error("Input " + DI->getDef()->getName() + " must be named!");
-
+      else if (DI && DI->getDef()->isSubClassOf("Register")) {
+        InstImpInputs.push_back(DI->getDef());
+      }
     }
     return false;
   }
@@ -973,6 +977,10 @@ static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
     Rec = Pat->getOperator();
   }
 
+  // SRCVALUE nodes are ignored.
+  if (Rec->getName() == "srcvalue")
+    return false;
+
   TreePatternNode *&Slot = InstInputs[Pat->getName()];
   if (!Slot) {
     Slot = Pat;
@@ -1000,9 +1008,11 @@ static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
 void DAGISelEmitter::
 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
                             std::map<std::string, TreePatternNode*> &InstInputs,
-                            std::map<std::string, Record*> &InstResults) {
+                            std::map<std::string, Record*> &InstResults,
+                            std::vector<Record*> &InstImpInputs,
+                            std::vector<Record*> &InstImpResults) {
   if (Pat->isLeaf()) {
-    bool isUse = HandleUse(I, Pat, InstInputs);
+    bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
     if (!isUse && Pat->getTransformFn())
       I->error("Cannot specify a transform function for a non-input value!");
     return;
@@ -1012,14 +1022,15 @@ FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
         I->error("Cannot have void nodes inside of patterns!");
-      FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
+      FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
+                                  InstImpInputs, InstImpResults);
     }
     
     // If this is a non-leaf node with no children, treat it basically as if
     // it were a leaf.  This handles nodes like (imm).
     bool isUse = false;
     if (Pat->getNumChildren() == 0)
-      isUse = HandleUse(I, Pat, InstInputs);
+      isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
     
     if (!isUse && Pat->getTransformFn())
       I->error("Cannot specify a transform function for a non-input value!");
@@ -1040,23 +1051,27 @@ FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
   for (unsigned i = 0; i != NumValues; ++i) {
     TreePatternNode *Dest = Pat->getChild(i);
     if (!Dest->isLeaf())
-      I->error("set destination should be a virtual register!");
+      I->error("set destination should be a register!");
     
     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
     if (!Val)
-      I->error("set destination should be a virtual register!");
+      I->error("set destination should be a register!");
+
+    if (Val->getDef()->isSubClassOf("RegisterClass")) {
+      if (Dest->getName().empty())
+        I->error("set destination must have a name!");
+      if (InstResults.count(Dest->getName()))
+        I->error("cannot set '" + Dest->getName() +"' multiple times");
+      InstResults[Dest->getName()] = Val->getDef();
+    } else if (Val->getDef()->isSubClassOf("Register")) {
+      InstImpResults.push_back(Val->getDef());
+    } else {
+      I->error("set destination should be a register!");
+    }
     
-    if (!Val->getDef()->isSubClassOf("RegisterClass"))
-      I->error("set destination should be a virtual register!");
-    if (Dest->getName().empty())
-      I->error("set destination must have a name!");
-    if (InstResults.count(Dest->getName()))
-      I->error("cannot set '" + Dest->getName() +"' multiple times");
-    InstResults[Dest->getName()] = Val->getDef();
-
     // Verify and collect info from the computation.
     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
-                                InstInputs, InstResults);
+                                InstInputs, InstResults, InstImpInputs, InstImpResults);
   }
 }
 
@@ -1130,8 +1145,11 @@ void DAGISelEmitter::ParseInstructions() {
       }
       
       // Create and insert the instruction.
+      std::vector<Record*> ImpResults;
+      std::vector<Record*> ImpOperands;
       Instructions.insert(std::make_pair(Instrs[i], 
-                            DAGInstruction(0, Results, Operands)));
+                          DAGInstruction(0, Results, Operands,
+                                         ImpResults, ImpOperands)));
       continue;  // no pattern.
     }
     
@@ -1152,6 +1170,9 @@ void DAGISelEmitter::ParseInstructions() {
     // InstResults - Keep track of all the virtual registers that are 'set'
     // in the instruction, including what reg class they are.
     std::map<std::string, Record*> InstResults;
+
+    std::vector<Record*> InstImpInputs;
+    std::vector<Record*> InstImpResults;
     
     // Verify that the top-level forms in the instruction are of void type, and
     // fill in the InstResults map.
@@ -1162,7 +1183,8 @@ void DAGISelEmitter::ParseInstructions() {
                  " void types");
 
       // Find inputs and outputs, and verify the structure of the uses/defs.
-      FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
+      FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
+                                  InstImpInputs, InstImpResults);
     }
 
     // Now that we have inputs and outputs of the pattern, inspect the operands
@@ -1251,7 +1273,7 @@ void DAGISelEmitter::ParseInstructions() {
       new TreePatternNode(I->getRecord(), ResultNodeOperands);
 
     // Create and insert the instruction.
-    DAGInstruction TheInst(I, Results, Operands);
+    DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
 
     // Use a temporary tree pattern to infer all types and make sure that the
@@ -1279,27 +1301,27 @@ void DAGISelEmitter::ParseInstructions() {
     }
     TreePatternNode *Pattern = I->getTree(0);
     TreePatternNode *SrcPattern;
-    if (TheInst.getNumResults() == 0) {
-      SrcPattern = Pattern;
-    } else {
-      if (Pattern->getOperator()->getName() != "set")
-        continue;  // Not a set (store or something?)
-    
+    if (Pattern->getOperator()->getName() == "set") {
       if (Pattern->getNumChildren() != 2)
         continue;  // Not a set of a single value (not handled so far)
 
       SrcPattern = Pattern->getChild(1)->clone();    
+    } else{
+      // Not a set (store or something?)
+      SrcPattern = Pattern;
     }
     
     std::string Reason;
     if (!SrcPattern->canPatternMatch(Reason, *this))
       I->error("Instruction can never match: " + Reason);
     
+    Record *Instr = II->first;
     TreePatternNode *DstPattern = TheInst.getResultPattern();
-    PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
+    PatternsToMatch.
+      push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
+                               SrcPattern, DstPattern));
 
     if (PatternHasCtrlDep(Pattern, *this)) {
-      Record *Instr = II->first;
       CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
       InstInfo.hasCtrlDep = true;
     }
@@ -1325,8 +1347,11 @@ void DAGISelEmitter::ParsePatterns() {
     {
       std::map<std::string, TreePatternNode*> InstInputs;
       std::map<std::string, Record*> InstResults;
+      std::vector<Record*> InstImpInputs;
+      std::vector<Record*> InstImpResults;
       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
-                                  InstInputs, InstResults);
+                                  InstInputs, InstResults,
+                                  InstImpInputs, InstImpResults);
     }
     
     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
@@ -1351,8 +1376,10 @@ void DAGISelEmitter::ParsePatterns() {
     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
       Pattern->error("Pattern can never match: " + Reason);
     
-    PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
-                                             Result->getOnlyTree()));
+    PatternsToMatch.
+      push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
+                               Pattern->getOnlyTree(),
+                               Result->getOnlyTree()));
   }
 }
 
@@ -1560,7 +1587,7 @@ void DAGISelEmitter::GenerateVariants() {
   //
   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
     std::vector<TreePatternNode*> Variants;
-    GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
+    GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
 
     assert(!Variants.empty() && "Must create at least original variant!");
     Variants.erase(Variants.begin());  // Remove the original pattern.
@@ -1569,7 +1596,7 @@ void DAGISelEmitter::GenerateVariants() {
       continue;
 
     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
-          PatternsToMatch[i].first->dump();
+          PatternsToMatch[i].getSrcPattern()->dump();
           std::cerr << "\n");
 
     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
@@ -1583,7 +1610,7 @@ void DAGISelEmitter::GenerateVariants() {
       bool AlreadyExists = false;
       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
         // Check to see if this variant already exists.
-        if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
+        if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
           AlreadyExists = true;
           break;
@@ -1593,8 +1620,9 @@ void DAGISelEmitter::GenerateVariants() {
       if (AlreadyExists) continue;
 
       // Otherwise, add it to the list of patterns we have.
-      PatternsToMatch.push_back(std::make_pair(Variant, 
-                                               PatternsToMatch[i].second));
+      PatternsToMatch.
+        push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
+                                 Variant, PatternsToMatch[i].getDstPattern()));
     }
 
     DEBUG(std::cerr << "\n");
@@ -1633,7 +1661,8 @@ static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
   assert(isExtIntegerVT(P->getExtType()) || 
          isExtFloatingPointVT(P->getExtType()) ||
-         P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
+         P->getExtType() == MVT::isVoid ||
+         P->getExtType() == MVT::Flag && "Not a valid pattern node to size!");
   unsigned Size = 1;  // The node itself.
 
   // FIXME: This is a hack to statically increase the priority of patterns
@@ -1680,15 +1709,16 @@ struct PatternSortingPredicate {
   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
   DAGISelEmitter &ISE;
 
-  bool operator()(DAGISelEmitter::PatternToMatch *LHS,
-                  DAGISelEmitter::PatternToMatch *RHS) {
-    unsigned LHSSize = getPatternSize(LHS->first, ISE);
-    unsigned RHSSize = getPatternSize(RHS->first, ISE);
+  bool operator()(PatternToMatch *LHS,
+                  PatternToMatch *RHS) {
+    unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
+    unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
     if (LHSSize < RHSSize) return false;
     
     // If the patterns have equal complexity, compare generated instruction cost
-    return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
+    return getResultPatternCost(LHS->getDstPattern()) <
+      getResultPatternCost(RHS->getDstPattern());
   }
 };
 
@@ -1720,30 +1750,55 @@ class PatternCodeEmitter {
 private:
   DAGISelEmitter &ISE;
 
-  // LHS of the pattern being matched
-  TreePatternNode *LHS;
+  // Predicates.
+  ListInit *Predicates;
+  // Instruction selector pattern.
+  TreePatternNode *Pattern;
+  // Matched instruction.
+  TreePatternNode *Instruction;
   unsigned PatternNo;
   std::ostream &OS;
   // Node to name mapping
   std::map<std::string,std::string> VariableMap;
-  // Name of the inner most node which produces a chain.
-  std::string InnerChain;
   // Names of all the folded nodes which produce chains.
-  std::vector<std::string> FoldedChains;
-  bool InFlag;
+  std::vector<std::pair<std::string, unsigned> > FoldedChains;
+  bool FoundChain;
   unsigned TmpNo;
 
 public:
-  PatternCodeEmitter(DAGISelEmitter &ise, TreePatternNode *lhs,
+  PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
+                     TreePatternNode *pattern, TreePatternNode *instr,
                      unsigned PatNum, std::ostream &os) :
-    ISE(ise), LHS(lhs), PatternNo(PatNum), OS(os),
-    InFlag(false), TmpNo(0) {};
+    ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
+    PatternNo(PatNum), OS(os), FoundChain(false), TmpNo(0) {};
 
   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
   /// if the match fails. At this point, we already know that the opcode for N
   /// matches, and the SDNode for the result has the RootName specified name.
   void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
                      bool isRoot = false) {
+
+    // Emit instruction predicates. Each predicate is just a string for now.
+    if (isRoot) {
+      for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
+        if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
+          Record *Def = Pred->getDef();
+          if (Def->isSubClassOf("Predicate")) {
+            if (i == 0)
+              OS << "      if (";
+            else
+              OS << " && ";
+            OS << "(" << Def->getValueAsString("CondString") << ")";
+            if (i == e-1)
+              OS << ") goto P" << PatternNo << "Fail;\n";
+          } else {
+            Def->dump();
+            assert(0 && "Unknown predicate type!");
+          }
+        }
+      }
+    }
+
     if (N->isLeaf()) {
       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
         OS << "      if (cast<ConstantSDNode>(" << RootName
@@ -1776,20 +1831,17 @@ public:
 
     // Emit code to load the child nodes and match their contents recursively.
     unsigned OpNo = 0;
-    if (NodeHasChain(N, ISE)) {
+    bool HasChain = NodeHasChain(N, ISE);
+    if (HasChain) {
       OpNo = 1;
       if (!isRoot) {
+        const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
         OS << "      if (!" << RootName << ".hasOneUse()) goto P"
            << PatternNo << "Fail;   // Multiple uses of actual result?\n";
         OS << "      if (CodeGenMap.count(" << RootName
-           << ".getValue(1))) goto P"
+           << ".getValue(" << CInfo.getNumResults() << "))) goto P"
            << PatternNo << "Fail;   // Already selected for a chain use?\n";
       }
-      if (InnerChain.empty()) {
-        OS << "      SDOperand " << RootName << "0 = " << RootName
-           << ".getOperand(0);\n";
-        InnerChain = RootName + "0";
-      }
     }
 
     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
@@ -1803,8 +1855,10 @@ public:
         OS << "      if (" << RootName << OpNo << ".getOpcode() != "
            << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
         EmitMatchCode(Child, RootName + utostr(OpNo));
-        if (NodeHasChain(Child, ISE))
-          FoldedChains.push_back(RootName + utostr(OpNo));
+        if (NodeHasChain(Child, ISE)) {
+          FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
+                                                CInfo.getNumResults()));
+        }
       } else {
         // If this child has a name associated with it, capture it in VarMap.  If
         // we already saw this in the pattern, emit code to verify dagness.
@@ -1829,12 +1883,10 @@ public:
           if (LeafRec->isSubClassOf("RegisterClass")) {
             // Handle register references.  Nothing to do here.
           } else if (LeafRec->isSubClassOf("Register")) {
-            if (!InFlag) {
-              OS << "      SDOperand InFlag = SDOperand(0,0);\n";
-              InFlag = true;
-            }
           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
             // Handle complex pattern. Nothing to do here.
+          } else if (LeafRec->getName() == "srcvalue") {
+            // Place holder for SRCVALUE nodes. Nothing to do here.
           } else if (LeafRec->isSubClassOf("ValueType")) {
             // Make sure this is the specified value type.
             OS << "      if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
@@ -1861,6 +1913,13 @@ public:
       }
     }
 
+    if (HasChain) {
+      if (!FoundChain) {
+        OS << "      SDOperand Chain = " << RootName << ".getOperand(0);\n";
+        FoundChain = true;
+      }
+    }
+
     // If there is a node predicate for this, emit the call.
     if (!N->getPredicateFn().empty())
       OS << "      if (!" << N->getPredicateFn() << "(" << RootName
@@ -1899,6 +1958,8 @@ public:
            << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
         OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
+      } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
+        OS << "      SDOperand Tmp" << ResNo << " = " << Val << ";\n";
       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
         std::string Fn = CP->getSelectFunc();
         NumRes = CP->getNumOperands();
@@ -1910,7 +1971,7 @@ public:
         OS << ";\n";
         OS << "      if (!" << Fn << "(" << Val;
         for (unsigned i = 0; i < NumRes; i++)
-          OS << " , Tmp" << i + ResNo;
+          OS << ", Tmp" << i + ResNo;
         OS << ")) goto P" << PatternNo << "Fail;\n";
         TmpNo = ResNo + NumRes;
       } else {
@@ -1949,6 +2010,16 @@ public:
 
     Record *Op = N->getOperator();
     if (Op->isSubClassOf("Instruction")) {
+      const DAGInstruction &Inst = ISE.getInstruction(Op);
+      unsigned NumImpResults  = Inst.getNumImpResults();
+      unsigned NumImpOperands = Inst.getNumImpOperands();
+      bool InFlag  = NumImpOperands > 0;
+      bool OutFlag = NumImpResults > 0;
+      bool IsCopyFromReg = false;
+
+      if (InFlag || OutFlag)
+        OS << "      SDOperand InFlag = SDOperand(0,0);\n";
+
       // Determine operand emission order. Complex pattern first.
       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
@@ -1980,21 +2051,25 @@ public:
           Ops.push_back(NumTemps[i].second + j);
       }
 
-      CodeGenInstruction &II =
-        ISE.getTargetInfo().getInstruction(Op->getName());
+      const CodeGenTarget &CGT = ISE.getTargetInfo();
+      CodeGenInstruction &II = CGT.getInstruction(Op->getName());
 
       // Emit all the chain and CopyToReg stuff.
       if (II.hasCtrlDep)
-        OS << "      SDOperand Chain = Select(" << InnerChain << ");\n";
-      EmitCopyToRegs(LHS, "N", II.hasCtrlDep);
+        OS << "      Chain = Select(Chain);\n";
+      if (InFlag)
+        EmitCopyToRegs(Pattern, "N", II.hasCtrlDep);
 
-      const DAGInstruction &Inst = ISE.getInstruction(Op);
       unsigned NumResults = Inst.getNumResults();    
       unsigned ResNo = TmpNo++;
       if (!isRoot) {
         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
-           << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
-           << getEnumName(N->getType());
+           << II.Namespace << "::" << II.TheDef->getName();
+        if (N->getType() != MVT::isVoid)
+          OS << ", MVT::" << getEnumName(N->getType());
+        if (OutFlag)
+          OS << ", MVT::Flag";
+
         unsigned LastOp = 0;
         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
           LastOp = Ops[i];
@@ -2006,39 +2081,84 @@ public:
           OS << "      Chain = Tmp" << LastOp << ".getValue("
              << NumResults << ");\n";
         }
-      } else if (II.hasCtrlDep) {
-        OS << "      SDOperand Result = ";
-        OS << "CurDAG->getTargetNode("
+      } else if (II.hasCtrlDep || OutFlag) {
+        OS << "      SDOperand Result = CurDAG->getTargetNode("
            << II.Namespace << "::" << II.TheDef->getName();
-        if (NumResults > 0) 
-          OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
-        OS << ", MVT::Other";
+
+        // Output order: results, chain, flags
+        // Result types.
+        if (NumResults > 0) { 
+          // TODO: multiple results?
+          if (N->getType() != MVT::isVoid)
+            OS << ", MVT::" << getEnumName(N->getType());
+        }
+        if (II.hasCtrlDep)
+          OS << ", MVT::Other";
+        if (OutFlag)
+          OS << ", MVT::Flag";
+
+        // Inputs.
         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
           OS << ", Tmp" << Ops[i];
-        OS << ", Chain";
-        if (InFlag)
-          OS << ", InFlag";
+        if (II.hasCtrlDep) OS << ", Chain";
+        if (InFlag)        OS << ", InFlag";
         OS << ");\n";
-        if (NumResults != 0) {
-          OS << "      CodeGenMap[N] = Result;\n";
+
+        unsigned ValNo = 0;
+        for (unsigned i = 0; i < NumResults; i++) {
+          OS << "      CodeGenMap[N.getValue(" << ValNo << ")] = Result"
+             << ".getValue(" << ValNo << ");\n";
+          ValNo++;
+        }
+
+        if (II.hasCtrlDep) {
+          OS << "      Chain = Result.getValue(" << ValNo << ");\n";
+          if (OutFlag)
+            OS << "      InFlag = Result.getValue(" << ValNo+1 << ");\n";
+        } else if (OutFlag) 
+            OS << "      InFlag = Result.getValue(" << ValNo << ");\n";
+
+        if (OutFlag)
+          IsCopyFromReg = EmitCopyFromRegs(N, II.hasCtrlDep);
+        if (IsCopyFromReg)
+          OS << "      CodeGenMap[N.getValue(" << ValNo++ << ")] = Result;\n";
+
+        if (OutFlag)
+          OS << "      CodeGenMap[N.getValue(" << ValNo++ << ")] = InFlag;\n";
+
+        if (IsCopyFromReg || II.hasCtrlDep) {
+          OS << "      ";
+          if (IsCopyFromReg || NodeHasChain(Pattern, ISE))
+            OS << "CodeGenMap[N.getValue(" << ValNo   << ")] = ";
+          for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
+            OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
+               << FoldedChains[j].second << ")] = ";
+          OS << "Chain;\n";
+        }
+
+        // FIXME: this only works because (for now) an instruction can either
+        // produce a single result or a single flag.
+        if (II.hasCtrlDep && OutFlag) {
+          if (IsCopyFromReg)
+            OS << "      return (N.ResNo == 0) ? Result : "
+               << "((N.ResNo == 2) ? Chain : InFlag);"
+               << "   // Chain comes before flag.\n";
+          else
+            OS << "      return (N.ResNo) ? Chain : InFlag;"
+               << "   // Chain comes before flag.\n";
+        } else {
+          OS << "      return Result.getValue(N.ResNo);\n";
         }
-        OS << "      Chain ";
-        if (NodeHasChain(LHS, ISE))
-          OS << "= CodeGenMap[N.getValue(1)] ";
-        for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
-          OS << "= CodeGenMap[" << FoldedChains[j] << ".getValue(1)] ";
-        OS << "= Result.getValue(1);\n";
-        if (NumResults == 0)
-          OS << "      return Chain;\n";
-        else
-          OS << "      return (N.ResNo) ? Chain : Result.getValue(0);\n";
       } else {
         // If this instruction is the root, and if there is only one use of it,
         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
         OS << "      if (N.Val->hasOneUse()) {\n";
         OS << "        return CurDAG->SelectNodeTo(N.Val, "
-           << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
-           << getEnumName(N->getType());
+           << II.Namespace << "::" << II.TheDef->getName();
+        if (N->getType() != MVT::isVoid)
+          OS << ", MVT::" << getEnumName(N->getType());
+        if (OutFlag)
+          OS << ", MVT::Flag";
         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
           OS << ", Tmp" << Ops[i];
         if (InFlag)
@@ -2046,8 +2166,11 @@ public:
         OS << ");\n";
         OS << "      } else {\n";
         OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
-           << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
-           << getEnumName(N->getType());
+           << II.Namespace << "::" << II.TheDef->getName();
+        if (N->getType() != MVT::isVoid)
+          OS << ", MVT::" << getEnumName(N->getType());
+        if (OutFlag)
+          OS << ", MVT::Flag";
         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
           OS << ", Tmp" << Ops[i];
         if (InFlag)
@@ -2055,12 +2178,11 @@ public:
         OS << ");\n";
         OS << "      }\n";
       }
+
       return std::make_pair(1, ResNo);
     } else if (Op->isSubClassOf("SDNodeXForm")) {
       assert(N->getNumChildren() == 1 && "node xform should have one child!");
-      unsigned OpVal = EmitResultCode(N->getChild(0))
-        .second;
-    
+      unsigned OpVal = EmitResultCode(N->getChild(0)).second;
       unsigned ResNo = TmpNo++;
       OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
          << "(Tmp" << OpVal << ".Val);\n";
@@ -2089,11 +2211,6 @@ public:
       OS << "      if (" << Prefix << ".Val->getValueType(0) != MVT::"
          << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
       return true;
-    } else if (Pat->isLeaf()) {
-      if (NodeIsComplexPattern(Pat))
-        OS << "      if (" << Prefix << ".Val->getValueType(0) != MVT::"
-           << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
-      return false;
     }
   
     unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
@@ -2120,7 +2237,9 @@ private:
           Record *RR = DI->getDef();
           if (RR->isSubClassOf("Register")) {
             MVT::ValueType RVT = getRegisterValueType(RR, T);
-            if (HasCtrlDep) {
+            if (RVT == MVT::Flag) {
+              OS << "      InFlag = Select(" << RootName << OpNo << ");\n";
+            } else if (HasCtrlDep) {
               OS << "      SDOperand " << RootName << "CR" << i << ";\n";
               OS << "      " << RootName << "CR" << i
                  << "  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
@@ -2143,6 +2262,43 @@ private:
       }
     }
   }
+
+  /// EmitCopyFromRegs - Emit code to copy result to physical registers
+  /// as specified by the instruction.
+  bool EmitCopyFromRegs(TreePatternNode *N, bool HasCtrlDep) {
+    bool RetVal = false;
+    Record *Op = N->getOperator();
+    if (Op->isSubClassOf("Instruction")) {
+      const DAGInstruction &Inst = ISE.getInstruction(Op);
+      const CodeGenTarget &CGT = ISE.getTargetInfo();
+      CodeGenInstruction &II = CGT.getInstruction(Op->getName());
+      unsigned NumImpResults  = Inst.getNumImpResults();
+      for (unsigned i = 0; i < NumImpResults; i++) {
+        Record *RR = Inst.getImpResult(i);
+        if (RR->isSubClassOf("Register")) {
+          MVT::ValueType RVT = getRegisterValueType(RR, CGT);
+          if (RVT != MVT::Flag) {
+            if (HasCtrlDep) {
+              OS << "      Result = CurDAG->getCopyFromReg(Chain, "
+                 << ISE.getQualifiedName(RR)
+                 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
+              OS << "      Chain  = Result.getValue(1);\n";
+              OS << "      InFlag = Result.getValue(2);\n";
+            } else {
+              OS << "      SDOperand Chain;\n";
+              OS << "      Result = CurDAG->getCopyFromReg("
+                 << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
+                 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
+              OS << "      Chain  = Result.getValue(1);\n";
+              OS << "      InFlag = Result.getValue(2);\n";
+            }
+            RetVal = true;
+          }
+        }
+      }
+    }
+    return RetVal;
+  }
 };
 
 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
@@ -2153,17 +2309,21 @@ void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
   static unsigned PatternCount = 0;
   unsigned PatternNo = PatternCount++;
   OS << "    { // Pattern #" << PatternNo << ": ";
-  Pattern.first->print(OS);
+  Pattern.getSrcPattern()->print(OS);
   OS << "\n      // Emits: ";
-  Pattern.second->print(OS);
+  Pattern.getDstPattern()->print(OS);
   OS << "\n";
-  OS << "      // Pattern complexity = " << getPatternSize(Pattern.first, *this)
-     << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
+  OS << "      // Pattern complexity = "
+     << getPatternSize(Pattern.getSrcPattern(), *this)
+     << "  cost = "
+     << getResultPatternCost(Pattern.getDstPattern()) << "\n";
 
-  PatternCodeEmitter Emitter(*this, Pattern.first, PatternNo, OS);
+  PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
+                             Pattern.getSrcPattern(), Pattern.getDstPattern(),
+                             PatternNo, OS);
 
   // Emit the matcher, capturing named arguments in VariableMap.
-  Emitter.EmitMatchCode(Pattern.first, "N", true /*the root*/);
+  Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", true /*the root*/);
 
   // TP - Get *SOME* tree pattern, we don't care which.
   TreePattern &TP = *PatternFragments.begin()->second;
@@ -2180,7 +2340,7 @@ void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
   // apply the type to the tree, then rerun type inference.  Iterate until all
   // types are resolved.
   //
-  TreePatternNode *Pat = Pattern.first->clone();
+  TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
   RemoveAllTypes(Pat);
   
   do {
@@ -2198,9 +2358,9 @@ void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
     // Insert a check for an unresolved type and add it to the tree.  If we find
     // an unresolved type to add a check for, this returns true and we iterate,
     // otherwise we are done.
-  } while (Emitter.InsertOneTypeCheck(Pat, Pattern.first, "N"));
+  } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
 
-  Emitter.EmitResultCode(Pattern.second, true /*the root*/);
+  Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
 
   delete Pat;
   
@@ -2232,13 +2392,12 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
      << "INSTRUCTION_LIST_END))\n"
      << "    return N;   // Already selected.\n\n"
-     << "  if (!N.Val->hasOneUse()) {\n"
-  << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
-     << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
-     << "  }\n"
+    << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
+     << "  if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
      << "  switch (N.getOpcode()) {\n"
      << "  default: break;\n"
      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
+     << "  case ISD::BasicBlock:\n"
      << "    return N;\n"
      << "  case ISD::AssertSext:\n"
      << "  case ISD::AssertZext: {\n"
@@ -2261,26 +2420,53 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
      << "    }\n"
      << "  case ISD::CopyFromReg: {\n"
      << "    SDOperand Chain = Select(N.getOperand(0));\n"
-     << "    if (Chain == N.getOperand(0)) return N; // No change\n"
-     << "    SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
-     << "                    cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
-     << "                                         N.Val->getValueType(0));\n"
-     << "    return New.getValue(N.ResNo);\n"
+     << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
+     << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
+     << "    if (N.Val->getNumValues() == 2) {\n"
+     << "      if (Chain == N.getOperand(0)) return N; // No change\n"
+     << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
+     << "      CodeGenMap[N.getValue(0)] = New;\n"
+     << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
+     << "      return New.getValue(N.ResNo);\n"
+     << "    } else {\n"
+     << "      SDOperand Flag;\n"
+     << "      if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
+     << "      if (Chain == N.getOperand(0) &&\n"
+     << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
+     << "        return N; // No change\n"
+     << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
+     << "      CodeGenMap[N.getValue(0)] = New;\n"
+     << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
+     << "      CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
+     << "      return New.getValue(N.ResNo);\n"
+     << "    }\n"
      << "  }\n"
      << "  case ISD::CopyToReg: {\n"
      << "    SDOperand Chain = Select(N.getOperand(0));\n"
-     << "    SDOperand Reg = N.getOperand(1);\n"
+     << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
      << "    SDOperand Val = Select(N.getOperand(2));\n"
-     << "    return CodeGenMap[N] = \n"
-     << "                   CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
-     << "                                   Chain, Reg, Val);\n"
+     << "    SDOperand Result = N;\n"
+     << "    if (N.Val->getNumValues() == 1) {\n"
+     << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
+     << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
+     << "      return CodeGenMap[N] = Result;\n"
+     << "    } else {\n"
+     << "      SDOperand Flag;\n"
+     << "      if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
+     << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
+     << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
+     << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
+     << "      CodeGenMap[N.getValue(0)] = Result;\n"
+     << "      CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
+     << "      return Result.getValue(N.ResNo);\n"
+     << "    }\n"
      << "  }\n";
     
   // Group the patterns by their top-level opcodes.
   std::map<Record*, std::vector<PatternToMatch*>,
            CompareByRecordName> PatternsByOpcode;
   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
-    TreePatternNode *Node = PatternsToMatch[i].first;
+    TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
     if (!Node->isLeaf()) {
       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
     } else {
@@ -2298,7 +2484,7 @@ void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
         std::cerr << "Unrecognized opcode '";
         Node->dump();
         std::cerr << "' on tree pattern '";
-        std::cerr << PatternsToMatch[i].second->getOperator()->getName();
+        std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
         std::cerr << "'!\n";
         exit(1);
       }
@@ -2360,8 +2546,8 @@ void DAGISelEmitter::run(std::ostream &OS) {
   
   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
-          std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
-          std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
+          std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
+          std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
           std::cerr << "\n";
         });