12d66f8b38bbcb3b2e32d923b053f7ea1c4af947
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <algorithm>
19 #include <set>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
24
25 /// FilterVTs - Filter a list of VT's according to a predicate.
26 ///
27 template<typename T>
28 static std::vector<MVT::ValueType> 
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30   std::vector<MVT::ValueType> Result;
31   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32     if (Filter(InVTs[i]))
33       Result.push_back(InVTs[i]);
34   return Result;
35 }
36
37 template<typename T>
38 static std::vector<unsigned char> 
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40   std::vector<unsigned char> Result;
41   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42     if (Filter((MVT::ValueType)InVTs[i]))
43       Result.push_back(InVTs[i]);
44   return Result;
45 }
46
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49   std::vector<unsigned char> Result;
50   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51       Result.push_back(InVTs[i]);
52   return Result;
53 }
54
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56                              const std::vector<unsigned char> &RHS) {
57   if (LHS.size() > RHS.size()) return false;
58   for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59     if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
60       return false;
61   return true;
62 }
63
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68   return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69 }
70
71 /// isExtFloatingPointVT - Return true if the specified extended value type 
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75   return EVTs[0] == MVT::isFP ||
76          !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
77 }
78
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
81 //
82
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84   OperandNo = R->getValueAsInt("OperandNum");
85   
86   if (R->isSubClassOf("SDTCisVT")) {
87     ConstraintType = SDTCisVT;
88     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89   } else if (R->isSubClassOf("SDTCisPtrTy")) {
90     ConstraintType = SDTCisPtrTy;
91   } else if (R->isSubClassOf("SDTCisInt")) {
92     ConstraintType = SDTCisInt;
93   } else if (R->isSubClassOf("SDTCisFP")) {
94     ConstraintType = SDTCisFP;
95   } else if (R->isSubClassOf("SDTCisSameAs")) {
96     ConstraintType = SDTCisSameAs;
97     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99     ConstraintType = SDTCisVTSmallerThanOp;
100     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
101       R->getValueAsInt("OtherOperandNum");
102   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103     ConstraintType = SDTCisOpSmallerThanOp;
104     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
105       R->getValueAsInt("BigOperandNum");
106   } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107     ConstraintType = SDTCisIntVectorOfSameSize;
108     x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109       R->getValueAsInt("OtherOpNum");
110   } else {
111     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112     exit(1);
113   }
114 }
115
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119                                                  TreePatternNode *N,
120                                                  unsigned NumResults) const {
121   assert(NumResults <= 1 &&
122          "We only work with nodes with zero or one result so far!");
123   
124   if (OpNo >= (NumResults + N->getNumChildren())) {
125     std::cerr << "Invalid operand number " << OpNo << " ";
126     N->dump();
127     std::cerr << '\n';
128     exit(1);
129   }
130
131   if (OpNo < NumResults)
132     return N;  // FIXME: need value #
133   else
134     return N->getChild(OpNo-NumResults);
135 }
136
137 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
138 /// constraint to the nodes operands.  This returns true if it makes a
139 /// change, false otherwise.  If a type contradiction is found, throw an
140 /// exception.
141 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
142                                            const SDNodeInfo &NodeInfo,
143                                            TreePattern &TP) const {
144   unsigned NumResults = NodeInfo.getNumResults();
145   assert(NumResults <= 1 &&
146          "We only work with nodes with zero or one result so far!");
147   
148   // Check that the number of operands is sane.  Negative operands -> varargs.
149   if (NodeInfo.getNumOperands() >= 0) {
150     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
151       TP.error(N->getOperator()->getName() + " node requires exactly " +
152                itostr(NodeInfo.getNumOperands()) + " operands!");
153   }
154
155   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
156   
157   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
158   
159   switch (ConstraintType) {
160   default: assert(0 && "Unknown constraint type!");
161   case SDTCisVT:
162     // Operand must be a particular type.
163     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
164   case SDTCisPtrTy: {
165     // Operand must be same as target pointer type.
166     return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
167   }
168   case SDTCisInt: {
169     // If there is only one integer type supported, this must be it.
170     std::vector<MVT::ValueType> IntVTs =
171       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
172
173     // If we found exactly one supported integer type, apply it.
174     if (IntVTs.size() == 1)
175       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
176     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
177   }
178   case SDTCisFP: {
179     // If there is only one FP type supported, this must be it.
180     std::vector<MVT::ValueType> FPVTs =
181       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
182         
183     // If we found exactly one supported FP type, apply it.
184     if (FPVTs.size() == 1)
185       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
186     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
187   }
188   case SDTCisSameAs: {
189     TreePatternNode *OtherNode =
190       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
191     return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
192            OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
193   }
194   case SDTCisVTSmallerThanOp: {
195     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
196     // have an integer type that is smaller than the VT.
197     if (!NodeToApply->isLeaf() ||
198         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
199         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
200                ->isSubClassOf("ValueType"))
201       TP.error(N->getOperator()->getName() + " expects a VT operand!");
202     MVT::ValueType VT =
203      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
204     if (!MVT::isInteger(VT))
205       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
206     
207     TreePatternNode *OtherNode =
208       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
209     
210     // It must be integer.
211     bool MadeChange = false;
212     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
213     
214     // This code only handles nodes that have one type set.  Assert here so
215     // that we can change this if we ever need to deal with multiple value
216     // types at this point.
217     assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
218     if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
219       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
220     return false;
221   }
222   case SDTCisOpSmallerThanOp: {
223     TreePatternNode *BigOperand =
224       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
225
226     // Both operands must be integer or FP, but we don't care which.
227     bool MadeChange = false;
228     
229     // This code does not currently handle nodes which have multiple types,
230     // where some types are integer, and some are fp.  Assert that this is not
231     // the case.
232     assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
233              isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
234            !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
235              isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
236            "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
237     if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
238       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
239     else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
240       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
241     if (isExtIntegerInVTs(BigOperand->getExtTypes()))
242       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
243     else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
244       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
245
246     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
247     
248     if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
249       VTs = FilterVTs(VTs, MVT::isInteger);
250     } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
251       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
252     } else {
253       VTs.clear();
254     }
255
256     switch (VTs.size()) {
257     default:         // Too many VT's to pick from.
258     case 0: break;   // No info yet.
259     case 1: 
260       // Only one VT of this flavor.  Cannot ever satisify the constraints.
261       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
262     case 2:
263       // If we have exactly two possible types, the little operand must be the
264       // small one, the big operand should be the big one.  Common with 
265       // float/double for example.
266       assert(VTs[0] < VTs[1] && "Should be sorted!");
267       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
268       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
269       break;
270     }    
271     return MadeChange;
272   }
273   case SDTCisIntVectorOfSameSize: {
274     TreePatternNode *OtherOperand =
275       getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
276                     N, NumResults);
277     if (OtherOperand->hasTypeSet()) {
278       if (!MVT::isVector(OtherOperand->getTypeNum(0)))
279         TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
280       MVT::ValueType IVT = OtherOperand->getTypeNum(0);
281       IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
282       return NodeToApply->UpdateNodeType(IVT, TP);
283     }
284     return false;
285   }
286   }  
287   return false;
288 }
289
290
291 //===----------------------------------------------------------------------===//
292 // SDNodeInfo implementation
293 //
294 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
295   EnumName    = R->getValueAsString("Opcode");
296   SDClassName = R->getValueAsString("SDClass");
297   Record *TypeProfile = R->getValueAsDef("TypeProfile");
298   NumResults = TypeProfile->getValueAsInt("NumResults");
299   NumOperands = TypeProfile->getValueAsInt("NumOperands");
300   
301   // Parse the properties.
302   Properties = 0;
303   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
304   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
305     if (PropList[i]->getName() == "SDNPCommutative") {
306       Properties |= 1 << SDNPCommutative;
307     } else if (PropList[i]->getName() == "SDNPAssociative") {
308       Properties |= 1 << SDNPAssociative;
309     } else if (PropList[i]->getName() == "SDNPHasChain") {
310       Properties |= 1 << SDNPHasChain;
311     } else if (PropList[i]->getName() == "SDNPOutFlag") {
312       Properties |= 1 << SDNPOutFlag;
313     } else if (PropList[i]->getName() == "SDNPInFlag") {
314       Properties |= 1 << SDNPInFlag;
315     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
316       Properties |= 1 << SDNPOptInFlag;
317     } else {
318       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
319                 << "' on node '" << R->getName() << "'!\n";
320       exit(1);
321     }
322   }
323   
324   
325   // Parse the type constraints.
326   std::vector<Record*> ConstraintList =
327     TypeProfile->getValueAsListOfDefs("Constraints");
328   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
329 }
330
331 //===----------------------------------------------------------------------===//
332 // TreePatternNode implementation
333 //
334
335 TreePatternNode::~TreePatternNode() {
336 #if 0 // FIXME: implement refcounted tree nodes!
337   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
338     delete getChild(i);
339 #endif
340 }
341
342 /// UpdateNodeType - Set the node type of N to VT if VT contains
343 /// information.  If N already contains a conflicting type, then throw an
344 /// exception.  This returns true if any information was updated.
345 ///
346 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
347                                      TreePattern &TP) {
348   assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
349   
350   if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs)) 
351     return false;
352   if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
353     setTypes(ExtVTs);
354     return true;
355   }
356
357   if (getExtTypeNum(0) == MVT::iPTR) {
358     if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
359       return false;
360     if (isExtIntegerInVTs(ExtVTs)) {
361       std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
362       if (FVTs.size()) {
363         setTypes(ExtVTs);
364         return true;
365       }
366     }
367   }
368   
369   if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
370     assert(hasTypeSet() && "should be handled above!");
371     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
372     if (getExtTypes() == FVTs)
373       return false;
374     setTypes(FVTs);
375     return true;
376   }
377   if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
378     //assert(hasTypeSet() && "should be handled above!");
379     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
380     if (getExtTypes() == FVTs)
381       return false;
382     if (FVTs.size()) {
383       setTypes(FVTs);
384       return true;
385     }
386   }      
387   if (ExtVTs[0] == MVT::isFP  && isExtFloatingPointInVTs(getExtTypes())) {
388     assert(hasTypeSet() && "should be handled above!");
389     std::vector<unsigned char> FVTs =
390       FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
391     if (getExtTypes() == FVTs)
392       return false;
393     setTypes(FVTs);
394     return true;
395   }
396       
397   // If we know this is an int or fp type, and we are told it is a specific one,
398   // take the advice.
399   //
400   // Similarly, we should probably set the type here to the intersection of
401   // {isInt|isFP} and ExtVTs
402   if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
403       (getExtTypeNum(0) == MVT::isFP  && isExtFloatingPointInVTs(ExtVTs))) {
404     setTypes(ExtVTs);
405     return true;
406   }
407   if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
408     setTypes(ExtVTs);
409     return true;
410   }
411
412   if (isLeaf()) {
413     dump();
414     std::cerr << " ";
415     TP.error("Type inference contradiction found in node!");
416   } else {
417     TP.error("Type inference contradiction found in node " + 
418              getOperator()->getName() + "!");
419   }
420   return true; // unreachable
421 }
422
423
424 void TreePatternNode::print(std::ostream &OS) const {
425   if (isLeaf()) {
426     OS << *getLeafValue();
427   } else {
428     OS << "(" << getOperator()->getName();
429   }
430   
431   // FIXME: At some point we should handle printing all the value types for 
432   // nodes that are multiply typed.
433   switch (getExtTypeNum(0)) {
434   case MVT::Other: OS << ":Other"; break;
435   case MVT::isInt: OS << ":isInt"; break;
436   case MVT::isFP : OS << ":isFP"; break;
437   case MVT::isUnknown: ; /*OS << ":?";*/ break;
438   case MVT::iPTR:  OS << ":iPTR"; break;
439   default: {
440     std::string VTName = llvm::getName(getTypeNum(0));
441     // Strip off MVT:: prefix if present.
442     if (VTName.substr(0,5) == "MVT::")
443       VTName = VTName.substr(5);
444     OS << ":" << VTName;
445     break;
446   }
447   }
448
449   if (!isLeaf()) {
450     if (getNumChildren() != 0) {
451       OS << " ";
452       getChild(0)->print(OS);
453       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
454         OS << ", ";
455         getChild(i)->print(OS);
456       }
457     }
458     OS << ")";
459   }
460   
461   if (!PredicateFn.empty())
462     OS << "<<P:" << PredicateFn << ">>";
463   if (TransformFn)
464     OS << "<<X:" << TransformFn->getName() << ">>";
465   if (!getName().empty())
466     OS << ":$" << getName();
467
468 }
469 void TreePatternNode::dump() const {
470   print(std::cerr);
471 }
472
473 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
474 /// the specified node.  For this comparison, all of the state of the node
475 /// is considered, except for the assigned name.  Nodes with differing names
476 /// that are otherwise identical are considered isomorphic.
477 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
478   if (N == this) return true;
479   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
480       getPredicateFn() != N->getPredicateFn() ||
481       getTransformFn() != N->getTransformFn())
482     return false;
483
484   if (isLeaf()) {
485     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
487         return DI->getDef() == NDI->getDef();
488     return getLeafValue() == N->getLeafValue();
489   }
490   
491   if (N->getOperator() != getOperator() ||
492       N->getNumChildren() != getNumChildren()) return false;
493   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
494     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
495       return false;
496   return true;
497 }
498
499 /// clone - Make a copy of this tree and all of its children.
500 ///
501 TreePatternNode *TreePatternNode::clone() const {
502   TreePatternNode *New;
503   if (isLeaf()) {
504     New = new TreePatternNode(getLeafValue());
505   } else {
506     std::vector<TreePatternNode*> CChildren;
507     CChildren.reserve(Children.size());
508     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
509       CChildren.push_back(getChild(i)->clone());
510     New = new TreePatternNode(getOperator(), CChildren);
511   }
512   New->setName(getName());
513   New->setTypes(getExtTypes());
514   New->setPredicateFn(getPredicateFn());
515   New->setTransformFn(getTransformFn());
516   return New;
517 }
518
519 /// SubstituteFormalArguments - Replace the formal arguments in this tree
520 /// with actual values specified by ArgMap.
521 void TreePatternNode::
522 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
523   if (isLeaf()) return;
524   
525   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
526     TreePatternNode *Child = getChild(i);
527     if (Child->isLeaf()) {
528       Init *Val = Child->getLeafValue();
529       if (dynamic_cast<DefInit*>(Val) &&
530           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
531         // We found a use of a formal argument, replace it with its value.
532         Child = ArgMap[Child->getName()];
533         assert(Child && "Couldn't find formal argument!");
534         setChild(i, Child);
535       }
536     } else {
537       getChild(i)->SubstituteFormalArguments(ArgMap);
538     }
539   }
540 }
541
542
543 /// InlinePatternFragments - If this pattern refers to any pattern
544 /// fragments, inline them into place, giving us a pattern without any
545 /// PatFrag references.
546 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
547   if (isLeaf()) return this;  // nothing to do.
548   Record *Op = getOperator();
549   
550   if (!Op->isSubClassOf("PatFrag")) {
551     // Just recursively inline children nodes.
552     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
553       setChild(i, getChild(i)->InlinePatternFragments(TP));
554     return this;
555   }
556
557   // Otherwise, we found a reference to a fragment.  First, look up its
558   // TreePattern record.
559   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
560   
561   // Verify that we are passing the right number of operands.
562   if (Frag->getNumArgs() != Children.size())
563     TP.error("'" + Op->getName() + "' fragment requires " +
564              utostr(Frag->getNumArgs()) + " operands!");
565
566   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
567
568   // Resolve formal arguments to their actual value.
569   if (Frag->getNumArgs()) {
570     // Compute the map of formal to actual arguments.
571     std::map<std::string, TreePatternNode*> ArgMap;
572     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
573       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
574   
575     FragTree->SubstituteFormalArguments(ArgMap);
576   }
577   
578   FragTree->setName(getName());
579   FragTree->UpdateNodeType(getExtTypes(), TP);
580   
581   // Get a new copy of this fragment to stitch into here.
582   //delete this;    // FIXME: implement refcounting!
583   return FragTree;
584 }
585
586 /// getImplicitType - Check to see if the specified record has an implicit
587 /// type which should be applied to it.  This infer the type of register
588 /// references from the register file information, for example.
589 ///
590 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
591                                       TreePattern &TP) {
592   // Some common return values
593   std::vector<unsigned char> Unknown(1, MVT::isUnknown);
594   std::vector<unsigned char> Other(1, MVT::Other);
595
596   // Check to see if this is a register or a register class...
597   if (R->isSubClassOf("RegisterClass")) {
598     if (NotRegisters) 
599       return Unknown;
600     const CodeGenRegisterClass &RC = 
601       TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
602     return ConvertVTs(RC.getValueTypes());
603   } else if (R->isSubClassOf("PatFrag")) {
604     // Pattern fragment types will be resolved when they are inlined.
605     return Unknown;
606   } else if (R->isSubClassOf("Register")) {
607     if (NotRegisters) 
608       return Unknown;
609     const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
610     return T.getRegisterVTs(R);
611   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
612     // Using a VTSDNode or CondCodeSDNode.
613     return Other;
614   } else if (R->isSubClassOf("ComplexPattern")) {
615     if (NotRegisters) 
616       return Unknown;
617     std::vector<unsigned char>
618     ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
619     return ComplexPat;
620   } else if (R->getName() == "node" || R->getName() == "srcvalue") {
621     // Placeholder.
622     return Unknown;
623   }
624   
625   TP.error("Unknown node flavor used in pattern: " + R->getName());
626   return Other;
627 }
628
629 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
630 /// this node and its children in the tree.  This returns true if it makes a
631 /// change, false otherwise.  If a type contradiction is found, throw an
632 /// exception.
633 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
634   DAGISelEmitter &ISE = TP.getDAGISelEmitter();
635   if (isLeaf()) {
636     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
637       // If it's a regclass or something else known, include the type.
638       return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
639     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
640       // Int inits are always integers. :)
641       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
642       
643       if (hasTypeSet()) {
644         // At some point, it may make sense for this tree pattern to have
645         // multiple types.  Assert here that it does not, so we revisit this
646         // code when appropriate.
647         assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
648         MVT::ValueType VT = getTypeNum(0);
649         for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
650           assert(getTypeNum(i) == VT && "TreePattern has too many types!");
651         
652         VT = getTypeNum(0);
653         if (VT != MVT::iPTR) {
654           unsigned Size = MVT::getSizeInBits(VT);
655           // Make sure that the value is representable for this type.
656           if (Size < 32) {
657             int Val = (II->getValue() << (32-Size)) >> (32-Size);
658             if (Val != II->getValue())
659               TP.error("Sign-extended integer value '" + itostr(II->getValue())+
660                        "' is out of range for type '" + 
661                        getEnumName(getTypeNum(0)) + "'!");
662           }
663         }
664       }
665       
666       return MadeChange;
667     }
668     return false;
669   }
670   
671   // special handling for set, which isn't really an SDNode.
672   if (getOperator()->getName() == "set") {
673     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
674     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
675     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
676     
677     // Types of operands must match.
678     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
679     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
680     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
681     return MadeChange;
682   } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
683              getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
684              getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
685     unsigned IID = 
686     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
687     const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
688     bool MadeChange = false;
689     
690     // Apply the result type to the node.
691     MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
692     
693     if (getNumChildren() != Int.ArgVTs.size())
694       TP.error("Intrinsic '" + Int.Name + "' expects " +
695                utostr(Int.ArgVTs.size()-1) + " operands, not " +
696                utostr(getNumChildren()-1) + " operands!");
697
698     // Apply type info to the intrinsic ID.
699     MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
700     
701     for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
702       MVT::ValueType OpVT = Int.ArgVTs[i];
703       MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
704       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
705     }
706     return MadeChange;
707   } else if (getOperator()->isSubClassOf("SDNode")) {
708     const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
709     
710     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
711     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
712       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
713     // Branch, etc. do not produce results and top-level forms in instr pattern
714     // must have void types.
715     if (NI.getNumResults() == 0)
716       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
717     
718     // If this is a vector_shuffle operation, apply types to the build_vector
719     // operation.  The types of the integers don't matter, but this ensures they
720     // won't get checked.
721     if (getOperator()->getName() == "vector_shuffle" &&
722         getChild(2)->getOperator()->getName() == "build_vector") {
723       TreePatternNode *BV = getChild(2);
724       const std::vector<MVT::ValueType> &LegalVTs
725         = ISE.getTargetInfo().getLegalValueTypes();
726       MVT::ValueType LegalIntVT = MVT::Other;
727       for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
728         if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
729           LegalIntVT = LegalVTs[i];
730           break;
731         }
732       assert(LegalIntVT != MVT::Other && "No legal integer VT?");
733             
734       for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
735         MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
736     }
737     return MadeChange;  
738   } else if (getOperator()->isSubClassOf("Instruction")) {
739     const DAGInstruction &Inst = ISE.getInstruction(getOperator());
740     bool MadeChange = false;
741     unsigned NumResults = Inst.getNumResults();
742     
743     assert(NumResults <= 1 &&
744            "Only supports zero or one result instrs!");
745     // Apply the result type to the node
746     if (NumResults == 0) {
747       MadeChange = UpdateNodeType(MVT::isVoid, TP);
748     } else {
749       Record *ResultNode = Inst.getResult(0);
750       assert(ResultNode->isSubClassOf("RegisterClass") &&
751              "Operands should be register classes!");
752
753       const CodeGenRegisterClass &RC = 
754         ISE.getTargetInfo().getRegisterClass(ResultNode);
755       MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
756     }
757
758     if (getNumChildren() != Inst.getNumOperands())
759       TP.error("Instruction '" + getOperator()->getName() + " expects " +
760                utostr(Inst.getNumOperands()) + " operands, not " +
761                utostr(getNumChildren()) + " operands!");
762     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
763       Record *OperandNode = Inst.getOperand(i);
764       MVT::ValueType VT;
765       if (OperandNode->isSubClassOf("RegisterClass")) {
766         const CodeGenRegisterClass &RC = 
767           ISE.getTargetInfo().getRegisterClass(OperandNode);
768         //VT = RC.getValueTypeNum(0);
769         MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
770                                                  TP);
771       } else if (OperandNode->isSubClassOf("Operand")) {
772         VT = getValueType(OperandNode->getValueAsDef("Type"));
773         MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
774       } else {
775         assert(0 && "Unknown operand type!");
776         abort();
777       }
778       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
779     }
780     return MadeChange;
781   } else {
782     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
783     
784     // Node transforms always take one operand.
785     if (getNumChildren() != 1)
786       TP.error("Node transform '" + getOperator()->getName() +
787                "' requires one operand!");
788
789     // If either the output or input of the xform does not have exact
790     // type info. We assume they must be the same. Otherwise, it is perfectly
791     // legal to transform from one type to a completely different type.
792     if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
793       bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
794       MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
795       return MadeChange;
796     }
797     return false;
798   }
799 }
800
801 /// canPatternMatch - If it is impossible for this pattern to match on this
802 /// target, fill in Reason and return false.  Otherwise, return true.  This is
803 /// used as a santity check for .td files (to prevent people from writing stuff
804 /// that can never possibly work), and to prevent the pattern permuter from
805 /// generating stuff that is useless.
806 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
807   if (isLeaf()) return true;
808
809   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
810     if (!getChild(i)->canPatternMatch(Reason, ISE))
811       return false;
812
813   // If this is an intrinsic, handle cases that would make it not match.  For
814   // example, if an operand is required to be an immediate.
815   if (getOperator()->isSubClassOf("Intrinsic")) {
816     // TODO:
817     return true;
818   }
819   
820   // If this node is a commutative operator, check that the LHS isn't an
821   // immediate.
822   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
823   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
824     // Scan all of the operands of the node and make sure that only the last one
825     // is a constant node.
826     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
827       if (!getChild(i)->isLeaf() && 
828           getChild(i)->getOperator()->getName() == "imm") {
829         Reason = "Immediate value must be on the RHS of commutative operators!";
830         return false;
831       }
832   }
833   
834   return true;
835 }
836
837 //===----------------------------------------------------------------------===//
838 // TreePattern implementation
839 //
840
841 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
842                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
843    isInputPattern = isInput;
844    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
845      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
846 }
847
848 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
849                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
850   isInputPattern = isInput;
851   Trees.push_back(ParseTreePattern(Pat));
852 }
853
854 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
855                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
856   isInputPattern = isInput;
857   Trees.push_back(Pat);
858 }
859
860
861
862 void TreePattern::error(const std::string &Msg) const {
863   dump();
864   throw "In " + TheRecord->getName() + ": " + Msg;
865 }
866
867 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
868   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
869   if (!OpDef) error("Pattern has unexpected operator type!");
870   Record *Operator = OpDef->getDef();
871   
872   if (Operator->isSubClassOf("ValueType")) {
873     // If the operator is a ValueType, then this must be "type cast" of a leaf
874     // node.
875     if (Dag->getNumArgs() != 1)
876       error("Type cast only takes one operand!");
877     
878     Init *Arg = Dag->getArg(0);
879     TreePatternNode *New;
880     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
881       Record *R = DI->getDef();
882       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
883         Dag->setArg(0, new DagInit(DI,
884                                 std::vector<std::pair<Init*, std::string> >()));
885         return ParseTreePattern(Dag);
886       }
887       New = new TreePatternNode(DI);
888     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
889       New = ParseTreePattern(DI);
890     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
891       New = new TreePatternNode(II);
892       if (!Dag->getArgName(0).empty())
893         error("Constant int argument should not have a name!");
894     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
895       // Turn this into an IntInit.
896       Init *II = BI->convertInitializerTo(new IntRecTy());
897       if (II == 0 || !dynamic_cast<IntInit*>(II))
898         error("Bits value must be constants!");
899       
900       New = new TreePatternNode(dynamic_cast<IntInit*>(II));
901       if (!Dag->getArgName(0).empty())
902         error("Constant int argument should not have a name!");
903     } else {
904       Arg->dump();
905       error("Unknown leaf value for tree pattern!");
906       return 0;
907     }
908     
909     // Apply the type cast.
910     New->UpdateNodeType(getValueType(Operator), *this);
911     New->setName(Dag->getArgName(0));
912     return New;
913   }
914   
915   // Verify that this is something that makes sense for an operator.
916   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
917       !Operator->isSubClassOf("Instruction") && 
918       !Operator->isSubClassOf("SDNodeXForm") &&
919       !Operator->isSubClassOf("Intrinsic") &&
920       Operator->getName() != "set")
921     error("Unrecognized node '" + Operator->getName() + "'!");
922   
923   //  Check to see if this is something that is illegal in an input pattern.
924   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
925                          Operator->isSubClassOf("SDNodeXForm")))
926     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
927   
928   std::vector<TreePatternNode*> Children;
929   
930   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
931     Init *Arg = Dag->getArg(i);
932     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
933       Children.push_back(ParseTreePattern(DI));
934       if (Children.back()->getName().empty())
935         Children.back()->setName(Dag->getArgName(i));
936     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
937       Record *R = DefI->getDef();
938       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
939       // TreePatternNode if its own.
940       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
941         Dag->setArg(i, new DagInit(DefI,
942                               std::vector<std::pair<Init*, std::string> >()));
943         --i;  // Revisit this node...
944       } else {
945         TreePatternNode *Node = new TreePatternNode(DefI);
946         Node->setName(Dag->getArgName(i));
947         Children.push_back(Node);
948         
949         // Input argument?
950         if (R->getName() == "node") {
951           if (Dag->getArgName(i).empty())
952             error("'node' argument requires a name to match with operand list");
953           Args.push_back(Dag->getArgName(i));
954         }
955       }
956     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
957       TreePatternNode *Node = new TreePatternNode(II);
958       if (!Dag->getArgName(i).empty())
959         error("Constant int argument should not have a name!");
960       Children.push_back(Node);
961     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
962       // Turn this into an IntInit.
963       Init *II = BI->convertInitializerTo(new IntRecTy());
964       if (II == 0 || !dynamic_cast<IntInit*>(II))
965         error("Bits value must be constants!");
966       
967       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
968       if (!Dag->getArgName(i).empty())
969         error("Constant int argument should not have a name!");
970       Children.push_back(Node);
971     } else {
972       std::cerr << '"';
973       Arg->dump();
974       std::cerr << "\": ";
975       error("Unknown leaf value for tree pattern!");
976     }
977   }
978   
979   // If the operator is an intrinsic, then this is just syntactic sugar for for
980   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
981   // convert the intrinsic name to a number.
982   if (Operator->isSubClassOf("Intrinsic")) {
983     const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
984     unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
985
986     // If this intrinsic returns void, it must have side-effects and thus a
987     // chain.
988     if (Int.ArgVTs[0] == MVT::isVoid) {
989       Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
990     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
991       // Has side-effects, requires chain.
992       Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
993     } else {
994       // Otherwise, no chain.
995       Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
996     }
997     
998     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
999     Children.insert(Children.begin(), IIDNode);
1000   }
1001   
1002   return new TreePatternNode(Operator, Children);
1003 }
1004
1005 /// InferAllTypes - Infer/propagate as many types throughout the expression
1006 /// patterns as possible.  Return true if all types are infered, false
1007 /// otherwise.  Throw an exception if a type contradiction is found.
1008 bool TreePattern::InferAllTypes() {
1009   bool MadeChange = true;
1010   while (MadeChange) {
1011     MadeChange = false;
1012     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1013       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1014   }
1015   
1016   bool HasUnresolvedTypes = false;
1017   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1018     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1019   return !HasUnresolvedTypes;
1020 }
1021
1022 void TreePattern::print(std::ostream &OS) const {
1023   OS << getRecord()->getName();
1024   if (!Args.empty()) {
1025     OS << "(" << Args[0];
1026     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1027       OS << ", " << Args[i];
1028     OS << ")";
1029   }
1030   OS << ": ";
1031   
1032   if (Trees.size() > 1)
1033     OS << "[\n";
1034   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1035     OS << "\t";
1036     Trees[i]->print(OS);
1037     OS << "\n";
1038   }
1039
1040   if (Trees.size() > 1)
1041     OS << "]\n";
1042 }
1043
1044 void TreePattern::dump() const { print(std::cerr); }
1045
1046
1047
1048 //===----------------------------------------------------------------------===//
1049 // DAGISelEmitter implementation
1050 //
1051
1052 // Parse all of the SDNode definitions for the target, populating SDNodes.
1053 void DAGISelEmitter::ParseNodeInfo() {
1054   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1055   while (!Nodes.empty()) {
1056     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1057     Nodes.pop_back();
1058   }
1059
1060   // Get the buildin intrinsic nodes.
1061   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1062   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1063   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1064 }
1065
1066 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1067 /// map, and emit them to the file as functions.
1068 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1069   OS << "\n// Node transformations.\n";
1070   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1071   while (!Xforms.empty()) {
1072     Record *XFormNode = Xforms.back();
1073     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1074     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1075     SDNodeXForms.insert(std::make_pair(XFormNode,
1076                                        std::make_pair(SDNode, Code)));
1077
1078     if (!Code.empty()) {
1079       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1080       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1081
1082       OS << "inline SDOperand Transform_" << XFormNode->getName()
1083          << "(SDNode *" << C2 << ") {\n";
1084       if (ClassName != "SDNode")
1085         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1086       OS << Code << "\n}\n";
1087     }
1088
1089     Xforms.pop_back();
1090   }
1091 }
1092
1093 void DAGISelEmitter::ParseComplexPatterns() {
1094   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1095   while (!AMs.empty()) {
1096     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1097     AMs.pop_back();
1098   }
1099 }
1100
1101
1102 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1103 /// file, building up the PatternFragments map.  After we've collected them all,
1104 /// inline fragments together as necessary, so that there are no references left
1105 /// inside a pattern fragment to a pattern fragment.
1106 ///
1107 /// This also emits all of the predicate functions to the output file.
1108 ///
1109 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1110   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1111   
1112   // First step, parse all of the fragments and emit predicate functions.
1113   OS << "\n// Predicate functions.\n";
1114   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1115     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1116     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1117     PatternFragments[Fragments[i]] = P;
1118     
1119     // Validate the argument list, converting it to map, to discard duplicates.
1120     std::vector<std::string> &Args = P->getArgList();
1121     std::set<std::string> OperandsMap(Args.begin(), Args.end());
1122     
1123     if (OperandsMap.count(""))
1124       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1125     
1126     // Parse the operands list.
1127     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1128     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1129     if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1130       P->error("Operands list should start with '(ops ... '!");
1131     
1132     // Copy over the arguments.       
1133     Args.clear();
1134     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1135       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1136           static_cast<DefInit*>(OpsList->getArg(j))->
1137           getDef()->getName() != "node")
1138         P->error("Operands list should all be 'node' values.");
1139       if (OpsList->getArgName(j).empty())
1140         P->error("Operands list should have names for each operand!");
1141       if (!OperandsMap.count(OpsList->getArgName(j)))
1142         P->error("'" + OpsList->getArgName(j) +
1143                  "' does not occur in pattern or was multiply specified!");
1144       OperandsMap.erase(OpsList->getArgName(j));
1145       Args.push_back(OpsList->getArgName(j));
1146     }
1147     
1148     if (!OperandsMap.empty())
1149       P->error("Operands list does not contain an entry for operand '" +
1150                *OperandsMap.begin() + "'!");
1151
1152     // If there is a code init for this fragment, emit the predicate code and
1153     // keep track of the fact that this fragment uses it.
1154     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1155     if (!Code.empty()) {
1156       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1157       std::string ClassName =
1158         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1159       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1160       
1161       OS << "inline bool Predicate_" << Fragments[i]->getName()
1162          << "(SDNode *" << C2 << ") {\n";
1163       if (ClassName != "SDNode")
1164         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1165       OS << Code << "\n}\n";
1166       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1167     }
1168     
1169     // If there is a node transformation corresponding to this, keep track of
1170     // it.
1171     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1172     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1173       P->getOnlyTree()->setTransformFn(Transform);
1174   }
1175   
1176   OS << "\n\n";
1177
1178   // Now that we've parsed all of the tree fragments, do a closure on them so
1179   // that there are not references to PatFrags left inside of them.
1180   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1181        E = PatternFragments.end(); I != E; ++I) {
1182     TreePattern *ThePat = I->second;
1183     ThePat->InlinePatternFragments();
1184         
1185     // Infer as many types as possible.  Don't worry about it if we don't infer
1186     // all of them, some may depend on the inputs of the pattern.
1187     try {
1188       ThePat->InferAllTypes();
1189     } catch (...) {
1190       // If this pattern fragment is not supported by this target (no types can
1191       // satisfy its constraints), just ignore it.  If the bogus pattern is
1192       // actually used by instructions, the type consistency error will be
1193       // reported there.
1194     }
1195     
1196     // If debugging, print out the pattern fragment result.
1197     DEBUG(ThePat->dump());
1198   }
1199 }
1200
1201 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1202 /// instruction input.  Return true if this is a real use.
1203 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1204                       std::map<std::string, TreePatternNode*> &InstInputs,
1205                       std::vector<Record*> &InstImpInputs) {
1206   // No name -> not interesting.
1207   if (Pat->getName().empty()) {
1208     if (Pat->isLeaf()) {
1209       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1210       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1211         I->error("Input " + DI->getDef()->getName() + " must be named!");
1212       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1213         InstImpInputs.push_back(DI->getDef());
1214     }
1215     return false;
1216   }
1217
1218   Record *Rec;
1219   if (Pat->isLeaf()) {
1220     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1221     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1222     Rec = DI->getDef();
1223   } else {
1224     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1225     Rec = Pat->getOperator();
1226   }
1227
1228   // SRCVALUE nodes are ignored.
1229   if (Rec->getName() == "srcvalue")
1230     return false;
1231
1232   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1233   if (!Slot) {
1234     Slot = Pat;
1235   } else {
1236     Record *SlotRec;
1237     if (Slot->isLeaf()) {
1238       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1239     } else {
1240       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1241       SlotRec = Slot->getOperator();
1242     }
1243     
1244     // Ensure that the inputs agree if we've already seen this input.
1245     if (Rec != SlotRec)
1246       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1247     if (Slot->getExtTypes() != Pat->getExtTypes())
1248       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1249   }
1250   return true;
1251 }
1252
1253 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1254 /// part of "I", the instruction), computing the set of inputs and outputs of
1255 /// the pattern.  Report errors if we see anything naughty.
1256 void DAGISelEmitter::
1257 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1258                             std::map<std::string, TreePatternNode*> &InstInputs,
1259                             std::map<std::string, TreePatternNode*>&InstResults,
1260                             std::vector<Record*> &InstImpInputs,
1261                             std::vector<Record*> &InstImpResults) {
1262   if (Pat->isLeaf()) {
1263     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1264     if (!isUse && Pat->getTransformFn())
1265       I->error("Cannot specify a transform function for a non-input value!");
1266     return;
1267   } else if (Pat->getOperator()->getName() != "set") {
1268     // If this is not a set, verify that the children nodes are not void typed,
1269     // and recurse.
1270     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1271       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1272         I->error("Cannot have void nodes inside of patterns!");
1273       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1274                                   InstImpInputs, InstImpResults);
1275     }
1276     
1277     // If this is a non-leaf node with no children, treat it basically as if
1278     // it were a leaf.  This handles nodes like (imm).
1279     bool isUse = false;
1280     if (Pat->getNumChildren() == 0)
1281       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1282     
1283     if (!isUse && Pat->getTransformFn())
1284       I->error("Cannot specify a transform function for a non-input value!");
1285     return;
1286   } 
1287   
1288   // Otherwise, this is a set, validate and collect instruction results.
1289   if (Pat->getNumChildren() == 0)
1290     I->error("set requires operands!");
1291   else if (Pat->getNumChildren() & 1)
1292     I->error("set requires an even number of operands");
1293   
1294   if (Pat->getTransformFn())
1295     I->error("Cannot specify a transform function on a set node!");
1296   
1297   // Check the set destinations.
1298   unsigned NumValues = Pat->getNumChildren()/2;
1299   for (unsigned i = 0; i != NumValues; ++i) {
1300     TreePatternNode *Dest = Pat->getChild(i);
1301     if (!Dest->isLeaf())
1302       I->error("set destination should be a register!");
1303     
1304     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1305     if (!Val)
1306       I->error("set destination should be a register!");
1307
1308     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1309       if (Dest->getName().empty())
1310         I->error("set destination must have a name!");
1311       if (InstResults.count(Dest->getName()))
1312         I->error("cannot set '" + Dest->getName() +"' multiple times");
1313       InstResults[Dest->getName()] = Dest;
1314     } else if (Val->getDef()->isSubClassOf("Register")) {
1315       InstImpResults.push_back(Val->getDef());
1316     } else {
1317       I->error("set destination should be a register!");
1318     }
1319     
1320     // Verify and collect info from the computation.
1321     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1322                                 InstInputs, InstResults,
1323                                 InstImpInputs, InstImpResults);
1324   }
1325 }
1326
1327 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1328 /// any fragments involved.  This populates the Instructions list with fully
1329 /// resolved instructions.
1330 void DAGISelEmitter::ParseInstructions() {
1331   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1332   
1333   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1334     ListInit *LI = 0;
1335     
1336     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1337       LI = Instrs[i]->getValueAsListInit("Pattern");
1338     
1339     // If there is no pattern, only collect minimal information about the
1340     // instruction for its operand list.  We have to assume that there is one
1341     // result, as we have no detailed info.
1342     if (!LI || LI->getSize() == 0) {
1343       std::vector<Record*> Results;
1344       std::vector<Record*> Operands;
1345       
1346       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1347
1348       if (InstInfo.OperandList.size() != 0) {
1349         // FIXME: temporary hack...
1350         if (InstInfo.noResults) {
1351           // These produce no results
1352           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1353             Operands.push_back(InstInfo.OperandList[j].Rec);
1354         } else {
1355           // Assume the first operand is the result.
1356           Results.push_back(InstInfo.OperandList[0].Rec);
1357       
1358           // The rest are inputs.
1359           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1360             Operands.push_back(InstInfo.OperandList[j].Rec);
1361         }
1362       }
1363       
1364       // Create and insert the instruction.
1365       std::vector<Record*> ImpResults;
1366       std::vector<Record*> ImpOperands;
1367       Instructions.insert(std::make_pair(Instrs[i], 
1368                           DAGInstruction(0, Results, Operands, ImpResults,
1369                                          ImpOperands)));
1370       continue;  // no pattern.
1371     }
1372     
1373     // Parse the instruction.
1374     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1375     // Inline pattern fragments into it.
1376     I->InlinePatternFragments();
1377     
1378     // Infer as many types as possible.  If we cannot infer all of them, we can
1379     // never do anything with this instruction pattern: report it to the user.
1380     if (!I->InferAllTypes())
1381       I->error("Could not infer all types in pattern!");
1382     
1383     // InstInputs - Keep track of all of the inputs of the instruction, along 
1384     // with the record they are declared as.
1385     std::map<std::string, TreePatternNode*> InstInputs;
1386     
1387     // InstResults - Keep track of all the virtual registers that are 'set'
1388     // in the instruction, including what reg class they are.
1389     std::map<std::string, TreePatternNode*> InstResults;
1390
1391     std::vector<Record*> InstImpInputs;
1392     std::vector<Record*> InstImpResults;
1393     
1394     // Verify that the top-level forms in the instruction are of void type, and
1395     // fill in the InstResults map.
1396     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1397       TreePatternNode *Pat = I->getTree(j);
1398       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1399         I->error("Top-level forms in instruction pattern should have"
1400                  " void types");
1401
1402       // Find inputs and outputs, and verify the structure of the uses/defs.
1403       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1404                                   InstImpInputs, InstImpResults);
1405     }
1406
1407     // Now that we have inputs and outputs of the pattern, inspect the operands
1408     // list for the instruction.  This determines the order that operands are
1409     // added to the machine instruction the node corresponds to.
1410     unsigned NumResults = InstResults.size();
1411
1412     // Parse the operands list from the (ops) list, validating it.
1413     std::vector<std::string> &Args = I->getArgList();
1414     assert(Args.empty() && "Args list should still be empty here!");
1415     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1416
1417     // Check that all of the results occur first in the list.
1418     std::vector<Record*> Results;
1419     TreePatternNode *Res0Node = NULL;
1420     for (unsigned i = 0; i != NumResults; ++i) {
1421       if (i == CGI.OperandList.size())
1422         I->error("'" + InstResults.begin()->first +
1423                  "' set but does not appear in operand list!");
1424       const std::string &OpName = CGI.OperandList[i].Name;
1425       
1426       // Check that it exists in InstResults.
1427       TreePatternNode *RNode = InstResults[OpName];
1428       if (RNode == 0)
1429         I->error("Operand $" + OpName + " does not exist in operand list!");
1430         
1431       if (i == 0)
1432         Res0Node = RNode;
1433       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1434       if (R == 0)
1435         I->error("Operand $" + OpName + " should be a set destination: all "
1436                  "outputs must occur before inputs in operand list!");
1437       
1438       if (CGI.OperandList[i].Rec != R)
1439         I->error("Operand $" + OpName + " class mismatch!");
1440       
1441       // Remember the return type.
1442       Results.push_back(CGI.OperandList[i].Rec);
1443       
1444       // Okay, this one checks out.
1445       InstResults.erase(OpName);
1446     }
1447
1448     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1449     // the copy while we're checking the inputs.
1450     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1451
1452     std::vector<TreePatternNode*> ResultNodeOperands;
1453     std::vector<Record*> Operands;
1454     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1455       const std::string &OpName = CGI.OperandList[i].Name;
1456       if (OpName.empty())
1457         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1458
1459       if (!InstInputsCheck.count(OpName))
1460         I->error("Operand $" + OpName +
1461                  " does not appear in the instruction pattern");
1462       TreePatternNode *InVal = InstInputsCheck[OpName];
1463       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1464       
1465       if (InVal->isLeaf() &&
1466           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1467         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1468         if (CGI.OperandList[i].Rec != InRec &&
1469             !InRec->isSubClassOf("ComplexPattern"))
1470           I->error("Operand $" + OpName + "'s register class disagrees"
1471                    " between the operand and pattern");
1472       }
1473       Operands.push_back(CGI.OperandList[i].Rec);
1474       
1475       // Construct the result for the dest-pattern operand list.
1476       TreePatternNode *OpNode = InVal->clone();
1477       
1478       // No predicate is useful on the result.
1479       OpNode->setPredicateFn("");
1480       
1481       // Promote the xform function to be an explicit node if set.
1482       if (Record *Xform = OpNode->getTransformFn()) {
1483         OpNode->setTransformFn(0);
1484         std::vector<TreePatternNode*> Children;
1485         Children.push_back(OpNode);
1486         OpNode = new TreePatternNode(Xform, Children);
1487       }
1488       
1489       ResultNodeOperands.push_back(OpNode);
1490     }
1491     
1492     if (!InstInputsCheck.empty())
1493       I->error("Input operand $" + InstInputsCheck.begin()->first +
1494                " occurs in pattern but not in operands list!");
1495
1496     TreePatternNode *ResultPattern =
1497       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1498     // Copy fully inferred output node type to instruction result pattern.
1499     if (NumResults > 0)
1500       ResultPattern->setTypes(Res0Node->getExtTypes());
1501
1502     // Create and insert the instruction.
1503     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1504     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1505
1506     // Use a temporary tree pattern to infer all types and make sure that the
1507     // constructed result is correct.  This depends on the instruction already
1508     // being inserted into the Instructions map.
1509     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1510     Temp.InferAllTypes();
1511
1512     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1513     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1514     
1515     DEBUG(I->dump());
1516   }
1517    
1518   // If we can, convert the instructions to be patterns that are matched!
1519   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1520        E = Instructions.end(); II != E; ++II) {
1521     DAGInstruction &TheInst = II->second;
1522     TreePattern *I = TheInst.getPattern();
1523     if (I == 0) continue;  // No pattern.
1524
1525     if (I->getNumTrees() != 1) {
1526       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1527       continue;
1528     }
1529     TreePatternNode *Pattern = I->getTree(0);
1530     TreePatternNode *SrcPattern;
1531     if (Pattern->getOperator()->getName() == "set") {
1532       if (Pattern->getNumChildren() != 2)
1533         continue;  // Not a set of a single value (not handled so far)
1534
1535       SrcPattern = Pattern->getChild(1)->clone();    
1536     } else{
1537       // Not a set (store or something?)
1538       SrcPattern = Pattern;
1539     }
1540     
1541     std::string Reason;
1542     if (!SrcPattern->canPatternMatch(Reason, *this))
1543       I->error("Instruction can never match: " + Reason);
1544     
1545     Record *Instr = II->first;
1546     TreePatternNode *DstPattern = TheInst.getResultPattern();
1547     PatternsToMatch.
1548       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1549                                SrcPattern, DstPattern,
1550                                Instr->getValueAsInt("AddedComplexity")));
1551   }
1552 }
1553
1554 void DAGISelEmitter::ParsePatterns() {
1555   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1556
1557   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1558     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1559     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1560
1561     // Inline pattern fragments into it.
1562     Pattern->InlinePatternFragments();
1563     
1564     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1565     if (LI->getSize() == 0) continue;  // no pattern.
1566     
1567     // Parse the instruction.
1568     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1569     
1570     // Inline pattern fragments into it.
1571     Result->InlinePatternFragments();
1572
1573     if (Result->getNumTrees() != 1)
1574       Result->error("Cannot handle instructions producing instructions "
1575                     "with temporaries yet!");
1576     
1577     bool IterateInference;
1578     bool InferredAllPatternTypes, InferredAllResultTypes;
1579     do {
1580       // Infer as many types as possible.  If we cannot infer all of them, we
1581       // can never do anything with this pattern: report it to the user.
1582       InferredAllPatternTypes = Pattern->InferAllTypes();
1583       
1584       // Infer as many types as possible.  If we cannot infer all of them, we can
1585       // never do anything with this pattern: report it to the user.
1586       InferredAllResultTypes = Result->InferAllTypes();
1587
1588       // Apply the type of the result to the source pattern.  This helps us
1589       // resolve cases where the input type is known to be a pointer type (which
1590       // is considered resolved), but the result knows it needs to be 32- or
1591       // 64-bits.  Infer the other way for good measure.
1592       IterateInference = Pattern->getOnlyTree()->
1593         UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1594       IterateInference |= Result->getOnlyTree()->
1595         UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1596     } while (IterateInference);
1597
1598     // Verify that we inferred enough types that we can do something with the
1599     // pattern and result.  If these fire the user has to add type casts.
1600     if (!InferredAllPatternTypes)
1601       Pattern->error("Could not infer all types in pattern!");
1602     if (!InferredAllResultTypes)
1603       Result->error("Could not infer all types in pattern result!");
1604     
1605     // Validate that the input pattern is correct.
1606     {
1607       std::map<std::string, TreePatternNode*> InstInputs;
1608       std::map<std::string, TreePatternNode*> InstResults;
1609       std::vector<Record*> InstImpInputs;
1610       std::vector<Record*> InstImpResults;
1611       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1612                                   InstInputs, InstResults,
1613                                   InstImpInputs, InstImpResults);
1614     }
1615
1616     // Promote the xform function to be an explicit node if set.
1617     std::vector<TreePatternNode*> ResultNodeOperands;
1618     TreePatternNode *DstPattern = Result->getOnlyTree();
1619     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1620       TreePatternNode *OpNode = DstPattern->getChild(ii);
1621       if (Record *Xform = OpNode->getTransformFn()) {
1622         OpNode->setTransformFn(0);
1623         std::vector<TreePatternNode*> Children;
1624         Children.push_back(OpNode);
1625         OpNode = new TreePatternNode(Xform, Children);
1626       }
1627       ResultNodeOperands.push_back(OpNode);
1628     }
1629     DstPattern = Result->getOnlyTree();
1630     if (!DstPattern->isLeaf())
1631       DstPattern = new TreePatternNode(DstPattern->getOperator(),
1632                                        ResultNodeOperands);
1633     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1634     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1635     Temp.InferAllTypes();
1636
1637     std::string Reason;
1638     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1639       Pattern->error("Pattern can never match: " + Reason);
1640     
1641     PatternsToMatch.
1642       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1643                                Pattern->getOnlyTree(),
1644                                Temp.getOnlyTree(),
1645                                Patterns[i]->getValueAsInt("AddedComplexity")));
1646   }
1647 }
1648
1649 /// CombineChildVariants - Given a bunch of permutations of each child of the
1650 /// 'operator' node, put them together in all possible ways.
1651 static void CombineChildVariants(TreePatternNode *Orig, 
1652                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1653                                  std::vector<TreePatternNode*> &OutVariants,
1654                                  DAGISelEmitter &ISE) {
1655   // Make sure that each operand has at least one variant to choose from.
1656   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1657     if (ChildVariants[i].empty())
1658       return;
1659         
1660   // The end result is an all-pairs construction of the resultant pattern.
1661   std::vector<unsigned> Idxs;
1662   Idxs.resize(ChildVariants.size());
1663   bool NotDone = true;
1664   while (NotDone) {
1665     // Create the variant and add it to the output list.
1666     std::vector<TreePatternNode*> NewChildren;
1667     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1668       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1669     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1670     
1671     // Copy over properties.
1672     R->setName(Orig->getName());
1673     R->setPredicateFn(Orig->getPredicateFn());
1674     R->setTransformFn(Orig->getTransformFn());
1675     R->setTypes(Orig->getExtTypes());
1676     
1677     // If this pattern cannot every match, do not include it as a variant.
1678     std::string ErrString;
1679     if (!R->canPatternMatch(ErrString, ISE)) {
1680       delete R;
1681     } else {
1682       bool AlreadyExists = false;
1683       
1684       // Scan to see if this pattern has already been emitted.  We can get
1685       // duplication due to things like commuting:
1686       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1687       // which are the same pattern.  Ignore the dups.
1688       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1689         if (R->isIsomorphicTo(OutVariants[i])) {
1690           AlreadyExists = true;
1691           break;
1692         }
1693       
1694       if (AlreadyExists)
1695         delete R;
1696       else
1697         OutVariants.push_back(R);
1698     }
1699     
1700     // Increment indices to the next permutation.
1701     NotDone = false;
1702     // Look for something we can increment without causing a wrap-around.
1703     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1704       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1705         NotDone = true;   // Found something to increment.
1706         break;
1707       }
1708       Idxs[IdxsIdx] = 0;
1709     }
1710   }
1711 }
1712
1713 /// CombineChildVariants - A helper function for binary operators.
1714 ///
1715 static void CombineChildVariants(TreePatternNode *Orig, 
1716                                  const std::vector<TreePatternNode*> &LHS,
1717                                  const std::vector<TreePatternNode*> &RHS,
1718                                  std::vector<TreePatternNode*> &OutVariants,
1719                                  DAGISelEmitter &ISE) {
1720   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1721   ChildVariants.push_back(LHS);
1722   ChildVariants.push_back(RHS);
1723   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1724 }  
1725
1726
1727 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1728                                      std::vector<TreePatternNode *> &Children) {
1729   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1730   Record *Operator = N->getOperator();
1731   
1732   // Only permit raw nodes.
1733   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1734       N->getTransformFn()) {
1735     Children.push_back(N);
1736     return;
1737   }
1738
1739   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1740     Children.push_back(N->getChild(0));
1741   else
1742     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1743
1744   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1745     Children.push_back(N->getChild(1));
1746   else
1747     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1748 }
1749
1750 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1751 /// the (potentially recursive) pattern by using algebraic laws.
1752 ///
1753 static void GenerateVariantsOf(TreePatternNode *N,
1754                                std::vector<TreePatternNode*> &OutVariants,
1755                                DAGISelEmitter &ISE) {
1756   // We cannot permute leaves.
1757   if (N->isLeaf()) {
1758     OutVariants.push_back(N);
1759     return;
1760   }
1761
1762   // Look up interesting info about the node.
1763   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1764
1765   // If this node is associative, reassociate.
1766   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1767     // Reassociate by pulling together all of the linked operators 
1768     std::vector<TreePatternNode*> MaximalChildren;
1769     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1770
1771     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1772     // permutations.
1773     if (MaximalChildren.size() == 3) {
1774       // Find the variants of all of our maximal children.
1775       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1776       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1777       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1778       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1779       
1780       // There are only two ways we can permute the tree:
1781       //   (A op B) op C    and    A op (B op C)
1782       // Within these forms, we can also permute A/B/C.
1783       
1784       // Generate legal pair permutations of A/B/C.
1785       std::vector<TreePatternNode*> ABVariants;
1786       std::vector<TreePatternNode*> BAVariants;
1787       std::vector<TreePatternNode*> ACVariants;
1788       std::vector<TreePatternNode*> CAVariants;
1789       std::vector<TreePatternNode*> BCVariants;
1790       std::vector<TreePatternNode*> CBVariants;
1791       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1792       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1793       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1794       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1795       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1796       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1797
1798       // Combine those into the result: (x op x) op x
1799       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1800       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1801       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1802       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1803       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1804       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1805
1806       // Combine those into the result: x op (x op x)
1807       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1808       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1809       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1810       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1811       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1812       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1813       return;
1814     }
1815   }
1816   
1817   // Compute permutations of all children.
1818   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1819   ChildVariants.resize(N->getNumChildren());
1820   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1821     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1822
1823   // Build all permutations based on how the children were formed.
1824   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1825
1826   // If this node is commutative, consider the commuted order.
1827   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1828     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1829     // Consider the commuted order.
1830     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1831                          OutVariants, ISE);
1832   }
1833 }
1834
1835
1836 // GenerateVariants - Generate variants.  For example, commutative patterns can
1837 // match multiple ways.  Add them to PatternsToMatch as well.
1838 void DAGISelEmitter::GenerateVariants() {
1839   
1840   DEBUG(std::cerr << "Generating instruction variants.\n");
1841   
1842   // Loop over all of the patterns we've collected, checking to see if we can
1843   // generate variants of the instruction, through the exploitation of
1844   // identities.  This permits the target to provide agressive matching without
1845   // the .td file having to contain tons of variants of instructions.
1846   //
1847   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1848   // intentionally do not reconsider these.  Any variants of added patterns have
1849   // already been added.
1850   //
1851   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1852     std::vector<TreePatternNode*> Variants;
1853     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1854
1855     assert(!Variants.empty() && "Must create at least original variant!");
1856     Variants.erase(Variants.begin());  // Remove the original pattern.
1857
1858     if (Variants.empty())  // No variants for this pattern.
1859       continue;
1860
1861     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1862           PatternsToMatch[i].getSrcPattern()->dump();
1863           std::cerr << "\n");
1864
1865     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1866       TreePatternNode *Variant = Variants[v];
1867
1868       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1869             Variant->dump();
1870             std::cerr << "\n");
1871       
1872       // Scan to see if an instruction or explicit pattern already matches this.
1873       bool AlreadyExists = false;
1874       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1875         // Check to see if this variant already exists.
1876         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1877           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1878           AlreadyExists = true;
1879           break;
1880         }
1881       }
1882       // If we already have it, ignore the variant.
1883       if (AlreadyExists) continue;
1884
1885       // Otherwise, add it to the list of patterns we have.
1886       PatternsToMatch.
1887         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1888                                  Variant, PatternsToMatch[i].getDstPattern(),
1889                                  PatternsToMatch[i].getAddedComplexity()));
1890     }
1891
1892     DEBUG(std::cerr << "\n");
1893   }
1894 }
1895
1896
1897 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1898 // ComplexPattern.
1899 static bool NodeIsComplexPattern(TreePatternNode *N)
1900 {
1901   return (N->isLeaf() &&
1902           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1903           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1904           isSubClassOf("ComplexPattern"));
1905 }
1906
1907 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1908 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1909 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1910                                                    DAGISelEmitter &ISE)
1911 {
1912   if (N->isLeaf() &&
1913       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1914       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1915       isSubClassOf("ComplexPattern")) {
1916     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1917                                   ->getDef());
1918   }
1919   return NULL;
1920 }
1921
1922 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1923 /// patterns before small ones.  This is used to determine the size of a
1924 /// pattern.
1925 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1926   assert((isExtIntegerInVTs(P->getExtTypes()) || 
1927           isExtFloatingPointInVTs(P->getExtTypes()) ||
1928           P->getExtTypeNum(0) == MVT::isVoid ||
1929           P->getExtTypeNum(0) == MVT::Flag ||
1930           P->getExtTypeNum(0) == MVT::iPTR) && 
1931          "Not a valid pattern node to size!");
1932   unsigned Size = 2;  // The node itself.
1933   // If the root node is a ConstantSDNode, increases its size.
1934   // e.g. (set R32:$dst, 0).
1935   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1936     Size++;
1937
1938   // FIXME: This is a hack to statically increase the priority of patterns
1939   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1940   // Later we can allow complexity / cost for each pattern to be (optionally)
1941   // specified. To get best possible pattern match we'll need to dynamically
1942   // calculate the complexity of all patterns a dag can potentially map to.
1943   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1944   if (AM)
1945     Size += AM->getNumOperands() * 2;
1946
1947   // If this node has some predicate function that must match, it adds to the
1948   // complexity of this node.
1949   if (!P->getPredicateFn().empty())
1950     ++Size;
1951   
1952   // Count children in the count if they are also nodes.
1953   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1954     TreePatternNode *Child = P->getChild(i);
1955     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1956       Size += getPatternSize(Child, ISE);
1957     else if (Child->isLeaf()) {
1958       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1959         Size += 3;  // Matches a ConstantSDNode (+2) and a specific value (+1).
1960       else if (NodeIsComplexPattern(Child))
1961         Size += getPatternSize(Child, ISE);
1962       else if (!Child->getPredicateFn().empty())
1963         ++Size;
1964     }
1965   }
1966   
1967   return Size;
1968 }
1969
1970 /// getResultPatternCost - Compute the number of instructions for this pattern.
1971 /// This is a temporary hack.  We should really include the instruction
1972 /// latencies in this calculation.
1973 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1974   if (P->isLeaf()) return 0;
1975   
1976   unsigned Cost = 0;
1977   Record *Op = P->getOperator();
1978   if (Op->isSubClassOf("Instruction")) {
1979     Cost++;
1980     CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1981     if (II.usesCustomDAGSchedInserter)
1982       Cost += 10;
1983   }
1984   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1985     Cost += getResultPatternCost(P->getChild(i), ISE);
1986   return Cost;
1987 }
1988
1989 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1990 // In particular, we want to match maximal patterns first and lowest cost within
1991 // a particular complexity first.
1992 struct PatternSortingPredicate {
1993   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1994   DAGISelEmitter &ISE;
1995
1996   bool operator()(PatternToMatch *LHS,
1997                   PatternToMatch *RHS) {
1998     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1999     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2000     LHSSize += LHS->getAddedComplexity();
2001     RHSSize += RHS->getAddedComplexity();
2002     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
2003     if (LHSSize < RHSSize) return false;
2004     
2005     // If the patterns have equal complexity, compare generated instruction cost
2006     return getResultPatternCost(LHS->getDstPattern(), ISE) <
2007       getResultPatternCost(RHS->getDstPattern(), ISE);
2008   }
2009 };
2010
2011 /// getRegisterValueType - Look up and return the first ValueType of specified 
2012 /// RegisterClass record
2013 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2014   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2015     return RC->getValueTypeNum(0);
2016   return MVT::Other;
2017 }
2018
2019
2020 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2021 /// type information from it.
2022 static void RemoveAllTypes(TreePatternNode *N) {
2023   N->removeTypes();
2024   if (!N->isLeaf())
2025     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2026       RemoveAllTypes(N->getChild(i));
2027 }
2028
2029 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2030   Record *N = Records.getDef(Name);
2031   if (!N || !N->isSubClassOf("SDNode")) {
2032     std::cerr << "Error getting SDNode '" << Name << "'!\n";
2033     exit(1);
2034   }
2035   return N;
2036 }
2037
2038 /// NodeHasProperty - return true if TreePatternNode has the specified
2039 /// property.
2040 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2041                             DAGISelEmitter &ISE)
2042 {
2043   if (N->isLeaf()) return false;
2044   Record *Operator = N->getOperator();
2045   if (!Operator->isSubClassOf("SDNode")) return false;
2046
2047   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2048   return NodeInfo.hasProperty(Property);
2049 }
2050
2051 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2052                                DAGISelEmitter &ISE)
2053 {
2054   if (NodeHasProperty(N, Property, ISE))
2055     return true;
2056
2057   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2058     TreePatternNode *Child = N->getChild(i);
2059     if (PatternHasProperty(Child, Property, ISE))
2060       return true;
2061   }
2062
2063   return false;
2064 }
2065
2066 class PatternCodeEmitter {
2067 private:
2068   DAGISelEmitter &ISE;
2069
2070   // Predicates.
2071   ListInit *Predicates;
2072   // Pattern cost.
2073   unsigned Cost;
2074   // Instruction selector pattern.
2075   TreePatternNode *Pattern;
2076   // Matched instruction.
2077   TreePatternNode *Instruction;
2078   
2079   // Node to name mapping
2080   std::map<std::string, std::string> VariableMap;
2081   // Node to operator mapping
2082   std::map<std::string, Record*> OperatorMap;
2083   // Names of all the folded nodes which produce chains.
2084   std::vector<std::pair<std::string, unsigned> > FoldedChains;
2085   std::set<std::string> Duplicates;
2086   /// These nodes are being marked "in-flight" so they cannot be folded.
2087   std::vector<std::string> InflightNodes;
2088
2089   /// GeneratedCode - This is the buffer that we emit code to.  The first bool
2090   /// indicates whether this is an exit predicate (something that should be
2091   /// tested, and if true, the match fails) [when true] or normal code to emit
2092   /// [when false].
2093   std::vector<std::pair<bool, std::string> > &GeneratedCode;
2094   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2095   /// the set of patterns for each top-level opcode.
2096   std::set<std::pair<bool, std::string> > &GeneratedDecl;
2097   /// TargetOpcodes - The target specific opcodes used by the resulting
2098   /// instructions.
2099   std::vector<std::string> &TargetOpcodes;
2100
2101   std::string ChainName;
2102   bool NewTF;
2103   bool DoReplace;
2104   unsigned TmpNo;
2105   unsigned OpcNo;
2106   
2107   void emitCheck(const std::string &S) {
2108     if (!S.empty())
2109       GeneratedCode.push_back(std::make_pair(true, S));
2110   }
2111   void emitCode(const std::string &S) {
2112     if (!S.empty())
2113       GeneratedCode.push_back(std::make_pair(false, S));
2114   }
2115   void emitDecl(const std::string &S, bool isSDNode=false) {
2116     assert(!S.empty() && "Invalid declaration");
2117     GeneratedDecl.insert(std::make_pair(isSDNode, S));
2118   }
2119   void emitOpcode(const std::string &Opc) {
2120     TargetOpcodes.push_back(Opc);
2121     OpcNo++;
2122   }
2123 public:
2124   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2125                      TreePatternNode *pattern, TreePatternNode *instr,
2126                      std::vector<std::pair<bool, std::string> > &gc,
2127                      std::set<std::pair<bool, std::string> > &gd,
2128                      std::vector<std::string> &to,
2129                      bool dorep)
2130   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2131     GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to),
2132     NewTF(false), DoReplace(dorep), TmpNo(0), OpcNo(0) {}
2133
2134   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2135   /// if the match fails. At this point, we already know that the opcode for N
2136   /// matches, and the SDNode for the result has the RootName specified name.
2137   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2138                      const std::string &RootName, const std::string &ParentName,
2139                      const std::string &ChainSuffix, bool &FoundChain) {
2140     bool isRoot = (P == NULL);
2141     // Emit instruction predicates. Each predicate is just a string for now.
2142     if (isRoot) {
2143       std::string PredicateCheck;
2144       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2145         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2146           Record *Def = Pred->getDef();
2147           if (!Def->isSubClassOf("Predicate")) {
2148 #ifndef NDEBUG
2149             Def->dump();
2150 #endif
2151             assert(0 && "Unknown predicate type!");
2152           }
2153           if (!PredicateCheck.empty())
2154             PredicateCheck += " || ";
2155           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2156         }
2157       }
2158       
2159       emitCheck(PredicateCheck);
2160     }
2161
2162     if (N->isLeaf()) {
2163       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2164         emitCheck("cast<ConstantSDNode>(" + RootName +
2165                   ")->getSignExtended() == " + itostr(II->getValue()));
2166         return;
2167       } else if (!NodeIsComplexPattern(N)) {
2168         assert(0 && "Cannot match this as a leaf value!");
2169         abort();
2170       }
2171     }
2172   
2173     // If this node has a name associated with it, capture it in VariableMap. If
2174     // we already saw this in the pattern, emit code to verify dagness.
2175     if (!N->getName().empty()) {
2176       std::string &VarMapEntry = VariableMap[N->getName()];
2177       if (VarMapEntry.empty()) {
2178         VarMapEntry = RootName;
2179       } else {
2180         // If we get here, this is a second reference to a specific name.  Since
2181         // we already have checked that the first reference is valid, we don't
2182         // have to recursively match it, just check that it's the same as the
2183         // previously named thing.
2184         emitCheck(VarMapEntry + " == " + RootName);
2185         return;
2186       }
2187
2188       if (!N->isLeaf())
2189         OperatorMap[N->getName()] = N->getOperator();
2190     }
2191
2192
2193     // Emit code to load the child nodes and match their contents recursively.
2194     unsigned OpNo = 0;
2195     bool NodeHasChain = NodeHasProperty   (N, SDNodeInfo::SDNPHasChain, ISE);
2196     bool HasChain     = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2197     bool HasOutFlag   = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag,  ISE);
2198     bool EmittedUseCheck = false;
2199     bool EmittedSlctedCheck = false;
2200     if (HasChain) {
2201       if (NodeHasChain)
2202         OpNo = 1;
2203       if (!isRoot) {
2204         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2205         // Not in flight?
2206         emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
2207         // Multiple uses of actual result?
2208         emitCheck(RootName + ".hasOneUse()");
2209         EmittedUseCheck = true;
2210         // hasOneUse() check is not strong enough. If the original node has
2211         // already been selected, it may have been replaced with another.
2212         for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2213           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2214                     "))");
2215         
2216         EmittedSlctedCheck = true;
2217         if (NodeHasChain) {
2218           // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2219           // has a chain use.
2220           // This a workaround for this problem:
2221           //
2222           //          [ch, r : ld]
2223           //             ^ ^
2224           //             | |
2225           //      [XX]--/   \- [flag : cmp]
2226           //       ^             ^
2227           //       |             |
2228           //       \---[br flag]-
2229           //
2230           // cmp + br should be considered as a single node as they are flagged
2231           // together. So, if the ld is folded into the cmp, the XX node in the
2232           // graph is now both an operand and a use of the ld/cmp/br node.
2233           if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2234             emitCheck(ParentName + ".Val->isOnlyUse(" +  RootName + ".Val)");
2235
2236           // If the immediate use can somehow reach this node through another
2237           // path, then can't fold it either or it will create a cycle.
2238           // e.g. In the following diagram, XX can reach ld through YY. If
2239           // ld is folded into XX, then YY is both a predecessor and a successor
2240           // of XX.
2241           //
2242           //         [ld]
2243           //         ^  ^
2244           //         |  |
2245           //        /   \---
2246           //      /        [YY]
2247           //      |         ^
2248           //     [XX]-------|
2249           const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2250           if (PInfo.getNumOperands() > 1 ||
2251               PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2252               PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2253               PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2254             if (PInfo.getNumOperands() > 1) {
2255               emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2256                         ".Val)");
2257             } else {
2258               emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2259                         "isNonImmUse(" + ParentName + ".Val, " + RootName +
2260                         ".Val))");
2261             }
2262         }
2263       }
2264
2265       if (NodeHasChain) {
2266         ChainName = "Chain" + ChainSuffix;
2267         emitDecl(ChainName);
2268         if (FoundChain) {
2269          // FIXME: temporary workaround for a common case where chain
2270          // is a TokenFactor and the previous "inner" chain is an operand.
2271           NewTF = true;
2272           emitDecl("OldTF", true);
2273           emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2274                     RootName + ".Val, Chain.Val, OldTF)).Val");
2275         } else {
2276           FoundChain = true;
2277           emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2278         }
2279       }
2280     }
2281
2282     // Don't fold any node which reads or writes a flag and has multiple uses.
2283     // FIXME: We really need to separate the concepts of flag and "glue". Those
2284     // real flag results, e.g. X86CMP output, can have multiple uses.
2285     // FIXME: If the optional incoming flag does not exist. Then it is ok to
2286     // fold it.
2287     if (!isRoot &&
2288         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2289          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2290          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2291       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2292       if (!EmittedUseCheck) {
2293         // Multiple uses of actual result?
2294         emitCheck(RootName + ".hasOneUse()");
2295       }
2296       if (!EmittedSlctedCheck)
2297         // hasOneUse() check is not strong enough. If the original node has
2298         // already been selected, it may have been replaced with another.
2299         for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2300           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2301                     "))");
2302     }
2303
2304     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2305       emitDecl(RootName + utostr(OpNo));
2306       emitCode(RootName + utostr(OpNo) + " = " +
2307                RootName + ".getOperand(" +utostr(OpNo) + ");");
2308       TreePatternNode *Child = N->getChild(i);
2309     
2310       if (!Child->isLeaf()) {
2311         // If it's not a leaf, recursively match.
2312         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2313         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2314                   CInfo.getEnumName());
2315         EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2316                       ChainSuffix + utostr(OpNo), FoundChain);
2317         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2318           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2319                                                 CInfo.getNumResults()));
2320       } else {
2321         // If this child has a name associated with it, capture it in VarMap. If
2322         // we already saw this in the pattern, emit code to verify dagness.
2323         if (!Child->getName().empty()) {
2324           std::string &VarMapEntry = VariableMap[Child->getName()];
2325           if (VarMapEntry.empty()) {
2326             VarMapEntry = RootName + utostr(OpNo);
2327           } else {
2328             // If we get here, this is a second reference to a specific name.
2329             // Since we already have checked that the first reference is valid,
2330             // we don't have to recursively match it, just check that it's the
2331             // same as the previously named thing.
2332             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2333             Duplicates.insert(RootName + utostr(OpNo));
2334             continue;
2335           }
2336         }
2337       
2338         // Handle leaves of various types.
2339         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2340           Record *LeafRec = DI->getDef();
2341           if (LeafRec->isSubClassOf("RegisterClass")) {
2342             // Handle register references.  Nothing to do here.
2343           } else if (LeafRec->isSubClassOf("Register")) {
2344             // Handle register references.
2345           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2346             // Handle complex pattern. Nothing to do here.
2347           } else if (LeafRec->getName() == "srcvalue") {
2348             // Place holder for SRCVALUE nodes. Nothing to do here.
2349           } else if (LeafRec->isSubClassOf("ValueType")) {
2350             // Make sure this is the specified value type.
2351             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2352                       ")->getVT() == MVT::" + LeafRec->getName());
2353           } else if (LeafRec->isSubClassOf("CondCode")) {
2354             // Make sure this is the specified cond code.
2355             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2356                       ")->get() == ISD::" + LeafRec->getName());
2357           } else {
2358 #ifndef NDEBUG
2359             Child->dump();
2360             std::cerr << " ";
2361 #endif
2362             assert(0 && "Unknown leaf type!");
2363           }
2364         } else if (IntInit *II =
2365                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2366           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2367           unsigned CTmp = TmpNo++;
2368           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2369                    RootName + utostr(OpNo) + ")->getSignExtended();");
2370
2371           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2372         } else {
2373 #ifndef NDEBUG
2374           Child->dump();
2375 #endif
2376           assert(0 && "Unknown leaf type!");
2377         }
2378       }
2379     }
2380
2381     // If there is a node predicate for this, emit the call.
2382     if (!N->getPredicateFn().empty())
2383       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2384   }
2385
2386   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2387   /// we actually have to build a DAG!
2388   std::pair<unsigned, unsigned>
2389   EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2390                  bool isRoot = false) {
2391     // This is something selected from the pattern we matched.
2392     if (!N->getName().empty()) {
2393       std::string &Val = VariableMap[N->getName()];
2394       assert(!Val.empty() &&
2395              "Variable referenced but not defined and not caught earlier!");
2396       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2397         // Already selected this operand, just return the tmpval.
2398         return std::make_pair(1, atoi(Val.c_str()+3));
2399       }
2400
2401       const ComplexPattern *CP;
2402       unsigned ResNo = TmpNo++;
2403       unsigned NumRes = 1;
2404       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2405         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2406         std::string CastType;
2407         switch (N->getTypeNum(0)) {
2408         default: assert(0 && "Unknown type for constant node!");
2409         case MVT::i1:  CastType = "bool"; break;
2410         case MVT::i8:  CastType = "unsigned char"; break;
2411         case MVT::i16: CastType = "unsigned short"; break;
2412         case MVT::i32: CastType = "unsigned"; break;
2413         case MVT::i64: CastType = "uint64_t"; break;
2414         }
2415         emitDecl("Tmp" + utostr(ResNo));
2416         emitCode("Tmp" + utostr(ResNo) + 
2417                  " = CurDAG->getTargetConstant(((" + CastType +
2418                  ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2419                  getEnumName(N->getTypeNum(0)) + ");");
2420       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2421         Record *Op = OperatorMap[N->getName()];
2422         // Transform ExternalSymbol to TargetExternalSymbol
2423         if (Op && Op->getName() == "externalsym") {
2424           emitDecl("Tmp" + utostr(ResNo));
2425           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2426                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2427                    Val + ")->getSymbol(), " +
2428                    getEnumName(N->getTypeNum(0)) + ");");
2429         } else {
2430           emitDecl("Tmp" + utostr(ResNo));
2431           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2432         }
2433       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2434         Record *Op = OperatorMap[N->getName()];
2435         // Transform GlobalAddress to TargetGlobalAddress
2436         if (Op && Op->getName() == "globaladdr") {
2437           emitDecl("Tmp" + utostr(ResNo));
2438           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2439                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2440                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2441                    ");");
2442         } else {
2443           emitDecl("Tmp" + utostr(ResNo));
2444           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2445         }
2446       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2447         emitDecl("Tmp" + utostr(ResNo));
2448         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2449       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2450         emitDecl("Tmp" + utostr(ResNo));
2451         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2452       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2453         std::string Fn = CP->getSelectFunc();
2454         NumRes = CP->getNumOperands();
2455         for (unsigned i = 0; i < NumRes; ++i)
2456           emitDecl("CPTmp" + utostr(i+ResNo));
2457
2458         std::string Code = "bool Match = " + Fn + "(" + Val;
2459         for (unsigned i = 0; i < NumRes; i++)
2460           Code += ", CPTmp" + utostr(i + ResNo);
2461         emitCode(Code + ");");
2462         if (InflightNodes.size()) {
2463           // Remove the in-flight nodes if the ComplexPattern does not match!
2464           emitCode("if (!Match) {");
2465           for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2466                  AE = InflightNodes.end(); AI != AE; ++AI)
2467             emitCode("  SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2468                      *AI + ".Val);");
2469           emitCode("}");
2470         }
2471
2472         emitCheck("Match");
2473
2474         for (unsigned i = 0; i < NumRes; ++i) {
2475           emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" +
2476                    utostr(i+ResNo) + ".Val);");
2477           InflightNodes.push_back("CPTmp" + utostr(i+ResNo));
2478         }
2479         for (unsigned i = 0; i < NumRes; ++i) {
2480           emitDecl("Tmp" + utostr(i+ResNo));
2481           emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
2482                    utostr(i+ResNo) + ");");
2483         }
2484
2485         TmpNo = ResNo + NumRes;
2486       } else {
2487         emitDecl("Tmp" + utostr(ResNo));
2488         // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2489         // node even if it isn't one. Don't select it.
2490         if (LikeLeaf)
2491           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2492         else {
2493           emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2494         }
2495
2496         if (isRoot && N->isLeaf()) {
2497           emitCode("Result = Tmp" + utostr(ResNo) + ";");
2498           emitCode("return;");
2499         }
2500       }
2501       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2502       // value if used multiple times by this pattern result.
2503       Val = "Tmp"+utostr(ResNo);
2504       return std::make_pair(NumRes, ResNo);
2505     }
2506     if (N->isLeaf()) {
2507       // If this is an explicit register reference, handle it.
2508       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2509         unsigned ResNo = TmpNo++;
2510         if (DI->getDef()->isSubClassOf("Register")) {
2511           emitDecl("Tmp" + utostr(ResNo));
2512           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2513                    ISE.getQualifiedName(DI->getDef()) + ", " +
2514                    getEnumName(N->getTypeNum(0)) + ");");
2515           return std::make_pair(1, ResNo);
2516         }
2517       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2518         unsigned ResNo = TmpNo++;
2519         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2520         emitDecl("Tmp" + utostr(ResNo));
2521         emitCode("Tmp" + utostr(ResNo) + 
2522                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2523                  ", " + getEnumName(N->getTypeNum(0)) + ");");
2524         return std::make_pair(1, ResNo);
2525       }
2526     
2527 #ifndef NDEBUG
2528       N->dump();
2529 #endif
2530       assert(0 && "Unknown leaf type!");
2531       return std::make_pair(1, ~0U);
2532     }
2533
2534     Record *Op = N->getOperator();
2535     if (Op->isSubClassOf("Instruction")) {
2536       const CodeGenTarget &CGT = ISE.getTargetInfo();
2537       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2538       const DAGInstruction &Inst = ISE.getInstruction(Op);
2539       TreePattern *InstPat = Inst.getPattern();
2540       TreePatternNode *InstPatNode =
2541         isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2542                : (InstPat ? InstPat->getOnlyTree() : NULL);
2543       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2544         InstPatNode = InstPatNode->getChild(1);
2545       }
2546       bool HasVarOps     = isRoot && II.hasVariableNumberOfOperands;
2547       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
2548       bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2549       bool NodeHasOptInFlag = isRoot &&
2550         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2551       bool NodeHasInFlag  = isRoot &&
2552         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2553       bool NodeHasOutFlag = HasImpResults || (isRoot &&
2554         PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2555       bool NodeHasChain = InstPatNode &&
2556         PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2557       bool InputHasChain = isRoot &&
2558         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2559
2560       if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
2561         emitDecl("InFlag");
2562       if (NodeHasOptInFlag) {
2563         // FIXME: This is ugly. We are using a SDNode* in place of a bool.
2564         emitDecl("HasInFlag", true);
2565         emitCode("HasInFlag = "
2566                  "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag) "
2567                  "? (SDNode*)1 : (SDNode*)0;");
2568       }
2569       if (HasVarOps)
2570         emitCode("std::vector<SDOperand> Ops;");
2571
2572       // How many results is this pattern expected to produce?
2573       unsigned PatResults = 0;
2574       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2575         MVT::ValueType VT = Pattern->getTypeNum(i);
2576         if (VT != MVT::isVoid && VT != MVT::Flag)
2577           PatResults++;
2578       }
2579
2580       // Determine operand emission order. Complex pattern first.
2581       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2582       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2583       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2584         TreePatternNode *Child = N->getChild(i);
2585         if (i == 0) {
2586           EmitOrder.push_back(std::make_pair(i, Child));
2587           OI = EmitOrder.begin();
2588         } else if (NodeIsComplexPattern(Child)) {
2589           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2590         } else {
2591           EmitOrder.push_back(std::make_pair(i, Child));
2592         }
2593       }
2594
2595       // Make sure these operands which would be selected won't be folded while
2596       // the isel traverses the DAG upward.
2597       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2598         TreePatternNode *Child = EmitOrder[i].second;
2599         if (!Child->getName().empty()) {
2600           std::string &Val = VariableMap[Child->getName()];
2601           assert(!Val.empty() &&
2602                  "Variable referenced but not defined and not caught earlier!");
2603           if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2604             emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " +
2605                      Val + ".Val);");
2606             InflightNodes.push_back(Val);
2607           }
2608         }
2609       }
2610
2611       // Emit all of the operands.
2612       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2613       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2614         unsigned OpOrder       = EmitOrder[i].first;
2615         TreePatternNode *Child = EmitOrder[i].second;
2616         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2617         NumTemps[OpOrder] = NumTemp;
2618       }
2619
2620       // List all the operands in the right order.
2621       std::vector<unsigned> Ops;
2622       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2623         for (unsigned j = 0; j < NumTemps[i].first; j++)
2624           Ops.push_back(NumTemps[i].second + j);
2625       }
2626
2627       // Emit all the chain and CopyToReg stuff.
2628       bool ChainEmitted = NodeHasChain;
2629       if (NodeHasChain)
2630         emitCode("Select(" + ChainName + ", " + ChainName + ");");
2631       if (NodeHasInFlag || HasImpInputs)
2632         EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2633       if (NodeHasOptInFlag) {
2634         emitCode("if (HasInFlag)");
2635         emitCode("  Select(InFlag, N.getOperand(N.getNumOperands()-1));");
2636       }
2637
2638       if (isRoot) {
2639         // The operands have been selected. Remove them from InFlightSet.
2640         for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2641                AE = InflightNodes.end(); AI != AE; ++AI)
2642           emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2643                    *AI + ".Val);");
2644       }
2645
2646       unsigned NumResults = Inst.getNumResults();    
2647       unsigned ResNo = TmpNo++;
2648       if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2649           NodeHasOptInFlag) {
2650         std::string Code;
2651         std::string Code2;
2652         std::string NodeName;
2653         if (!isRoot) {
2654           NodeName = "Tmp" + utostr(ResNo);
2655           emitDecl(NodeName);
2656           Code2 = NodeName + " = SDOperand(";
2657         } else {
2658           NodeName = "ResNode";
2659           emitDecl(NodeName, true);
2660           Code2 = NodeName + " = ";
2661         }
2662         Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2663         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2664
2665         // Output order: results, chain, flags
2666         // Result types.
2667         if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2668           Code += ", " + getEnumName(N->getTypeNum(0));
2669         if (NodeHasChain)
2670           Code += ", MVT::Other";
2671         if (NodeHasOutFlag)
2672           Code += ", MVT::Flag";
2673
2674         // Inputs.
2675         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2676           if (HasVarOps)
2677             emitCode("Ops.push_back(Tmp" + utostr(Ops[i]) + ");");
2678           else
2679             Code += ", Tmp" + utostr(Ops[i]);
2680         }
2681
2682         if (HasVarOps) {
2683           if (NodeHasInFlag || HasImpInputs)
2684             emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2685                      "i != e; ++i) {");
2686           else if (NodeHasOptInFlag) 
2687             emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2688                      "(HasInFlag?1:0); i != e; ++i) {");
2689           else
2690             emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2691                      "i != e; ++i) {");
2692           emitCode("  SDOperand VarOp(0, 0);");
2693           emitCode("  Select(VarOp, N.getOperand(i));");
2694           emitCode("  Ops.push_back(VarOp);");
2695           emitCode("}");
2696         }
2697
2698         if (NodeHasChain) {
2699           if (HasVarOps)
2700             emitCode("Ops.push_back(" + ChainName + ");");
2701           else
2702             Code += ", " + ChainName;
2703         }
2704         if (NodeHasInFlag || HasImpInputs) {
2705           if (HasVarOps)
2706             emitCode("Ops.push_back(InFlag);");
2707           else
2708             Code += ", InFlag";
2709         } else if (NodeHasOptInFlag && HasVarOps) {
2710           emitCode("if (HasInFlag)");
2711           emitCode("  Ops.push_back(InFlag);");
2712         }
2713
2714         if (HasVarOps)
2715           Code += ", Ops";
2716         else if (NodeHasOptInFlag)
2717           Code = "HasInFlag ? " + Code + ", InFlag) : " + Code;
2718
2719         if (!isRoot)
2720           Code += "), 0";
2721         emitCode(Code2 + Code + ");");
2722
2723         if (NodeHasChain)
2724           // Remember which op produces the chain.
2725           if (!isRoot)
2726             emitCode(ChainName + " = SDOperand(" + NodeName +
2727                      ".Val, " + utostr(PatResults) + ");");
2728           else
2729             emitCode(ChainName + " = SDOperand(" + NodeName +
2730                      ", " + utostr(PatResults) + ");");
2731
2732         if (!isRoot)
2733           return std::make_pair(1, ResNo);
2734
2735         if (NewTF)
2736           emitCode("if (OldTF) "
2737                    "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2738                    ChainName + ".Val, 0);");
2739
2740         for (unsigned i = 0; i < NumResults; i++)
2741           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2742                    utostr(i) + ", ResNode, " + utostr(i) + ");");
2743
2744         if (NodeHasOutFlag)
2745           emitCode("InFlag = SDOperand(ResNode, " + 
2746                    utostr(NumResults + (unsigned)NodeHasChain) + ");");
2747
2748         if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2749           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2750                    "0, ResNode, 0);");
2751           NumResults = 1;
2752         }
2753
2754         if (InputHasChain) {
2755           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + 
2756                    utostr(PatResults) + ", " + ChainName + ".Val, " +
2757                    ChainName + ".ResNo" + ");");
2758           if (DoReplace)
2759             emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2760                      utostr(PatResults) + ", " + ChainName + ".Val, " +
2761                      ChainName + ".ResNo" + ");");
2762         }
2763
2764         if (FoldedChains.size() > 0) {
2765           std::string Code;
2766           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2767             emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2768                      FoldedChains[j].first + ".Val, " + 
2769                      utostr(FoldedChains[j].second) + ", ResNode, " +
2770                      utostr(NumResults) + ");");
2771
2772           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2773             std::string Code =
2774               FoldedChains[j].first + ".Val, " +
2775               utostr(FoldedChains[j].second) + ", ";
2776             emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2777                      utostr(NumResults) + ");");
2778           }
2779         }
2780
2781         if (NodeHasOutFlag)
2782           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2783                    utostr(PatResults + (unsigned)InputHasChain) +
2784                    ", InFlag.Val, InFlag.ResNo);");
2785
2786         // User does not expect the instruction would produce a chain!
2787         bool AddedChain = NodeHasChain && !InputHasChain;
2788         if (AddedChain && NodeHasOutFlag) {
2789           if (PatResults == 0) {
2790             emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2791           } else {
2792             emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2793             emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2794             emitCode("else");
2795             emitCode("  Result = SDOperand(ResNode, N.ResNo+1);");
2796           }
2797         } else if (InputHasChain && !NodeHasChain) {
2798           // One of the inner node produces a chain.
2799           emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2800           emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2801           if (NodeHasOutFlag) {
2802             emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2803             emitCode("  Result = SDOperand(ResNode, N.ResNo-1);");
2804           }
2805           emitCode("else");
2806           emitCode("  Result = SDOperand(" + ChainName + ".Val, " +
2807                    ChainName + ".ResNo);");
2808         } else {
2809           emitCode("Result = SDOperand(ResNode, N.ResNo);");
2810         }
2811       } else {
2812         // If this instruction is the root, and if there is only one use of it,
2813         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2814         emitCode("if (N.Val->hasOneUse()) {");
2815         std::string Code = "  Result = CurDAG->SelectNodeTo(N.Val, Opc" +
2816           utostr(OpcNo);
2817         if (N->getTypeNum(0) != MVT::isVoid)
2818           Code += ", " + getEnumName(N->getTypeNum(0));
2819         if (NodeHasOutFlag)
2820           Code += ", MVT::Flag";
2821         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2822           Code += ", Tmp" + utostr(Ops[i]);
2823         if (NodeHasInFlag || HasImpInputs)
2824           Code += ", InFlag";
2825         emitCode(Code + ");");
2826         emitCode("} else {");
2827         emitDecl("ResNode", true);
2828         Code = "  ResNode = CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2829         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2830         if (N->getTypeNum(0) != MVT::isVoid)
2831           Code += ", " + getEnumName(N->getTypeNum(0));
2832         if (NodeHasOutFlag)
2833           Code += ", MVT::Flag";
2834         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2835           Code += ", Tmp" + utostr(Ops[i]);
2836         if (NodeHasInFlag || HasImpInputs)
2837           Code += ", InFlag";
2838         emitCode(Code + ");");
2839         emitCode("  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo"
2840                  ", ResNode, 0);");
2841         emitCode("  Result = SDOperand(ResNode, 0);");
2842         emitCode("}");
2843       }
2844
2845       if (isRoot)
2846         emitCode("return;");
2847       return std::make_pair(1, ResNo);
2848     } else if (Op->isSubClassOf("SDNodeXForm")) {
2849       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2850       // PatLeaf node - the operand may or may not be a leaf node. But it should
2851       // behave like one.
2852       unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2853       unsigned ResNo = TmpNo++;
2854       emitDecl("Tmp" + utostr(ResNo));
2855       emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2856                + "(Tmp" + utostr(OpVal) + ".Val);");
2857       if (isRoot) {
2858         emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2859                  "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2860                  utostr(ResNo) + ".ResNo);");
2861         emitCode("Result = Tmp" + utostr(ResNo) + ";");
2862         emitCode("return;");
2863       }
2864       return std::make_pair(1, ResNo);
2865     } else {
2866       N->dump();
2867       std::cerr << "\n";
2868       throw std::string("Unknown node in result pattern!");
2869     }
2870   }
2871
2872   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2873   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2874   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2875   /// for, this returns true otherwise false if Pat has all types.
2876   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2877                           const std::string &Prefix) {
2878     // Did we find one?
2879     if (Pat->getExtTypes() != Other->getExtTypes()) {
2880       // Move a type over from 'other' to 'pat'.
2881       Pat->setTypes(Other->getExtTypes());
2882       emitCheck(Prefix + ".Val->getValueType(0) == " +
2883                 getName(Pat->getTypeNum(0)));
2884       return true;
2885     }
2886   
2887     unsigned OpNo =
2888       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2889     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2890       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2891                              Prefix + utostr(OpNo)))
2892         return true;
2893     return false;
2894   }
2895
2896 private:
2897   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2898   /// being built.
2899   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2900                             bool &ChainEmitted, bool isRoot = false) {
2901     const CodeGenTarget &T = ISE.getTargetInfo();
2902     unsigned OpNo =
2903       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2904     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2905     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2906       TreePatternNode *Child = N->getChild(i);
2907       if (!Child->isLeaf()) {
2908         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2909       } else {
2910         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2911           if (!Child->getName().empty()) {
2912             std::string Name = RootName + utostr(OpNo);
2913             if (Duplicates.find(Name) != Duplicates.end())
2914               // A duplicate! Do not emit a copy for this node.
2915               continue;
2916           }
2917
2918           Record *RR = DI->getDef();
2919           if (RR->isSubClassOf("Register")) {
2920             MVT::ValueType RVT = getRegisterValueType(RR, T);
2921             if (RVT == MVT::Flag) {
2922               emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2923             } else {
2924               if (!ChainEmitted) {
2925                 emitDecl("Chain");
2926                 emitCode("Chain = CurDAG->getEntryNode();");
2927                 ChainName = "Chain";
2928                 ChainEmitted = true;
2929               }
2930               emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2931                        RootName + utostr(OpNo) + ");");
2932               emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2933                        ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2934                        ", " + getEnumName(RVT) + "), " +
2935                        RootName + utostr(OpNo) + ", InFlag).Val;");
2936               emitCode(ChainName + " = SDOperand(ResNode, 0);");
2937               emitCode("InFlag = SDOperand(ResNode, 1);");
2938             }
2939           }
2940         }
2941       }
2942     }
2943
2944     if (HasInFlag)
2945       emitCode("Select(InFlag, " + RootName +
2946                ".getOperand(" + utostr(OpNo) + "));");
2947   }
2948
2949   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2950   /// as specified by the instruction. It returns true if any copy is
2951   /// emitted.
2952   bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2953     bool RetVal = false;
2954     Record *Op = N->getOperator();
2955     if (Op->isSubClassOf("Instruction")) {
2956       const DAGInstruction &Inst = ISE.getInstruction(Op);
2957       const CodeGenTarget &CGT = ISE.getTargetInfo();
2958       unsigned NumImpResults  = Inst.getNumImpResults();
2959       for (unsigned i = 0; i < NumImpResults; i++) {
2960         Record *RR = Inst.getImpResult(i);
2961         if (RR->isSubClassOf("Register")) {
2962           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2963           if (RVT != MVT::Flag) {
2964             if (!ChainEmitted) {
2965               emitDecl("Chain");
2966               emitCode("Chain = CurDAG->getEntryNode();");
2967               ChainEmitted = true;
2968               ChainName = "Chain";
2969             }
2970             emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName +
2971                      ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2972                      ", InFlag).Val;");
2973             emitCode(ChainName + " = SDOperand(ResNode, 1);");
2974             emitCode("InFlag = SDOperand(ResNode, 2);");
2975             RetVal = true;
2976           }
2977         }
2978       }
2979     }
2980     return RetVal;
2981   }
2982 };
2983
2984 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2985 /// stream to match the pattern, and generate the code for the match if it
2986 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2987 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2988                       std::vector<std::pair<bool, std::string> > &GeneratedCode,
2989                          std::set<std::pair<bool, std::string> > &GeneratedDecl,
2990                                         std::vector<std::string> &TargetOpcodes,
2991                                             bool DoReplace) {
2992   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2993                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2994                              GeneratedCode, GeneratedDecl, TargetOpcodes,
2995                              DoReplace);
2996
2997   // Emit the matcher, capturing named arguments in VariableMap.
2998   bool FoundChain = false;
2999   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
3000
3001   // TP - Get *SOME* tree pattern, we don't care which.
3002   TreePattern &TP = *PatternFragments.begin()->second;
3003   
3004   // At this point, we know that we structurally match the pattern, but the
3005   // types of the nodes may not match.  Figure out the fewest number of type 
3006   // comparisons we need to emit.  For example, if there is only one integer
3007   // type supported by a target, there should be no type comparisons at all for
3008   // integer patterns!
3009   //
3010   // To figure out the fewest number of type checks needed, clone the pattern,
3011   // remove the types, then perform type inference on the pattern as a whole.
3012   // If there are unresolved types, emit an explicit check for those types,
3013   // apply the type to the tree, then rerun type inference.  Iterate until all
3014   // types are resolved.
3015   //
3016   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3017   RemoveAllTypes(Pat);
3018   
3019   do {
3020     // Resolve/propagate as many types as possible.
3021     try {
3022       bool MadeChange = true;
3023       while (MadeChange)
3024         MadeChange = Pat->ApplyTypeConstraints(TP,
3025                                                true/*Ignore reg constraints*/);
3026     } catch (...) {
3027       assert(0 && "Error: could not find consistent types for something we"
3028              " already decided was ok!");
3029       abort();
3030     }
3031
3032     // Insert a check for an unresolved type and add it to the tree.  If we find
3033     // an unresolved type to add a check for, this returns true and we iterate,
3034     // otherwise we are done.
3035   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
3036
3037   Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
3038   delete Pat;
3039 }
3040
3041 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
3042 /// a line causes any of them to be empty, remove them and return true when
3043 /// done.
3044 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
3045                           std::vector<std::pair<bool, std::string> > > >
3046                           &Patterns) {
3047   bool ErasedPatterns = false;
3048   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3049     Patterns[i].second.pop_back();
3050     if (Patterns[i].second.empty()) {
3051       Patterns.erase(Patterns.begin()+i);
3052       --i; --e;
3053       ErasedPatterns = true;
3054     }
3055   }
3056   return ErasedPatterns;
3057 }
3058
3059 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3060 /// code together between the patterns.
3061 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
3062                                   std::vector<std::pair<bool, std::string> > > >
3063                                   &Patterns, unsigned Indent,
3064                                   std::ostream &OS) {
3065   typedef std::pair<bool, std::string> CodeLine;
3066   typedef std::vector<CodeLine> CodeList;
3067   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3068   
3069   if (Patterns.empty()) return;
3070   
3071   // Figure out how many patterns share the next code line.  Explicitly copy
3072   // FirstCodeLine so that we don't invalidate a reference when changing
3073   // Patterns.
3074   const CodeLine FirstCodeLine = Patterns.back().second.back();
3075   unsigned LastMatch = Patterns.size()-1;
3076   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3077     --LastMatch;
3078   
3079   // If not all patterns share this line, split the list into two pieces.  The
3080   // first chunk will use this line, the second chunk won't.
3081   if (LastMatch != 0) {
3082     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3083     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3084     
3085     // FIXME: Emit braces?
3086     if (Shared.size() == 1) {
3087       PatternToMatch &Pattern = *Shared.back().first;
3088       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3089       Pattern.getSrcPattern()->print(OS);
3090       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3091       Pattern.getDstPattern()->print(OS);
3092       OS << "\n";
3093       unsigned AddedComplexity = Pattern.getAddedComplexity();
3094       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3095          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3096          << "  cost = "
3097          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3098     }
3099     if (!FirstCodeLine.first) {
3100       OS << std::string(Indent, ' ') << "{\n";
3101       Indent += 2;
3102     }
3103     EmitPatterns(Shared, Indent, OS);
3104     if (!FirstCodeLine.first) {
3105       Indent -= 2;
3106       OS << std::string(Indent, ' ') << "}\n";
3107     }
3108     
3109     if (Other.size() == 1) {
3110       PatternToMatch &Pattern = *Other.back().first;
3111       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3112       Pattern.getSrcPattern()->print(OS);
3113       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3114       Pattern.getDstPattern()->print(OS);
3115       OS << "\n";
3116       unsigned AddedComplexity = Pattern.getAddedComplexity();
3117       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3118          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3119          << "  cost = "
3120          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
3121     }
3122     EmitPatterns(Other, Indent, OS);
3123     return;
3124   }
3125   
3126   // Remove this code from all of the patterns that share it.
3127   bool ErasedPatterns = EraseCodeLine(Patterns);
3128   
3129   bool isPredicate = FirstCodeLine.first;
3130   
3131   // Otherwise, every pattern in the list has this line.  Emit it.
3132   if (!isPredicate) {
3133     // Normal code.
3134     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3135   } else {
3136     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3137     
3138     // If the next code line is another predicate, and if all of the pattern
3139     // in this group share the same next line, emit it inline now.  Do this
3140     // until we run out of common predicates.
3141     while (!ErasedPatterns && Patterns.back().second.back().first) {
3142       // Check that all of fhe patterns in Patterns end with the same predicate.
3143       bool AllEndWithSamePredicate = true;
3144       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3145         if (Patterns[i].second.back() != Patterns.back().second.back()) {
3146           AllEndWithSamePredicate = false;
3147           break;
3148         }
3149       // If all of the predicates aren't the same, we can't share them.
3150       if (!AllEndWithSamePredicate) break;
3151       
3152       // Otherwise we can.  Emit it shared now.
3153       OS << " &&\n" << std::string(Indent+4, ' ')
3154          << Patterns.back().second.back().second;
3155       ErasedPatterns = EraseCodeLine(Patterns);
3156     }
3157     
3158     OS << ") {\n";
3159     Indent += 2;
3160   }
3161   
3162   EmitPatterns(Patterns, Indent, OS);
3163   
3164   if (isPredicate)
3165     OS << std::string(Indent-2, ' ') << "}\n";
3166 }
3167
3168
3169
3170 namespace {
3171   /// CompareByRecordName - An ordering predicate that implements less-than by
3172   /// comparing the names records.
3173   struct CompareByRecordName {
3174     bool operator()(const Record *LHS, const Record *RHS) const {
3175       // Sort by name first.
3176       if (LHS->getName() < RHS->getName()) return true;
3177       // If both names are equal, sort by pointer.
3178       return LHS->getName() == RHS->getName() && LHS < RHS;
3179     }
3180   };
3181 }
3182
3183 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3184   std::string InstNS = Target.inst_begin()->second.Namespace;
3185   if (!InstNS.empty()) InstNS += "::";
3186   
3187   // Group the patterns by their top-level opcodes.
3188   std::map<Record*, std::vector<PatternToMatch*>,
3189     CompareByRecordName> PatternsByOpcode;
3190   // All unique target node emission functions.
3191   std::map<std::string, unsigned> EmitFunctions;
3192   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3193     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3194     if (!Node->isLeaf()) {
3195       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3196     } else {
3197       const ComplexPattern *CP;
3198       if (IntInit *II = 
3199           dynamic_cast<IntInit*>(Node->getLeafValue())) {
3200         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3201       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3202         std::vector<Record*> OpNodes = CP->getRootNodes();
3203         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3204           PatternsByOpcode[OpNodes[j]]
3205             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3206         }
3207       } else {
3208         std::cerr << "Unrecognized opcode '";
3209         Node->dump();
3210         std::cerr << "' on tree pattern '";
3211         std::cerr << 
3212            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3213         std::cerr << "'!\n";
3214         exit(1);
3215       }
3216     }
3217   }
3218   
3219   // Emit one Select_* method for each top-level opcode.  We do this instead of
3220   // emitting one giant switch statement to support compilers where this will
3221   // result in the recursive functions taking less stack space.
3222   for (std::map<Record*, std::vector<PatternToMatch*>,
3223        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3224        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3225     const std::string &OpName = PBOI->first->getName();
3226     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3227     bool OptSlctOrder = 
3228       (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3229        OpcodeInfo.getNumResults() > 0);
3230     std::vector<PatternToMatch*> &Patterns = PBOI->second;
3231     assert(!Patterns.empty() && "No patterns but map has entry?");
3232     
3233     // We want to emit all of the matching code now.  However, we want to emit
3234     // the matches in order of minimal cost.  Sort the patterns so the least
3235     // cost one is at the start.
3236     std::stable_sort(Patterns.begin(), Patterns.end(),
3237                      PatternSortingPredicate(*this));
3238
3239     typedef std::vector<std::pair<bool, std::string> > CodeList;
3240     typedef std::vector<std::pair<bool, std::string> >::iterator CodeListI;
3241     
3242     std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3243     std::vector<std::vector<std::string> > PatternOpcodes;
3244     std::vector<std::set<std::pair<bool, std::string> > > PatternDecls;
3245     std::set<std::pair<bool, std::string> > AllGenDecls;
3246     for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3247       CodeList GeneratedCode;
3248       std::set<std::pair<bool, std::string> > GeneratedDecl;
3249       std::vector<std::string> TargetOpcodes;
3250       GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3251                              TargetOpcodes, OptSlctOrder);
3252       for (std::set<std::pair<bool, std::string> >::iterator
3253              si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si)
3254         AllGenDecls.insert(*si);
3255       CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3256       PatternDecls.push_back(GeneratedDecl);
3257       PatternOpcodes.push_back(TargetOpcodes);
3258     }
3259     
3260     // Scan the code to see if all of the patterns are reachable and if it is
3261     // possible that the last one might not match.
3262     bool mightNotMatch = true;
3263     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3264       CodeList &GeneratedCode = CodeForPatterns[i].second;
3265       mightNotMatch = false;
3266
3267       for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3268         if (GeneratedCode[j].first) { // predicate.
3269           mightNotMatch = true;
3270           break;
3271         }
3272       }
3273       
3274       // If this pattern definitely matches, and if it isn't the last one, the
3275       // patterns after it CANNOT ever match.  Error out.
3276       if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3277         std::cerr << "Pattern '";
3278         CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3279         std::cerr << "' is impossible to select!\n";
3280         exit(1);
3281       }
3282     }
3283
3284     // Factor target node emission code (emitted by EmitResultCode) into
3285     // separate functions. Uniquing and share them among all instruction
3286     // selection routines.
3287     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3288       CodeList &GeneratedCode = CodeForPatterns[i].second;
3289       std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3290       std::set<std::pair<bool, std::string> > Decls = PatternDecls[i];
3291       int CodeSize = (int)GeneratedCode.size();
3292       int LastPred = -1;
3293       for (int j = CodeSize-1; j >= 0; --j) {
3294         if (GeneratedCode[j].first) {
3295           LastPred = j;
3296           break;
3297         }
3298       }
3299
3300       std::string CalleeDecls;
3301       std::string CalleeCode = "(SDOperand &Result, SDOperand &N";
3302       std::string CallerCode = "(Result, N";
3303       for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3304         CalleeCode += ", unsigned Opc" + utostr(j);
3305         CallerCode += ", " + TargetOpcodes[j];
3306       }
3307       for (std::set<std::pair<bool, std::string> >::iterator
3308              I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3309         std::string Name = I->second;
3310         if (I->first) {
3311           CalleeCode += ", SDNode *" + Name;
3312           CallerCode += ", " + Name;
3313         } else {
3314           CalleeCode += ", SDOperand &" + Name;
3315           CallerCode += ", " + Name;
3316         }
3317       }
3318       CallerCode += ");";
3319       CalleeCode += ") ";
3320 #ifndef _MSC_VER
3321       // Prevent emission routines from being inlined to reduce selection
3322       // routines stack frame sizes.
3323       CalleeCode += "__attribute__((noinline)) ";
3324 #endif
3325       CalleeCode += "{\n" + CalleeDecls;
3326       for (int j = LastPred+1; j < CodeSize; ++j)
3327         CalleeCode += "  " + GeneratedCode[j].second + '\n';
3328       for (int j = LastPred+1; j < CodeSize; ++j)
3329         GeneratedCode.pop_back();
3330       CalleeCode += "}\n";
3331
3332       // Uniquing the emission routines.
3333       unsigned EmitFuncNum;
3334       std::map<std::string, unsigned>::iterator EFI =
3335         EmitFunctions.find(CalleeCode);
3336       if (EFI != EmitFunctions.end()) {
3337         EmitFuncNum = EFI->second;
3338       } else {
3339         EmitFuncNum = EmitFunctions.size();
3340         EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3341         OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode;
3342       }
3343
3344       // Replace the emission code within selection routines with calls to the
3345       // emission functions.
3346       CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode;
3347       GeneratedCode.push_back(std::make_pair(false, CallerCode));
3348       GeneratedCode.push_back(std::make_pair(false, "return;"));
3349     }
3350
3351     // Print function.
3352     OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";    
3353     if (OptSlctOrder) {
3354       OS << "  if (N.ResNo == " << OpcodeInfo.getNumResults()
3355          << " && N.getValue(0).hasOneUse()) {\n"
3356          << "    SDOperand Dummy = "
3357          << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3358          << "    SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3359          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3360          << "    SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3361          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3362          << "    Result = Dummy;\n"
3363          << "    return;\n"
3364          << "  }\n";
3365     }
3366
3367     // Print all declarations.
3368     for (std::set<std::pair<bool, std::string> >::iterator
3369            I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I)
3370       if (I->first)
3371         OS << "  SDNode *" << I->second << " = NULL;\n";
3372       else
3373         OS << "  SDOperand " << I->second << "(0, 0);\n";
3374
3375     // Loop through and reverse all of the CodeList vectors, as we will be
3376     // accessing them from their logical front, but accessing the end of a
3377     // vector is more efficient.
3378     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3379       CodeList &GeneratedCode = CodeForPatterns[i].second;
3380       std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3381     }
3382     
3383     // Next, reverse the list of patterns itself for the same reason.
3384     std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3385     
3386     // Emit all of the patterns now, grouped together to share code.
3387     EmitPatterns(CodeForPatterns, 2, OS);
3388     
3389     // If the last pattern has predicates (which could fail) emit code to catch
3390     // the case where nothing handles a pattern.
3391     if (mightNotMatch) {
3392       OS << "  std::cerr << \"Cannot yet select: \";\n";
3393       if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3394           OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3395           OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3396         OS << "  N.Val->dump(CurDAG);\n";
3397       } else {
3398         OS << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
3399                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3400            << "  std::cerr << \"intrinsic %\"<< "
3401                          "Intrinsic::getName((Intrinsic::ID)iid);\n";
3402       }
3403       OS << "  std::cerr << '\\n';\n"
3404          << "  abort();\n";
3405     }
3406     OS << "}\n\n";
3407   }
3408   
3409   // Emit boilerplate.
3410   OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3411      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3412      << "  Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3413      << "  // Select the flag operand.\n"
3414      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
3415      << "    Select(Ops.back(), Ops.back());\n"
3416      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3417      << "  std::vector<MVT::ValueType> VTs;\n"
3418      << "  VTs.push_back(MVT::Other);\n"
3419      << "  VTs.push_back(MVT::Flag);\n"
3420      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3421     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3422     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3423      << "  Result = New.getValue(N.ResNo);\n"
3424      << "  return;\n"
3425      << "}\n\n";
3426   
3427   OS << "// The main instruction selector code.\n"
3428      << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3429      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3430      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3431      << "INSTRUCTION_LIST_END)) {\n"
3432      << "    Result = N;\n"
3433      << "    return;   // Already selected.\n"
3434      << "  }\n\n"
3435     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3436      << "  if (CGMI != CodeGenMap.end()) {\n"
3437      << "    Result = CGMI->second;\n"
3438      << "    return;\n"
3439      << "  }\n\n"
3440      << "  switch (N.getOpcode()) {\n"
3441      << "  default: break;\n"
3442      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
3443      << "  case ISD::BasicBlock:\n"
3444      << "  case ISD::Register:\n"
3445      << "  case ISD::HANDLENODE:\n"
3446      << "  case ISD::TargetConstant:\n"
3447      << "  case ISD::TargetConstantPool:\n"
3448      << "  case ISD::TargetFrameIndex:\n"
3449      << "  case ISD::TargetJumpTable:\n"
3450      << "  case ISD::TargetGlobalAddress: {\n"
3451      << "    Result = N;\n"
3452      << "    return;\n"
3453      << "  }\n"
3454      << "  case ISD::AssertSext:\n"
3455      << "  case ISD::AssertZext: {\n"
3456      << "    SDOperand Tmp0;\n"
3457      << "    Select(Tmp0, N.getOperand(0));\n"
3458      << "    if (!N.Val->hasOneUse())\n"
3459      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3460      << "Tmp0.Val, Tmp0.ResNo);\n"
3461      << "    Result = Tmp0;\n"
3462      << "    return;\n"
3463      << "  }\n"
3464      << "  case ISD::TokenFactor:\n"
3465      << "    if (N.getNumOperands() == 2) {\n"
3466      << "      SDOperand Op0, Op1;\n"
3467      << "      Select(Op0, N.getOperand(0));\n"
3468      << "      Select(Op1, N.getOperand(1));\n"
3469      << "      Result = \n"
3470      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3471      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3472      << "Result.Val, Result.ResNo);\n"
3473      << "    } else {\n"
3474      << "      std::vector<SDOperand> Ops;\n"
3475      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3476      << "        SDOperand Val;\n"
3477      << "        Select(Val, N.getOperand(i));\n"
3478      << "        Ops.push_back(Val);\n"
3479      << "      }\n"
3480      << "      Result = \n"
3481      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3482      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3483      << "Result.Val, Result.ResNo);\n"
3484      << "    }\n"
3485      << "    return;\n"
3486      << "  case ISD::CopyFromReg: {\n"
3487      << "    SDOperand Chain;\n"
3488      << "    Select(Chain, N.getOperand(0));\n"
3489      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3490      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
3491      << "    if (N.Val->getNumValues() == 2) {\n"
3492      << "      if (Chain == N.getOperand(0)) {\n"
3493      << "        Result = N; // No change\n"
3494      << "        return;\n"
3495      << "      }\n"
3496      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3497      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3498      << "New.Val, 0);\n"
3499      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3500      << "New.Val, 1);\n"
3501      << "      Result = New.getValue(N.ResNo);\n"
3502      << "      return;\n"
3503      << "    } else {\n"
3504      << "      SDOperand Flag;\n"
3505      << "      if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3506      << "      if (Chain == N.getOperand(0) &&\n"
3507      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3508      << "        Result = N; // No change\n"
3509      << "        return;\n"
3510      << "      }\n"
3511      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3512      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3513      << "New.Val, 0);\n"
3514      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3515      << "New.Val, 1);\n"
3516      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3517      << "New.Val, 2);\n"
3518      << "      Result = New.getValue(N.ResNo);\n"
3519      << "      return;\n"
3520      << "    }\n"
3521      << "  }\n"
3522      << "  case ISD::CopyToReg: {\n"
3523      << "    SDOperand Chain;\n"
3524      << "    Select(Chain, N.getOperand(0));\n"
3525      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3526      << "    SDOperand Val;\n"
3527      << "    Select(Val, N.getOperand(2));\n"
3528      << "    Result = N;\n"
3529      << "    if (N.Val->getNumValues() == 1) {\n"
3530      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3531      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3532      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3533      << "Result.Val, 0);\n"
3534      << "    } else {\n"
3535      << "      SDOperand Flag(0, 0);\n"
3536      << "      if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3537      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3538      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3539      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3540      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3541      << "Result.Val, 0);\n"
3542      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3543      << "Result.Val, 1);\n"
3544      << "      Result = Result.getValue(N.ResNo);\n"
3545      << "    }\n"
3546      << "    return;\n"
3547      << "  }\n"
3548      << "  case ISD::INLINEASM:  Select_INLINEASM(Result, N); return;\n";
3549
3550     
3551   // Loop over all of the case statements, emiting a call to each method we
3552   // emitted above.
3553   for (std::map<Record*, std::vector<PatternToMatch*>,
3554                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3555        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3556     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3557     OS << "  case " << OpcodeInfo.getEnumName() << ": "
3558        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3559        << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3560   }
3561
3562   OS << "  } // end of big switch.\n\n"
3563      << "  std::cerr << \"Cannot yet select: \";\n"
3564      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3565      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3566      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3567      << "    N.Val->dump(CurDAG);\n"
3568      << "  } else {\n"
3569      << "    unsigned iid = cast<ConstantSDNode>(N.getOperand("
3570                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3571      << "    std::cerr << \"intrinsic %\"<< "
3572                         "Intrinsic::getName((Intrinsic::ID)iid);\n"
3573      << "  }\n"
3574      << "  std::cerr << '\\n';\n"
3575      << "  abort();\n"
3576      << "}\n";
3577 }
3578
3579 void DAGISelEmitter::run(std::ostream &OS) {
3580   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3581                        " target", OS);
3582   
3583   OS << "// *** NOTE: This file is #included into the middle of the target\n"
3584      << "// *** instruction selector class.  These functions are really "
3585      << "methods.\n\n";
3586   
3587   OS << "// Instance var to keep track of multiply used nodes that have \n"
3588      << "// already been selected.\n"
3589      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3590
3591   OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3592      << "// and their place handle nodes.\n";
3593   OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3594   OS << "// Instance var to keep track of mapping of place handle nodes\n"
3595      << "// and their replacement nodes.\n";
3596   OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3597   OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3598      << "// should not be folded.\n";
3599   OS << "std::set<SDNode*> InFlightSet;\n";
3600
3601   OS << "\n";
3602   OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3603      << "std::set<SDNode *> &Visited) {\n";
3604   OS << "  if (found || !Visited.insert(Use).second) return;\n";
3605   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3606   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3607   OS << "    if (N != Def) {\n";
3608   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3609   OS << "    } else {\n";
3610   OS << "      found = true;\n";
3611   OS << "      break;\n";
3612   OS << "    }\n";
3613   OS << "  }\n";
3614   OS << "}\n";
3615
3616   OS << "\n";
3617   OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3618   OS << "  std::set<SDNode *> Visited;\n";
3619   OS << "  bool found = false;\n";
3620   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3621   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3622   OS << "    if (N != Def) {\n";
3623   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3624   OS << "      if (found) break;\n";
3625   OS << "    }\n";
3626   OS << "  }\n";
3627   OS << "  return found;\n";
3628   OS << "}\n";
3629
3630   OS << "\n";
3631   OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3632      << "// handle node in ReplaceMap.\n";
3633   OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3634      << "unsigned RNum) {\n";
3635   OS << "  SDOperand N(H, HNum);\n";
3636   OS << "  std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3637   OS << "  if (HMI != HandleMap.end()) {\n";
3638   OS << "    ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3639   OS << "    HandleMap.erase(N);\n";
3640   OS << "  }\n";
3641   OS << "}\n";
3642
3643   OS << "\n";
3644   OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3645   OS << "// handles.Some handles do not yet have replacements because the\n";
3646   OS << "// nodes they replacements have only dead readers.\n";
3647   OS << "void SelectDanglingHandles() {\n";
3648   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3649      << "HandleMap.begin(),\n"
3650      << "         E = HandleMap.end(); I != E; ++I) {\n";
3651   OS << "    SDOperand N = I->first;\n";
3652   OS << "    SDOperand R;\n";
3653   OS << "    Select(R, N.getValue(0));\n";
3654   OS << "    AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3655   OS << "  }\n";
3656   OS << "}\n";
3657   OS << "\n";
3658   OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3659   OS << "// specific nodes.\n";
3660   OS << "void ReplaceHandles() {\n";
3661   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3662      << "ReplaceMap.begin(),\n"
3663      << "        E = ReplaceMap.end(); I != E; ++I) {\n";
3664   OS << "    SDOperand From = I->first;\n";
3665   OS << "    SDOperand To   = I->second;\n";
3666   OS << "    for (SDNode::use_iterator UI = From.Val->use_begin(), "
3667      << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3668   OS << "      SDNode *Use = *UI;\n";
3669   OS << "      std::vector<SDOperand> Ops;\n";
3670   OS << "      for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n";
3671   OS << "        SDOperand O = Use->getOperand(i);\n";
3672   OS << "        if (O.Val == From.Val)\n";
3673   OS << "          Ops.push_back(To);\n";
3674   OS << "        else\n";
3675   OS << "          Ops.push_back(O);\n";
3676   OS << "      }\n";
3677   OS << "      SDOperand U = SDOperand(Use, 0);\n";
3678   OS << "      CurDAG->UpdateNodeOperands(U, Ops);\n";
3679   OS << "    }\n";
3680   OS << "  }\n";
3681   OS << "}\n";
3682
3683   OS << "\n";
3684   OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3685   OS << "// if the folding were to happen. This is called when, for example,\n";
3686   OS << "// a load is folded into a store. If the store's chain is the load,\n";
3687   OS << "// then the resulting node's input chain would be the load's input\n";
3688   OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3689   OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3690   OS << "// with the other operands along with the input chain of the load.\n";
3691   OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3692      << "SDNode *Chain, SDNode* &OldTF) {\n";
3693   OS << "  OldTF = NULL;\n";
3694   OS << "  if (N == Chain) {\n";
3695   OS << "    return N->getOperand(0);\n";
3696   OS << "  } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3697   OS << "             N->isOperand(Chain)) {\n";
3698   OS << "    SDOperand Ch = SDOperand(Chain, 0);\n";
3699   OS << "    std::map<SDOperand, SDOperand>::iterator CGMI = "
3700      << "CodeGenMap.find(Ch);\n";
3701   OS << "    if (CGMI != CodeGenMap.end())\n";
3702   OS << "      return SDOperand(0, 0);\n";
3703   OS << "    OldTF = Chain;\n";
3704   OS << "    std::vector<SDOperand> Ops;\n";
3705   OS << "    for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3706   OS << "      SDOperand Op = Chain->getOperand(i);\n";
3707   OS << "      if (Op.Val == N)\n";
3708   OS << "        Ops.push_back(N->getOperand(0));\n";
3709   OS << "      else\n";
3710   OS << "        Ops.push_back(Op);\n";
3711   OS << "    }\n";
3712   OS << "    return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3713   OS << "  }\n";
3714   OS << "  return SDOperand(0, 0);\n";
3715   OS << "}\n";
3716
3717   OS << "\n";
3718   OS << "// SelectRoot - Top level entry to DAG isel.\n";
3719   OS << "SDOperand SelectRoot(SDOperand N) {\n";
3720   OS << "  SDOperand ResNode;\n";
3721   OS << "  Select(ResNode, N);\n";
3722   OS << "  SelectDanglingHandles();\n";
3723   OS << "  ReplaceHandles();\n";
3724   OS << "  ReplaceMap.clear();\n";
3725   OS << "  return ResNode;\n";
3726   OS << "}\n";
3727   
3728   Intrinsics = LoadIntrinsics(Records);
3729   ParseNodeInfo();
3730   ParseNodeTransforms(OS);
3731   ParseComplexPatterns();
3732   ParsePatternFragments(OS);
3733   ParseInstructions();
3734   ParsePatterns();
3735   
3736   // Generate variants.  For example, commutative patterns can match
3737   // multiple ways.  Add them to PatternsToMatch as well.
3738   GenerateVariants();
3739
3740   
3741   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3742         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3743           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3744           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3745           std::cerr << "\n";
3746         });
3747   
3748   // At this point, we have full information about the 'Patterns' we need to
3749   // parse, both implicitly from instructions as well as from explicit pattern
3750   // definitions.  Emit the resultant instruction selector.
3751   EmitInstructionSelector(OS);  
3752   
3753   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3754        E = PatternFragments.end(); I != E; ++I)
3755     delete I->second;
3756   PatternFragments.clear();
3757
3758   Instructions.clear();
3759 }