Add result of a Xform to isel queue.
[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
746     CodeGenInstruction &InstInfo =
747       ISE.getTargetInfo().getInstruction(getOperator()->getName());
748     // Apply the result type to the node
749     if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack...
750       MadeChange = UpdateNodeType(MVT::isVoid, TP);
751     } else {
752       Record *ResultNode = Inst.getResult(0);
753       assert(ResultNode->isSubClassOf("RegisterClass") &&
754              "Operands should be register classes!");
755
756       const CodeGenRegisterClass &RC = 
757         ISE.getTargetInfo().getRegisterClass(ResultNode);
758       MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
759     }
760
761     if (getNumChildren() != Inst.getNumOperands())
762       TP.error("Instruction '" + getOperator()->getName() + " expects " +
763                utostr(Inst.getNumOperands()) + " operands, not " +
764                utostr(getNumChildren()) + " operands!");
765     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
766       Record *OperandNode = Inst.getOperand(i);
767       MVT::ValueType VT;
768       if (OperandNode->isSubClassOf("RegisterClass")) {
769         const CodeGenRegisterClass &RC = 
770           ISE.getTargetInfo().getRegisterClass(OperandNode);
771         MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
772                                                  TP);
773       } else if (OperandNode->isSubClassOf("Operand")) {
774         VT = getValueType(OperandNode->getValueAsDef("Type"));
775         MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
776       } else {
777         assert(0 && "Unknown operand type!");
778         abort();
779       }
780       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
781     }
782     return MadeChange;
783   } else {
784     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
785     
786     // Node transforms always take one operand.
787     if (getNumChildren() != 1)
788       TP.error("Node transform '" + getOperator()->getName() +
789                "' requires one operand!");
790
791     // If either the output or input of the xform does not have exact
792     // type info. We assume they must be the same. Otherwise, it is perfectly
793     // legal to transform from one type to a completely different type.
794     if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
795       bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
796       MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
797       return MadeChange;
798     }
799     return false;
800   }
801 }
802
803 /// canPatternMatch - If it is impossible for this pattern to match on this
804 /// target, fill in Reason and return false.  Otherwise, return true.  This is
805 /// used as a santity check for .td files (to prevent people from writing stuff
806 /// that can never possibly work), and to prevent the pattern permuter from
807 /// generating stuff that is useless.
808 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
809   if (isLeaf()) return true;
810
811   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
812     if (!getChild(i)->canPatternMatch(Reason, ISE))
813       return false;
814
815   // If this is an intrinsic, handle cases that would make it not match.  For
816   // example, if an operand is required to be an immediate.
817   if (getOperator()->isSubClassOf("Intrinsic")) {
818     // TODO:
819     return true;
820   }
821   
822   // If this node is a commutative operator, check that the LHS isn't an
823   // immediate.
824   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
825   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
826     // Scan all of the operands of the node and make sure that only the last one
827     // is a constant node, unless the RHS also is.
828     if (getChild(getNumChildren()-1)->isLeaf() ||
829         getChild(getNumChildren()-1)->getOperator()->getName() != "imm") {
830       for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
831         if (!getChild(i)->isLeaf() && 
832             getChild(i)->getOperator()->getName() == "imm") {
833           Reason = "Immediate value must be on the RHS of commutative operators!";
834           return false;
835         }
836     }
837   }
838   
839   return true;
840 }
841
842 //===----------------------------------------------------------------------===//
843 // TreePattern implementation
844 //
845
846 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
847                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
848    isInputPattern = isInput;
849    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
850      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
851 }
852
853 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
854                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
855   isInputPattern = isInput;
856   Trees.push_back(ParseTreePattern(Pat));
857 }
858
859 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
860                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
861   isInputPattern = isInput;
862   Trees.push_back(Pat);
863 }
864
865
866
867 void TreePattern::error(const std::string &Msg) const {
868   dump();
869   throw "In " + TheRecord->getName() + ": " + Msg;
870 }
871
872 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
873   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
874   if (!OpDef) error("Pattern has unexpected operator type!");
875   Record *Operator = OpDef->getDef();
876   
877   if (Operator->isSubClassOf("ValueType")) {
878     // If the operator is a ValueType, then this must be "type cast" of a leaf
879     // node.
880     if (Dag->getNumArgs() != 1)
881       error("Type cast only takes one operand!");
882     
883     Init *Arg = Dag->getArg(0);
884     TreePatternNode *New;
885     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
886       Record *R = DI->getDef();
887       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
888         Dag->setArg(0, new DagInit(DI,
889                                 std::vector<std::pair<Init*, std::string> >()));
890         return ParseTreePattern(Dag);
891       }
892       New = new TreePatternNode(DI);
893     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
894       New = ParseTreePattern(DI);
895     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
896       New = new TreePatternNode(II);
897       if (!Dag->getArgName(0).empty())
898         error("Constant int argument should not have a name!");
899     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
900       // Turn this into an IntInit.
901       Init *II = BI->convertInitializerTo(new IntRecTy());
902       if (II == 0 || !dynamic_cast<IntInit*>(II))
903         error("Bits value must be constants!");
904       
905       New = new TreePatternNode(dynamic_cast<IntInit*>(II));
906       if (!Dag->getArgName(0).empty())
907         error("Constant int argument should not have a name!");
908     } else {
909       Arg->dump();
910       error("Unknown leaf value for tree pattern!");
911       return 0;
912     }
913     
914     // Apply the type cast.
915     New->UpdateNodeType(getValueType(Operator), *this);
916     New->setName(Dag->getArgName(0));
917     return New;
918   }
919   
920   // Verify that this is something that makes sense for an operator.
921   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
922       !Operator->isSubClassOf("Instruction") && 
923       !Operator->isSubClassOf("SDNodeXForm") &&
924       !Operator->isSubClassOf("Intrinsic") &&
925       Operator->getName() != "set")
926     error("Unrecognized node '" + Operator->getName() + "'!");
927   
928   //  Check to see if this is something that is illegal in an input pattern.
929   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
930                          Operator->isSubClassOf("SDNodeXForm")))
931     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
932   
933   std::vector<TreePatternNode*> Children;
934   
935   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
936     Init *Arg = Dag->getArg(i);
937     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
938       Children.push_back(ParseTreePattern(DI));
939       if (Children.back()->getName().empty())
940         Children.back()->setName(Dag->getArgName(i));
941     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
942       Record *R = DefI->getDef();
943       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
944       // TreePatternNode if its own.
945       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
946         Dag->setArg(i, new DagInit(DefI,
947                               std::vector<std::pair<Init*, std::string> >()));
948         --i;  // Revisit this node...
949       } else {
950         TreePatternNode *Node = new TreePatternNode(DefI);
951         Node->setName(Dag->getArgName(i));
952         Children.push_back(Node);
953         
954         // Input argument?
955         if (R->getName() == "node") {
956           if (Dag->getArgName(i).empty())
957             error("'node' argument requires a name to match with operand list");
958           Args.push_back(Dag->getArgName(i));
959         }
960       }
961     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
962       TreePatternNode *Node = new TreePatternNode(II);
963       if (!Dag->getArgName(i).empty())
964         error("Constant int argument should not have a name!");
965       Children.push_back(Node);
966     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
967       // Turn this into an IntInit.
968       Init *II = BI->convertInitializerTo(new IntRecTy());
969       if (II == 0 || !dynamic_cast<IntInit*>(II))
970         error("Bits value must be constants!");
971       
972       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
973       if (!Dag->getArgName(i).empty())
974         error("Constant int argument should not have a name!");
975       Children.push_back(Node);
976     } else {
977       std::cerr << '"';
978       Arg->dump();
979       std::cerr << "\": ";
980       error("Unknown leaf value for tree pattern!");
981     }
982   }
983   
984   // If the operator is an intrinsic, then this is just syntactic sugar for for
985   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
986   // convert the intrinsic name to a number.
987   if (Operator->isSubClassOf("Intrinsic")) {
988     const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
989     unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
990
991     // If this intrinsic returns void, it must have side-effects and thus a
992     // chain.
993     if (Int.ArgVTs[0] == MVT::isVoid) {
994       Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
995     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
996       // Has side-effects, requires chain.
997       Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
998     } else {
999       // Otherwise, no chain.
1000       Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1001     }
1002     
1003     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1004     Children.insert(Children.begin(), IIDNode);
1005   }
1006   
1007   return new TreePatternNode(Operator, Children);
1008 }
1009
1010 /// InferAllTypes - Infer/propagate as many types throughout the expression
1011 /// patterns as possible.  Return true if all types are infered, false
1012 /// otherwise.  Throw an exception if a type contradiction is found.
1013 bool TreePattern::InferAllTypes() {
1014   bool MadeChange = true;
1015   while (MadeChange) {
1016     MadeChange = false;
1017     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1018       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1019   }
1020   
1021   bool HasUnresolvedTypes = false;
1022   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1023     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1024   return !HasUnresolvedTypes;
1025 }
1026
1027 void TreePattern::print(std::ostream &OS) const {
1028   OS << getRecord()->getName();
1029   if (!Args.empty()) {
1030     OS << "(" << Args[0];
1031     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1032       OS << ", " << Args[i];
1033     OS << ")";
1034   }
1035   OS << ": ";
1036   
1037   if (Trees.size() > 1)
1038     OS << "[\n";
1039   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1040     OS << "\t";
1041     Trees[i]->print(OS);
1042     OS << "\n";
1043   }
1044
1045   if (Trees.size() > 1)
1046     OS << "]\n";
1047 }
1048
1049 void TreePattern::dump() const { print(std::cerr); }
1050
1051
1052
1053 //===----------------------------------------------------------------------===//
1054 // DAGISelEmitter implementation
1055 //
1056
1057 // Parse all of the SDNode definitions for the target, populating SDNodes.
1058 void DAGISelEmitter::ParseNodeInfo() {
1059   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1060   while (!Nodes.empty()) {
1061     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1062     Nodes.pop_back();
1063   }
1064
1065   // Get the buildin intrinsic nodes.
1066   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1067   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1068   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1069 }
1070
1071 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1072 /// map, and emit them to the file as functions.
1073 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1074   OS << "\n// Node transformations.\n";
1075   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1076   while (!Xforms.empty()) {
1077     Record *XFormNode = Xforms.back();
1078     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1079     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1080     SDNodeXForms.insert(std::make_pair(XFormNode,
1081                                        std::make_pair(SDNode, Code)));
1082
1083     if (!Code.empty()) {
1084       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1085       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1086
1087       OS << "inline SDOperand Transform_" << XFormNode->getName()
1088          << "(SDNode *" << C2 << ") {\n";
1089       if (ClassName != "SDNode")
1090         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1091       OS << Code << "\n}\n";
1092     }
1093
1094     Xforms.pop_back();
1095   }
1096 }
1097
1098 void DAGISelEmitter::ParseComplexPatterns() {
1099   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1100   while (!AMs.empty()) {
1101     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1102     AMs.pop_back();
1103   }
1104 }
1105
1106
1107 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1108 /// file, building up the PatternFragments map.  After we've collected them all,
1109 /// inline fragments together as necessary, so that there are no references left
1110 /// inside a pattern fragment to a pattern fragment.
1111 ///
1112 /// This also emits all of the predicate functions to the output file.
1113 ///
1114 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1115   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1116   
1117   // First step, parse all of the fragments and emit predicate functions.
1118   OS << "\n// Predicate functions.\n";
1119   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1120     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1121     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1122     PatternFragments[Fragments[i]] = P;
1123     
1124     // Validate the argument list, converting it to map, to discard duplicates.
1125     std::vector<std::string> &Args = P->getArgList();
1126     std::set<std::string> OperandsMap(Args.begin(), Args.end());
1127     
1128     if (OperandsMap.count(""))
1129       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1130     
1131     // Parse the operands list.
1132     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1133     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1134     if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1135       P->error("Operands list should start with '(ops ... '!");
1136     
1137     // Copy over the arguments.       
1138     Args.clear();
1139     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1140       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1141           static_cast<DefInit*>(OpsList->getArg(j))->
1142           getDef()->getName() != "node")
1143         P->error("Operands list should all be 'node' values.");
1144       if (OpsList->getArgName(j).empty())
1145         P->error("Operands list should have names for each operand!");
1146       if (!OperandsMap.count(OpsList->getArgName(j)))
1147         P->error("'" + OpsList->getArgName(j) +
1148                  "' does not occur in pattern or was multiply specified!");
1149       OperandsMap.erase(OpsList->getArgName(j));
1150       Args.push_back(OpsList->getArgName(j));
1151     }
1152     
1153     if (!OperandsMap.empty())
1154       P->error("Operands list does not contain an entry for operand '" +
1155                *OperandsMap.begin() + "'!");
1156
1157     // If there is a code init for this fragment, emit the predicate code and
1158     // keep track of the fact that this fragment uses it.
1159     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1160     if (!Code.empty()) {
1161       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1162       std::string ClassName =
1163         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1164       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1165       
1166       OS << "inline bool Predicate_" << Fragments[i]->getName()
1167          << "(SDNode *" << C2 << ") {\n";
1168       if (ClassName != "SDNode")
1169         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1170       OS << Code << "\n}\n";
1171       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1172     }
1173     
1174     // If there is a node transformation corresponding to this, keep track of
1175     // it.
1176     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1177     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1178       P->getOnlyTree()->setTransformFn(Transform);
1179   }
1180   
1181   OS << "\n\n";
1182
1183   // Now that we've parsed all of the tree fragments, do a closure on them so
1184   // that there are not references to PatFrags left inside of them.
1185   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1186        E = PatternFragments.end(); I != E; ++I) {
1187     TreePattern *ThePat = I->second;
1188     ThePat->InlinePatternFragments();
1189         
1190     // Infer as many types as possible.  Don't worry about it if we don't infer
1191     // all of them, some may depend on the inputs of the pattern.
1192     try {
1193       ThePat->InferAllTypes();
1194     } catch (...) {
1195       // If this pattern fragment is not supported by this target (no types can
1196       // satisfy its constraints), just ignore it.  If the bogus pattern is
1197       // actually used by instructions, the type consistency error will be
1198       // reported there.
1199     }
1200     
1201     // If debugging, print out the pattern fragment result.
1202     DEBUG(ThePat->dump());
1203   }
1204 }
1205
1206 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1207 /// instruction input.  Return true if this is a real use.
1208 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1209                       std::map<std::string, TreePatternNode*> &InstInputs,
1210                       std::vector<Record*> &InstImpInputs) {
1211   // No name -> not interesting.
1212   if (Pat->getName().empty()) {
1213     if (Pat->isLeaf()) {
1214       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1215       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1216         I->error("Input " + DI->getDef()->getName() + " must be named!");
1217       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1218         InstImpInputs.push_back(DI->getDef());
1219     }
1220     return false;
1221   }
1222
1223   Record *Rec;
1224   if (Pat->isLeaf()) {
1225     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1226     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1227     Rec = DI->getDef();
1228   } else {
1229     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1230     Rec = Pat->getOperator();
1231   }
1232
1233   // SRCVALUE nodes are ignored.
1234   if (Rec->getName() == "srcvalue")
1235     return false;
1236
1237   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1238   if (!Slot) {
1239     Slot = Pat;
1240   } else {
1241     Record *SlotRec;
1242     if (Slot->isLeaf()) {
1243       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1244     } else {
1245       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1246       SlotRec = Slot->getOperator();
1247     }
1248     
1249     // Ensure that the inputs agree if we've already seen this input.
1250     if (Rec != SlotRec)
1251       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1252     if (Slot->getExtTypes() != Pat->getExtTypes())
1253       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1254   }
1255   return true;
1256 }
1257
1258 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1259 /// part of "I", the instruction), computing the set of inputs and outputs of
1260 /// the pattern.  Report errors if we see anything naughty.
1261 void DAGISelEmitter::
1262 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1263                             std::map<std::string, TreePatternNode*> &InstInputs,
1264                             std::map<std::string, TreePatternNode*>&InstResults,
1265                             std::vector<Record*> &InstImpInputs,
1266                             std::vector<Record*> &InstImpResults) {
1267   if (Pat->isLeaf()) {
1268     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1269     if (!isUse && Pat->getTransformFn())
1270       I->error("Cannot specify a transform function for a non-input value!");
1271     return;
1272   } else if (Pat->getOperator()->getName() != "set") {
1273     // If this is not a set, verify that the children nodes are not void typed,
1274     // and recurse.
1275     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1276       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1277         I->error("Cannot have void nodes inside of patterns!");
1278       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1279                                   InstImpInputs, InstImpResults);
1280     }
1281     
1282     // If this is a non-leaf node with no children, treat it basically as if
1283     // it were a leaf.  This handles nodes like (imm).
1284     bool isUse = false;
1285     if (Pat->getNumChildren() == 0)
1286       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1287     
1288     if (!isUse && Pat->getTransformFn())
1289       I->error("Cannot specify a transform function for a non-input value!");
1290     return;
1291   } 
1292   
1293   // Otherwise, this is a set, validate and collect instruction results.
1294   if (Pat->getNumChildren() == 0)
1295     I->error("set requires operands!");
1296   else if (Pat->getNumChildren() & 1)
1297     I->error("set requires an even number of operands");
1298   
1299   if (Pat->getTransformFn())
1300     I->error("Cannot specify a transform function on a set node!");
1301   
1302   // Check the set destinations.
1303   unsigned NumValues = Pat->getNumChildren()/2;
1304   for (unsigned i = 0; i != NumValues; ++i) {
1305     TreePatternNode *Dest = Pat->getChild(i);
1306     if (!Dest->isLeaf())
1307       I->error("set destination should be a register!");
1308     
1309     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1310     if (!Val)
1311       I->error("set destination should be a register!");
1312
1313     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1314       if (Dest->getName().empty())
1315         I->error("set destination must have a name!");
1316       if (InstResults.count(Dest->getName()))
1317         I->error("cannot set '" + Dest->getName() +"' multiple times");
1318       InstResults[Dest->getName()] = Dest;
1319     } else if (Val->getDef()->isSubClassOf("Register")) {
1320       InstImpResults.push_back(Val->getDef());
1321     } else {
1322       I->error("set destination should be a register!");
1323     }
1324     
1325     // Verify and collect info from the computation.
1326     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1327                                 InstInputs, InstResults,
1328                                 InstImpInputs, InstImpResults);
1329   }
1330 }
1331
1332 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1333 /// any fragments involved.  This populates the Instructions list with fully
1334 /// resolved instructions.
1335 void DAGISelEmitter::ParseInstructions() {
1336   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1337   
1338   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1339     ListInit *LI = 0;
1340     
1341     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1342       LI = Instrs[i]->getValueAsListInit("Pattern");
1343     
1344     // If there is no pattern, only collect minimal information about the
1345     // instruction for its operand list.  We have to assume that there is one
1346     // result, as we have no detailed info.
1347     if (!LI || LI->getSize() == 0) {
1348       std::vector<Record*> Results;
1349       std::vector<Record*> Operands;
1350       
1351       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1352
1353       if (InstInfo.OperandList.size() != 0) {
1354         // FIXME: temporary hack...
1355         if (InstInfo.noResults) {
1356           // These produce no results
1357           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1358             Operands.push_back(InstInfo.OperandList[j].Rec);
1359         } else {
1360           // Assume the first operand is the result.
1361           Results.push_back(InstInfo.OperandList[0].Rec);
1362       
1363           // The rest are inputs.
1364           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1365             Operands.push_back(InstInfo.OperandList[j].Rec);
1366         }
1367       }
1368       
1369       // Create and insert the instruction.
1370       std::vector<Record*> ImpResults;
1371       std::vector<Record*> ImpOperands;
1372       Instructions.insert(std::make_pair(Instrs[i], 
1373                           DAGInstruction(0, Results, Operands, ImpResults,
1374                                          ImpOperands)));
1375       continue;  // no pattern.
1376     }
1377     
1378     // Parse the instruction.
1379     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1380     // Inline pattern fragments into it.
1381     I->InlinePatternFragments();
1382     
1383     // Infer as many types as possible.  If we cannot infer all of them, we can
1384     // never do anything with this instruction pattern: report it to the user.
1385     if (!I->InferAllTypes())
1386       I->error("Could not infer all types in pattern!");
1387     
1388     // InstInputs - Keep track of all of the inputs of the instruction, along 
1389     // with the record they are declared as.
1390     std::map<std::string, TreePatternNode*> InstInputs;
1391     
1392     // InstResults - Keep track of all the virtual registers that are 'set'
1393     // in the instruction, including what reg class they are.
1394     std::map<std::string, TreePatternNode*> InstResults;
1395
1396     std::vector<Record*> InstImpInputs;
1397     std::vector<Record*> InstImpResults;
1398     
1399     // Verify that the top-level forms in the instruction are of void type, and
1400     // fill in the InstResults map.
1401     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1402       TreePatternNode *Pat = I->getTree(j);
1403       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1404         I->error("Top-level forms in instruction pattern should have"
1405                  " void types");
1406
1407       // Find inputs and outputs, and verify the structure of the uses/defs.
1408       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1409                                   InstImpInputs, InstImpResults);
1410     }
1411
1412     // Now that we have inputs and outputs of the pattern, inspect the operands
1413     // list for the instruction.  This determines the order that operands are
1414     // added to the machine instruction the node corresponds to.
1415     unsigned NumResults = InstResults.size();
1416
1417     // Parse the operands list from the (ops) list, validating it.
1418     std::vector<std::string> &Args = I->getArgList();
1419     assert(Args.empty() && "Args list should still be empty here!");
1420     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1421
1422     // Check that all of the results occur first in the list.
1423     std::vector<Record*> Results;
1424     TreePatternNode *Res0Node = NULL;
1425     for (unsigned i = 0; i != NumResults; ++i) {
1426       if (i == CGI.OperandList.size())
1427         I->error("'" + InstResults.begin()->first +
1428                  "' set but does not appear in operand list!");
1429       const std::string &OpName = CGI.OperandList[i].Name;
1430       
1431       // Check that it exists in InstResults.
1432       TreePatternNode *RNode = InstResults[OpName];
1433       if (RNode == 0)
1434         I->error("Operand $" + OpName + " does not exist in operand list!");
1435         
1436       if (i == 0)
1437         Res0Node = RNode;
1438       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1439       if (R == 0)
1440         I->error("Operand $" + OpName + " should be a set destination: all "
1441                  "outputs must occur before inputs in operand list!");
1442       
1443       if (CGI.OperandList[i].Rec != R)
1444         I->error("Operand $" + OpName + " class mismatch!");
1445       
1446       // Remember the return type.
1447       Results.push_back(CGI.OperandList[i].Rec);
1448       
1449       // Okay, this one checks out.
1450       InstResults.erase(OpName);
1451     }
1452
1453     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1454     // the copy while we're checking the inputs.
1455     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1456
1457     std::vector<TreePatternNode*> ResultNodeOperands;
1458     std::vector<Record*> Operands;
1459     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1460       const std::string &OpName = CGI.OperandList[i].Name;
1461       if (OpName.empty())
1462         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1463
1464       if (!InstInputsCheck.count(OpName))
1465         I->error("Operand $" + OpName +
1466                  " does not appear in the instruction pattern");
1467       TreePatternNode *InVal = InstInputsCheck[OpName];
1468       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1469       
1470       if (InVal->isLeaf() &&
1471           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1472         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1473         if (CGI.OperandList[i].Rec != InRec &&
1474             !InRec->isSubClassOf("ComplexPattern"))
1475           I->error("Operand $" + OpName + "'s register class disagrees"
1476                    " between the operand and pattern");
1477       }
1478       Operands.push_back(CGI.OperandList[i].Rec);
1479       
1480       // Construct the result for the dest-pattern operand list.
1481       TreePatternNode *OpNode = InVal->clone();
1482       
1483       // No predicate is useful on the result.
1484       OpNode->setPredicateFn("");
1485       
1486       // Promote the xform function to be an explicit node if set.
1487       if (Record *Xform = OpNode->getTransformFn()) {
1488         OpNode->setTransformFn(0);
1489         std::vector<TreePatternNode*> Children;
1490         Children.push_back(OpNode);
1491         OpNode = new TreePatternNode(Xform, Children);
1492       }
1493       
1494       ResultNodeOperands.push_back(OpNode);
1495     }
1496     
1497     if (!InstInputsCheck.empty())
1498       I->error("Input operand $" + InstInputsCheck.begin()->first +
1499                " occurs in pattern but not in operands list!");
1500
1501     TreePatternNode *ResultPattern =
1502       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1503     // Copy fully inferred output node type to instruction result pattern.
1504     if (NumResults > 0)
1505       ResultPattern->setTypes(Res0Node->getExtTypes());
1506
1507     // Create and insert the instruction.
1508     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1509     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1510
1511     // Use a temporary tree pattern to infer all types and make sure that the
1512     // constructed result is correct.  This depends on the instruction already
1513     // being inserted into the Instructions map.
1514     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1515     Temp.InferAllTypes();
1516
1517     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1518     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1519     
1520     DEBUG(I->dump());
1521   }
1522    
1523   // If we can, convert the instructions to be patterns that are matched!
1524   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1525        E = Instructions.end(); II != E; ++II) {
1526     DAGInstruction &TheInst = II->second;
1527     TreePattern *I = TheInst.getPattern();
1528     if (I == 0) continue;  // No pattern.
1529
1530     if (I->getNumTrees() != 1) {
1531       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1532       continue;
1533     }
1534     TreePatternNode *Pattern = I->getTree(0);
1535     TreePatternNode *SrcPattern;
1536     if (Pattern->getOperator()->getName() == "set") {
1537       if (Pattern->getNumChildren() != 2)
1538         continue;  // Not a set of a single value (not handled so far)
1539
1540       SrcPattern = Pattern->getChild(1)->clone();    
1541     } else{
1542       // Not a set (store or something?)
1543       SrcPattern = Pattern;
1544     }
1545     
1546     std::string Reason;
1547     if (!SrcPattern->canPatternMatch(Reason, *this))
1548       I->error("Instruction can never match: " + Reason);
1549     
1550     Record *Instr = II->first;
1551     TreePatternNode *DstPattern = TheInst.getResultPattern();
1552     PatternsToMatch.
1553       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1554                                SrcPattern, DstPattern,
1555                                Instr->getValueAsInt("AddedComplexity")));
1556   }
1557 }
1558
1559 void DAGISelEmitter::ParsePatterns() {
1560   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1561
1562   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1563     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1564     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1565
1566     // Inline pattern fragments into it.
1567     Pattern->InlinePatternFragments();
1568     
1569     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1570     if (LI->getSize() == 0) continue;  // no pattern.
1571     
1572     // Parse the instruction.
1573     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1574     
1575     // Inline pattern fragments into it.
1576     Result->InlinePatternFragments();
1577
1578     if (Result->getNumTrees() != 1)
1579       Result->error("Cannot handle instructions producing instructions "
1580                     "with temporaries yet!");
1581     
1582     bool IterateInference;
1583     bool InferredAllPatternTypes, InferredAllResultTypes;
1584     do {
1585       // Infer as many types as possible.  If we cannot infer all of them, we
1586       // can never do anything with this pattern: report it to the user.
1587       InferredAllPatternTypes = Pattern->InferAllTypes();
1588       
1589       // Infer as many types as possible.  If we cannot infer all of them, we can
1590       // never do anything with this pattern: report it to the user.
1591       InferredAllResultTypes = Result->InferAllTypes();
1592
1593       // Apply the type of the result to the source pattern.  This helps us
1594       // resolve cases where the input type is known to be a pointer type (which
1595       // is considered resolved), but the result knows it needs to be 32- or
1596       // 64-bits.  Infer the other way for good measure.
1597       IterateInference = Pattern->getOnlyTree()->
1598         UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1599       IterateInference |= Result->getOnlyTree()->
1600         UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1601     } while (IterateInference);
1602
1603     // Verify that we inferred enough types that we can do something with the
1604     // pattern and result.  If these fire the user has to add type casts.
1605     if (!InferredAllPatternTypes)
1606       Pattern->error("Could not infer all types in pattern!");
1607     if (!InferredAllResultTypes)
1608       Result->error("Could not infer all types in pattern result!");
1609     
1610     // Validate that the input pattern is correct.
1611     {
1612       std::map<std::string, TreePatternNode*> InstInputs;
1613       std::map<std::string, TreePatternNode*> InstResults;
1614       std::vector<Record*> InstImpInputs;
1615       std::vector<Record*> InstImpResults;
1616       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1617                                   InstInputs, InstResults,
1618                                   InstImpInputs, InstImpResults);
1619     }
1620
1621     // Promote the xform function to be an explicit node if set.
1622     std::vector<TreePatternNode*> ResultNodeOperands;
1623     TreePatternNode *DstPattern = Result->getOnlyTree();
1624     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1625       TreePatternNode *OpNode = DstPattern->getChild(ii);
1626       if (Record *Xform = OpNode->getTransformFn()) {
1627         OpNode->setTransformFn(0);
1628         std::vector<TreePatternNode*> Children;
1629         Children.push_back(OpNode);
1630         OpNode = new TreePatternNode(Xform, Children);
1631       }
1632       ResultNodeOperands.push_back(OpNode);
1633     }
1634     DstPattern = Result->getOnlyTree();
1635     if (!DstPattern->isLeaf())
1636       DstPattern = new TreePatternNode(DstPattern->getOperator(),
1637                                        ResultNodeOperands);
1638     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1639     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1640     Temp.InferAllTypes();
1641
1642     std::string Reason;
1643     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1644       Pattern->error("Pattern can never match: " + Reason);
1645     
1646     PatternsToMatch.
1647       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1648                                Pattern->getOnlyTree(),
1649                                Temp.getOnlyTree(),
1650                                Patterns[i]->getValueAsInt("AddedComplexity")));
1651   }
1652 }
1653
1654 /// CombineChildVariants - Given a bunch of permutations of each child of the
1655 /// 'operator' node, put them together in all possible ways.
1656 static void CombineChildVariants(TreePatternNode *Orig, 
1657                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1658                                  std::vector<TreePatternNode*> &OutVariants,
1659                                  DAGISelEmitter &ISE) {
1660   // Make sure that each operand has at least one variant to choose from.
1661   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1662     if (ChildVariants[i].empty())
1663       return;
1664         
1665   // The end result is an all-pairs construction of the resultant pattern.
1666   std::vector<unsigned> Idxs;
1667   Idxs.resize(ChildVariants.size());
1668   bool NotDone = true;
1669   while (NotDone) {
1670     // Create the variant and add it to the output list.
1671     std::vector<TreePatternNode*> NewChildren;
1672     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1673       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1674     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1675     
1676     // Copy over properties.
1677     R->setName(Orig->getName());
1678     R->setPredicateFn(Orig->getPredicateFn());
1679     R->setTransformFn(Orig->getTransformFn());
1680     R->setTypes(Orig->getExtTypes());
1681     
1682     // If this pattern cannot every match, do not include it as a variant.
1683     std::string ErrString;
1684     if (!R->canPatternMatch(ErrString, ISE)) {
1685       delete R;
1686     } else {
1687       bool AlreadyExists = false;
1688       
1689       // Scan to see if this pattern has already been emitted.  We can get
1690       // duplication due to things like commuting:
1691       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1692       // which are the same pattern.  Ignore the dups.
1693       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1694         if (R->isIsomorphicTo(OutVariants[i])) {
1695           AlreadyExists = true;
1696           break;
1697         }
1698       
1699       if (AlreadyExists)
1700         delete R;
1701       else
1702         OutVariants.push_back(R);
1703     }
1704     
1705     // Increment indices to the next permutation.
1706     NotDone = false;
1707     // Look for something we can increment without causing a wrap-around.
1708     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1709       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1710         NotDone = true;   // Found something to increment.
1711         break;
1712       }
1713       Idxs[IdxsIdx] = 0;
1714     }
1715   }
1716 }
1717
1718 /// CombineChildVariants - A helper function for binary operators.
1719 ///
1720 static void CombineChildVariants(TreePatternNode *Orig, 
1721                                  const std::vector<TreePatternNode*> &LHS,
1722                                  const std::vector<TreePatternNode*> &RHS,
1723                                  std::vector<TreePatternNode*> &OutVariants,
1724                                  DAGISelEmitter &ISE) {
1725   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1726   ChildVariants.push_back(LHS);
1727   ChildVariants.push_back(RHS);
1728   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1729 }  
1730
1731
1732 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1733                                      std::vector<TreePatternNode *> &Children) {
1734   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1735   Record *Operator = N->getOperator();
1736   
1737   // Only permit raw nodes.
1738   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1739       N->getTransformFn()) {
1740     Children.push_back(N);
1741     return;
1742   }
1743
1744   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1745     Children.push_back(N->getChild(0));
1746   else
1747     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1748
1749   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1750     Children.push_back(N->getChild(1));
1751   else
1752     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1753 }
1754
1755 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1756 /// the (potentially recursive) pattern by using algebraic laws.
1757 ///
1758 static void GenerateVariantsOf(TreePatternNode *N,
1759                                std::vector<TreePatternNode*> &OutVariants,
1760                                DAGISelEmitter &ISE) {
1761   // We cannot permute leaves.
1762   if (N->isLeaf()) {
1763     OutVariants.push_back(N);
1764     return;
1765   }
1766
1767   // Look up interesting info about the node.
1768   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1769
1770   // If this node is associative, reassociate.
1771   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1772     // Reassociate by pulling together all of the linked operators 
1773     std::vector<TreePatternNode*> MaximalChildren;
1774     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1775
1776     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1777     // permutations.
1778     if (MaximalChildren.size() == 3) {
1779       // Find the variants of all of our maximal children.
1780       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1781       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1782       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1783       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1784       
1785       // There are only two ways we can permute the tree:
1786       //   (A op B) op C    and    A op (B op C)
1787       // Within these forms, we can also permute A/B/C.
1788       
1789       // Generate legal pair permutations of A/B/C.
1790       std::vector<TreePatternNode*> ABVariants;
1791       std::vector<TreePatternNode*> BAVariants;
1792       std::vector<TreePatternNode*> ACVariants;
1793       std::vector<TreePatternNode*> CAVariants;
1794       std::vector<TreePatternNode*> BCVariants;
1795       std::vector<TreePatternNode*> CBVariants;
1796       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1797       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1798       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1799       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1800       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1801       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1802
1803       // Combine those into the result: (x op x) op x
1804       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1805       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1806       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1807       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1808       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1809       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1810
1811       // Combine those into the result: x op (x op x)
1812       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1813       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1814       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1815       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1816       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1817       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1818       return;
1819     }
1820   }
1821   
1822   // Compute permutations of all children.
1823   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1824   ChildVariants.resize(N->getNumChildren());
1825   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1826     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1827
1828   // Build all permutations based on how the children were formed.
1829   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1830
1831   // If this node is commutative, consider the commuted order.
1832   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1833     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1834     // Don't count children which are actually register references.
1835     unsigned NC = 0;
1836     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1837       TreePatternNode *Child = N->getChild(i);
1838       if (Child->isLeaf())
1839         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1840           Record *RR = DI->getDef();
1841           if (RR->isSubClassOf("Register"))
1842             continue;
1843         }
1844       NC++;
1845     }
1846     // Consider the commuted order.
1847     if (NC == 2)
1848       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1849                            OutVariants, ISE);
1850   }
1851 }
1852
1853
1854 // GenerateVariants - Generate variants.  For example, commutative patterns can
1855 // match multiple ways.  Add them to PatternsToMatch as well.
1856 void DAGISelEmitter::GenerateVariants() {
1857   
1858   DEBUG(std::cerr << "Generating instruction variants.\n");
1859   
1860   // Loop over all of the patterns we've collected, checking to see if we can
1861   // generate variants of the instruction, through the exploitation of
1862   // identities.  This permits the target to provide agressive matching without
1863   // the .td file having to contain tons of variants of instructions.
1864   //
1865   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1866   // intentionally do not reconsider these.  Any variants of added patterns have
1867   // already been added.
1868   //
1869   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1870     std::vector<TreePatternNode*> Variants;
1871     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1872
1873     assert(!Variants.empty() && "Must create at least original variant!");
1874     Variants.erase(Variants.begin());  // Remove the original pattern.
1875
1876     if (Variants.empty())  // No variants for this pattern.
1877       continue;
1878
1879     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1880           PatternsToMatch[i].getSrcPattern()->dump();
1881           std::cerr << "\n");
1882
1883     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1884       TreePatternNode *Variant = Variants[v];
1885
1886       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1887             Variant->dump();
1888             std::cerr << "\n");
1889       
1890       // Scan to see if an instruction or explicit pattern already matches this.
1891       bool AlreadyExists = false;
1892       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1893         // Check to see if this variant already exists.
1894         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1895           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1896           AlreadyExists = true;
1897           break;
1898         }
1899       }
1900       // If we already have it, ignore the variant.
1901       if (AlreadyExists) continue;
1902
1903       // Otherwise, add it to the list of patterns we have.
1904       PatternsToMatch.
1905         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1906                                  Variant, PatternsToMatch[i].getDstPattern(),
1907                                  PatternsToMatch[i].getAddedComplexity()));
1908     }
1909
1910     DEBUG(std::cerr << "\n");
1911   }
1912 }
1913
1914 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1915 // ComplexPattern.
1916 static bool NodeIsComplexPattern(TreePatternNode *N)
1917 {
1918   return (N->isLeaf() &&
1919           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1920           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1921           isSubClassOf("ComplexPattern"));
1922 }
1923
1924 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1925 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1926 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1927                                                    DAGISelEmitter &ISE)
1928 {
1929   if (N->isLeaf() &&
1930       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1931       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1932       isSubClassOf("ComplexPattern")) {
1933     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1934                                   ->getDef());
1935   }
1936   return NULL;
1937 }
1938
1939 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1940 /// patterns before small ones.  This is used to determine the size of a
1941 /// pattern.
1942 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1943   assert((isExtIntegerInVTs(P->getExtTypes()) || 
1944           isExtFloatingPointInVTs(P->getExtTypes()) ||
1945           P->getExtTypeNum(0) == MVT::isVoid ||
1946           P->getExtTypeNum(0) == MVT::Flag ||
1947           P->getExtTypeNum(0) == MVT::iPTR) && 
1948          "Not a valid pattern node to size!");
1949   unsigned Size = 3;  // The node itself.
1950   // If the root node is a ConstantSDNode, increases its size.
1951   // e.g. (set R32:$dst, 0).
1952   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1953     Size += 2;
1954
1955   // FIXME: This is a hack to statically increase the priority of patterns
1956   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1957   // Later we can allow complexity / cost for each pattern to be (optionally)
1958   // specified. To get best possible pattern match we'll need to dynamically
1959   // calculate the complexity of all patterns a dag can potentially map to.
1960   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1961   if (AM)
1962     Size += AM->getNumOperands() * 3;
1963
1964   // If this node has some predicate function that must match, it adds to the
1965   // complexity of this node.
1966   if (!P->getPredicateFn().empty())
1967     ++Size;
1968   
1969   // Count children in the count if they are also nodes.
1970   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1971     TreePatternNode *Child = P->getChild(i);
1972     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1973       Size += getPatternSize(Child, ISE);
1974     else if (Child->isLeaf()) {
1975       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1976         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
1977       else if (NodeIsComplexPattern(Child))
1978         Size += getPatternSize(Child, ISE);
1979       else if (!Child->getPredicateFn().empty())
1980         ++Size;
1981     }
1982   }
1983   
1984   return Size;
1985 }
1986
1987 /// getResultPatternCost - Compute the number of instructions for this pattern.
1988 /// This is a temporary hack.  We should really include the instruction
1989 /// latencies in this calculation.
1990 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1991   if (P->isLeaf()) return 0;
1992   
1993   unsigned Cost = 0;
1994   Record *Op = P->getOperator();
1995   if (Op->isSubClassOf("Instruction")) {
1996     Cost++;
1997     CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1998     if (II.usesCustomDAGSchedInserter)
1999       Cost += 10;
2000   }
2001   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2002     Cost += getResultPatternCost(P->getChild(i), ISE);
2003   return Cost;
2004 }
2005
2006 /// getResultPatternCodeSize - Compute the code size of instructions for this
2007 /// pattern.
2008 static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2009   if (P->isLeaf()) return 0;
2010
2011   unsigned Cost = 0;
2012   Record *Op = P->getOperator();
2013   if (Op->isSubClassOf("Instruction")) {
2014     Cost += Op->getValueAsInt("CodeSize");
2015   }
2016   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2017     Cost += getResultPatternSize(P->getChild(i), ISE);
2018   return Cost;
2019 }
2020
2021 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2022 // In particular, we want to match maximal patterns first and lowest cost within
2023 // a particular complexity first.
2024 struct PatternSortingPredicate {
2025   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2026   DAGISelEmitter &ISE;
2027
2028   bool operator()(PatternToMatch *LHS,
2029                   PatternToMatch *RHS) {
2030     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2031     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2032     LHSSize += LHS->getAddedComplexity();
2033     RHSSize += RHS->getAddedComplexity();
2034     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
2035     if (LHSSize < RHSSize) return false;
2036     
2037     // If the patterns have equal complexity, compare generated instruction cost
2038     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2039     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2040     if (LHSCost < RHSCost) return true;
2041     if (LHSCost > RHSCost) return false;
2042
2043     return getResultPatternSize(LHS->getDstPattern(), ISE) <
2044       getResultPatternSize(RHS->getDstPattern(), ISE);
2045   }
2046 };
2047
2048 /// getRegisterValueType - Look up and return the first ValueType of specified 
2049 /// RegisterClass record
2050 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2051   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2052     return RC->getValueTypeNum(0);
2053   return MVT::Other;
2054 }
2055
2056
2057 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2058 /// type information from it.
2059 static void RemoveAllTypes(TreePatternNode *N) {
2060   N->removeTypes();
2061   if (!N->isLeaf())
2062     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2063       RemoveAllTypes(N->getChild(i));
2064 }
2065
2066 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2067   Record *N = Records.getDef(Name);
2068   if (!N || !N->isSubClassOf("SDNode")) {
2069     std::cerr << "Error getting SDNode '" << Name << "'!\n";
2070     exit(1);
2071   }
2072   return N;
2073 }
2074
2075 /// NodeHasProperty - return true if TreePatternNode has the specified
2076 /// property.
2077 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2078                             DAGISelEmitter &ISE)
2079 {
2080   if (N->isLeaf()) return false;
2081   Record *Operator = N->getOperator();
2082   if (!Operator->isSubClassOf("SDNode")) return false;
2083
2084   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2085   return NodeInfo.hasProperty(Property);
2086 }
2087
2088 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2089                                DAGISelEmitter &ISE)
2090 {
2091   if (NodeHasProperty(N, Property, ISE))
2092     return true;
2093
2094   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2095     TreePatternNode *Child = N->getChild(i);
2096     if (PatternHasProperty(Child, Property, ISE))
2097       return true;
2098   }
2099
2100   return false;
2101 }
2102
2103 class PatternCodeEmitter {
2104 private:
2105   DAGISelEmitter &ISE;
2106
2107   // Predicates.
2108   ListInit *Predicates;
2109   // Pattern cost.
2110   unsigned Cost;
2111   // Instruction selector pattern.
2112   TreePatternNode *Pattern;
2113   // Matched instruction.
2114   TreePatternNode *Instruction;
2115   
2116   // Node to name mapping
2117   std::map<std::string, std::string> VariableMap;
2118   // Node to operator mapping
2119   std::map<std::string, Record*> OperatorMap;
2120   // Names of all the folded nodes which produce chains.
2121   std::vector<std::pair<std::string, unsigned> > FoldedChains;
2122   std::set<std::string> Duplicates;
2123
2124   /// GeneratedCode - This is the buffer that we emit code to.  The first int
2125   /// indicates whether this is an exit predicate (something that should be
2126   /// tested, and if true, the match fails) [when 1], or normal code to emit
2127   /// [when 0], or initialization code to emit [when 2].
2128   std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
2129   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2130   /// the set of patterns for each top-level opcode.
2131   std::set<std::string> &GeneratedDecl;
2132   /// TargetOpcodes - The target specific opcodes used by the resulting
2133   /// instructions.
2134   std::vector<std::string> &TargetOpcodes;
2135   std::vector<std::string> &TargetVTs;
2136
2137   std::string ChainName;
2138   unsigned TmpNo;
2139   unsigned OpcNo;
2140   unsigned VTNo;
2141   
2142   void emitCheck(const std::string &S) {
2143     if (!S.empty())
2144       GeneratedCode.push_back(std::make_pair(1, S));
2145   }
2146   void emitCode(const std::string &S) {
2147     if (!S.empty())
2148       GeneratedCode.push_back(std::make_pair(0, S));
2149   }
2150   void emitInit(const std::string &S) {
2151     if (!S.empty())
2152       GeneratedCode.push_back(std::make_pair(2, S));
2153   }
2154   void emitDecl(const std::string &S) {
2155     assert(!S.empty() && "Invalid declaration");
2156     GeneratedDecl.insert(S);
2157   }
2158   void emitOpcode(const std::string &Opc) {
2159     TargetOpcodes.push_back(Opc);
2160     OpcNo++;
2161   }
2162   void emitVT(const std::string &VT) {
2163     TargetVTs.push_back(VT);
2164     VTNo++;
2165   }
2166 public:
2167   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2168                      TreePatternNode *pattern, TreePatternNode *instr,
2169                      std::vector<std::pair<unsigned, std::string> > &gc,
2170                      std::set<std::string> &gd,
2171                      std::vector<std::string> &to,
2172                      std::vector<std::string> &tv)
2173   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2174     GeneratedCode(gc), GeneratedDecl(gd),
2175     TargetOpcodes(to), TargetVTs(tv),
2176     TmpNo(0), OpcNo(0), VTNo(0) {}
2177
2178   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2179   /// if the match fails. At this point, we already know that the opcode for N
2180   /// matches, and the SDNode for the result has the RootName specified name.
2181   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2182                      const std::string &RootName, const std::string &ParentName,
2183                      const std::string &ChainSuffix, bool &FoundChain) {
2184     bool isRoot = (P == NULL);
2185     // Emit instruction predicates. Each predicate is just a string for now.
2186     if (isRoot) {
2187       std::string PredicateCheck;
2188       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2189         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2190           Record *Def = Pred->getDef();
2191           if (!Def->isSubClassOf("Predicate")) {
2192 #ifndef NDEBUG
2193             Def->dump();
2194 #endif
2195             assert(0 && "Unknown predicate type!");
2196           }
2197           if (!PredicateCheck.empty())
2198             PredicateCheck += " && ";
2199           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2200         }
2201       }
2202       
2203       emitCheck(PredicateCheck);
2204     }
2205
2206     if (N->isLeaf()) {
2207       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2208         emitCheck("cast<ConstantSDNode>(" + RootName +
2209                   ")->getSignExtended() == " + itostr(II->getValue()));
2210         return;
2211       } else if (!NodeIsComplexPattern(N)) {
2212         assert(0 && "Cannot match this as a leaf value!");
2213         abort();
2214       }
2215     }
2216   
2217     // If this node has a name associated with it, capture it in VariableMap. If
2218     // we already saw this in the pattern, emit code to verify dagness.
2219     if (!N->getName().empty()) {
2220       std::string &VarMapEntry = VariableMap[N->getName()];
2221       if (VarMapEntry.empty()) {
2222         VarMapEntry = RootName;
2223       } else {
2224         // If we get here, this is a second reference to a specific name.  Since
2225         // we already have checked that the first reference is valid, we don't
2226         // have to recursively match it, just check that it's the same as the
2227         // previously named thing.
2228         emitCheck(VarMapEntry + " == " + RootName);
2229         return;
2230       }
2231
2232       if (!N->isLeaf())
2233         OperatorMap[N->getName()] = N->getOperator();
2234     }
2235
2236
2237     // Emit code to load the child nodes and match their contents recursively.
2238     unsigned OpNo = 0;
2239     bool NodeHasChain = NodeHasProperty   (N, SDNodeInfo::SDNPHasChain, ISE);
2240     bool HasChain     = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2241     bool HasOutFlag   = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag,  ISE);
2242     bool EmittedUseCheck = false;
2243     if (HasChain) {
2244       if (NodeHasChain)
2245         OpNo = 1;
2246       if (!isRoot) {
2247         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2248         // Multiple uses of actual result?
2249         emitCheck(RootName + ".hasOneUse()");
2250         EmittedUseCheck = true;
2251         if (NodeHasChain) {
2252           // If the immediate use can somehow reach this node through another
2253           // path, then can't fold it either or it will create a cycle.
2254           // e.g. In the following diagram, XX can reach ld through YY. If
2255           // ld is folded into XX, then YY is both a predecessor and a successor
2256           // of XX.
2257           //
2258           //         [ld]
2259           //         ^  ^
2260           //         |  |
2261           //        /   \---
2262           //      /        [YY]
2263           //      |         ^
2264           //     [XX]-------|
2265           const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2266           if (PInfo.getNumOperands() > 1 ||
2267               PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2268               PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2269               PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2270             emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2271                       ".Val)");
2272         }
2273       }
2274
2275       if (NodeHasChain) {
2276         if (FoundChain)
2277           emitCheck("Chain.Val == " + RootName + ".Val");
2278         else
2279           FoundChain = true;
2280         ChainName = "Chain" + ChainSuffix;
2281         emitInit("SDOperand " + ChainName + " = " + RootName +
2282                  ".getOperand(0);");
2283       }
2284     }
2285
2286     // Don't fold any node which reads or writes a flag and has multiple uses.
2287     // FIXME: We really need to separate the concepts of flag and "glue". Those
2288     // real flag results, e.g. X86CMP output, can have multiple uses.
2289     // FIXME: If the optional incoming flag does not exist. Then it is ok to
2290     // fold it.
2291     if (!isRoot &&
2292         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2293          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2294          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2295       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2296       if (!EmittedUseCheck) {
2297         // Multiple uses of actual result?
2298         emitCheck(RootName + ".hasOneUse()");
2299       }
2300     }
2301
2302     const ComplexPattern *CP;
2303     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2304       emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
2305                RootName + ".getOperand(" +utostr(OpNo) + ");");
2306
2307       TreePatternNode *Child = N->getChild(i);    
2308       if (!Child->isLeaf()) {
2309         // If it's not a leaf, recursively match.
2310         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2311         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2312                   CInfo.getEnumName());
2313         EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2314                       ChainSuffix + utostr(OpNo), FoundChain);
2315         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2316           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2317                                                 CInfo.getNumResults()));
2318       } else {
2319         // If this child has a name associated with it, capture it in VarMap. If
2320         // we already saw this in the pattern, emit code to verify dagness.
2321         if (!Child->getName().empty()) {
2322           std::string &VarMapEntry = VariableMap[Child->getName()];
2323           if (VarMapEntry.empty()) {
2324             VarMapEntry = RootName + utostr(OpNo);
2325           } else {
2326             // If we get here, this is a second reference to a specific name.
2327             // Since we already have checked that the first reference is valid,
2328             // we don't have to recursively match it, just check that it's the
2329             // same as the previously named thing.
2330             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2331             Duplicates.insert(RootName + utostr(OpNo));
2332             continue;
2333           }
2334         }
2335       
2336         // Handle leaves of various types.
2337         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2338           Record *LeafRec = DI->getDef();
2339           if (LeafRec->isSubClassOf("RegisterClass")) {
2340             // Handle register references.  Nothing to do here.
2341           } else if (LeafRec->isSubClassOf("Register")) {
2342             // Handle register references.
2343           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2344             // Handle complex pattern.
2345             CP = NodeGetComplexPattern(Child, ISE);
2346             std::string Fn = CP->getSelectFunc();
2347             unsigned NumOps = CP->getNumOperands();
2348             for (unsigned i = 0; i < NumOps; ++i) {
2349               emitDecl("CPTmp" + utostr(i));
2350               emitCode("SDOperand CPTmp" + utostr(i) + ";");
2351             }
2352
2353             std::string Code = Fn + "(" + RootName + utostr(OpNo);
2354             for (unsigned i = 0; i < NumOps; i++)
2355               Code += ", CPTmp" + utostr(i);
2356             emitCheck(Code + ")");
2357           } else if (LeafRec->getName() == "srcvalue") {
2358             // Place holder for SRCVALUE nodes. Nothing to do here.
2359           } else if (LeafRec->isSubClassOf("ValueType")) {
2360             // Make sure this is the specified value type.
2361             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2362                       ")->getVT() == MVT::" + LeafRec->getName());
2363           } else if (LeafRec->isSubClassOf("CondCode")) {
2364             // Make sure this is the specified cond code.
2365             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2366                       ")->get() == ISD::" + LeafRec->getName());
2367           } else {
2368 #ifndef NDEBUG
2369             Child->dump();
2370             std::cerr << " ";
2371 #endif
2372             assert(0 && "Unknown leaf type!");
2373           }
2374         } else if (IntInit *II =
2375                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2376           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2377           unsigned CTmp = TmpNo++;
2378           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2379                    RootName + utostr(OpNo) + ")->getSignExtended();");
2380
2381           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2382         } else {
2383 #ifndef NDEBUG
2384           Child->dump();
2385 #endif
2386           assert(0 && "Unknown leaf type!");
2387         }
2388       }
2389     }
2390
2391     // Handle cases when root is a complex pattern.
2392     if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2393       std::string Fn = CP->getSelectFunc();
2394       unsigned NumOps = CP->getNumOperands();
2395       for (unsigned i = 0; i < NumOps; ++i) {
2396         emitDecl("CPTmp" + utostr(i));
2397         emitCode("SDOperand CPTmp" + utostr(i) + ";");
2398       }
2399
2400       std::string Code = Fn + "(" + RootName;
2401       for (unsigned i = 0; i < NumOps; i++)
2402         Code += ", CPTmp" + utostr(i);
2403       emitCheck(Code + ")");
2404     }
2405
2406     // If there is a node predicate for this, emit the call.
2407     if (!N->getPredicateFn().empty())
2408       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2409   }
2410
2411   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2412   /// we actually have to build a DAG!
2413   std::vector<std::string>
2414   EmitResultCode(TreePatternNode *N, bool RetSelected,
2415                  bool InFlagDecled, bool ResNodeDecled,
2416                  bool LikeLeaf = false, bool isRoot = false) {
2417     // List of arguments of getTargetNode() or SelectNodeTo().
2418     std::vector<std::string> NodeOps;
2419     // This is something selected from the pattern we matched.
2420     if (!N->getName().empty()) {
2421       std::string &Val = VariableMap[N->getName()];
2422       assert(!Val.empty() &&
2423              "Variable referenced but not defined and not caught earlier!");
2424       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2425         // Already selected this operand, just return the tmpval.
2426         NodeOps.push_back(Val);
2427         return NodeOps;
2428       }
2429
2430       const ComplexPattern *CP;
2431       unsigned ResNo = TmpNo++;
2432       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2433         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2434         std::string CastType;
2435         switch (N->getTypeNum(0)) {
2436         default: assert(0 && "Unknown type for constant node!");
2437         case MVT::i1:  CastType = "bool"; break;
2438         case MVT::i8:  CastType = "unsigned char"; break;
2439         case MVT::i16: CastType = "unsigned short"; break;
2440         case MVT::i32: CastType = "unsigned"; break;
2441         case MVT::i64: CastType = "uint64_t"; break;
2442         }
2443         emitCode("SDOperand Tmp" + utostr(ResNo) + 
2444                  " = CurDAG->getTargetConstant(((" + CastType +
2445                  ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2446                  getEnumName(N->getTypeNum(0)) + ");");
2447         NodeOps.push_back("Tmp" + utostr(ResNo));
2448         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2449         // value if used multiple times by this pattern result.
2450         Val = "Tmp"+utostr(ResNo);
2451       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2452         Record *Op = OperatorMap[N->getName()];
2453         // Transform ExternalSymbol to TargetExternalSymbol
2454         if (Op && Op->getName() == "externalsym") {
2455           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2456                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2457                    Val + ")->getSymbol(), " +
2458                    getEnumName(N->getTypeNum(0)) + ");");
2459           NodeOps.push_back("Tmp" + utostr(ResNo));
2460           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2461           // value if used multiple times by this pattern result.
2462           Val = "Tmp"+utostr(ResNo);
2463         } else {
2464           NodeOps.push_back(Val);
2465         }
2466       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2467         Record *Op = OperatorMap[N->getName()];
2468         // Transform GlobalAddress to TargetGlobalAddress
2469         if (Op && Op->getName() == "globaladdr") {
2470           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2471                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2472                    ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2473                    ");");
2474           NodeOps.push_back("Tmp" + utostr(ResNo));
2475           // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2476           // value if used multiple times by this pattern result.
2477           Val = "Tmp"+utostr(ResNo);
2478         } else {
2479           NodeOps.push_back(Val);
2480         }
2481       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2482         NodeOps.push_back(Val);
2483         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2484         // value if used multiple times by this pattern result.
2485         Val = "Tmp"+utostr(ResNo);
2486       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2487         NodeOps.push_back(Val);
2488         // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2489         // value if used multiple times by this pattern result.
2490         Val = "Tmp"+utostr(ResNo);
2491       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2492         std::string Fn = CP->getSelectFunc();
2493         for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2494           emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2495           NodeOps.push_back("CPTmp" + utostr(i));
2496         }
2497       } else {
2498         // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
2499         // node even if it isn't one. Don't select it.
2500         if (!LikeLeaf) {
2501           emitCode("AddToISelQueue(" + Val + ");");
2502           if (isRoot && N->isLeaf()) {
2503             emitCode("ReplaceUses(N, " + Val + ");");
2504             emitCode("return NULL;");
2505           }
2506         }
2507         NodeOps.push_back(Val);
2508       }
2509       return NodeOps;
2510     }
2511     if (N->isLeaf()) {
2512       // If this is an explicit register reference, handle it.
2513       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2514         unsigned ResNo = TmpNo++;
2515         if (DI->getDef()->isSubClassOf("Register")) {
2516           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2517                    ISE.getQualifiedName(DI->getDef()) + ", " +
2518                    getEnumName(N->getTypeNum(0)) + ");");
2519           NodeOps.push_back("Tmp" + utostr(ResNo));
2520           return NodeOps;
2521         }
2522       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2523         unsigned ResNo = TmpNo++;
2524         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2525         emitCode("SDOperand Tmp" + utostr(ResNo) + 
2526                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2527                  ", " + getEnumName(N->getTypeNum(0)) + ");");
2528         NodeOps.push_back("Tmp" + utostr(ResNo));
2529         return NodeOps;
2530       }
2531     
2532 #ifndef NDEBUG
2533       N->dump();
2534 #endif
2535       assert(0 && "Unknown leaf type!");
2536       return NodeOps;
2537     }
2538
2539     Record *Op = N->getOperator();
2540     if (Op->isSubClassOf("Instruction")) {
2541       const CodeGenTarget &CGT = ISE.getTargetInfo();
2542       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2543       const DAGInstruction &Inst = ISE.getInstruction(Op);
2544       TreePattern *InstPat = Inst.getPattern();
2545       TreePatternNode *InstPatNode =
2546         isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2547                : (InstPat ? InstPat->getOnlyTree() : NULL);
2548       if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2549         InstPatNode = InstPatNode->getChild(1);
2550       }
2551       bool HasVarOps     = isRoot && II.hasVariableNumberOfOperands;
2552       bool HasImpInputs  = isRoot && Inst.getNumImpOperands() > 0;
2553       bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2554       bool NodeHasOptInFlag = isRoot &&
2555         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2556       bool NodeHasInFlag  = isRoot &&
2557         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2558       bool NodeHasOutFlag = HasImpResults || (isRoot &&
2559         PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2560       bool NodeHasChain = InstPatNode &&
2561         PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
2562       bool InputHasChain = isRoot &&
2563         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2564
2565       if (NodeHasOptInFlag) {
2566         emitCode("bool HasInFlag = "
2567            "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2568       }
2569       if (HasVarOps)
2570         emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
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       std::vector<std::string> AllOps;
2581       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2582         std::vector<std::string> Ops = EmitResultCode(N->getChild(i),
2583                                       RetSelected, InFlagDecled, ResNodeDecled);
2584         AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2585       }
2586
2587       // Emit all the chain and CopyToReg stuff.
2588       bool ChainEmitted = NodeHasChain;
2589       if (NodeHasChain)
2590         emitCode("AddToISelQueue(" + ChainName + ");");
2591       if (NodeHasInFlag || HasImpInputs)
2592         EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2593                              InFlagDecled, ResNodeDecled, true);
2594       if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
2595         if (!InFlagDecled) {
2596           emitCode("SDOperand InFlag(0, 0);");
2597           InFlagDecled = true;
2598         }
2599         if (NodeHasOptInFlag) {
2600           emitCode("if (HasInFlag) {");
2601           emitCode("  InFlag = N.getOperand(N.getNumOperands()-1);");
2602           emitCode("  AddToISelQueue(InFlag);");
2603           emitCode("}");
2604         }
2605       }
2606
2607       unsigned NumResults = Inst.getNumResults();    
2608       unsigned ResNo = TmpNo++;
2609       if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2610           NodeHasOptInFlag) {
2611         std::string Code;
2612         std::string Code2;
2613         std::string NodeName;
2614         if (!isRoot) {
2615           NodeName = "Tmp" + utostr(ResNo);
2616           Code2 = "SDOperand " + NodeName + " = SDOperand(";
2617         } else {
2618           NodeName = "ResNode";
2619           if (!ResNodeDecled)
2620             Code2 = "SDNode *" + NodeName + " = ";
2621           else
2622             Code2 = NodeName + " = ";
2623         }
2624
2625         Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2626         unsigned OpsNo = OpcNo;
2627         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2628
2629         // Output order: results, chain, flags
2630         // Result types.
2631         if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2632           Code += ", VT" + utostr(VTNo);
2633           emitVT(getEnumName(N->getTypeNum(0)));
2634         }
2635         if (NodeHasChain)
2636           Code += ", MVT::Other";
2637         if (NodeHasOutFlag)
2638           Code += ", MVT::Flag";
2639
2640         // Inputs.
2641         if (HasVarOps) {
2642           for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2643             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2644           AllOps.clear();
2645         }
2646
2647         if (HasVarOps) {
2648           if (NodeHasInFlag || HasImpInputs)
2649             emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2650                      "i != e; ++i) {");
2651           else if (NodeHasOptInFlag) 
2652             emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2653                      "(HasInFlag?1:0); i != e; ++i) {");
2654           else
2655             emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2656                      "i != e; ++i) {");
2657           emitCode("  AddToISelQueue(N.getOperand(i));");
2658           emitCode("  Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
2659           emitCode("}");
2660         }
2661
2662         if (NodeHasChain) {
2663           if (HasVarOps)
2664             emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
2665           else
2666             AllOps.push_back(ChainName);
2667         }
2668
2669         if (HasVarOps) {
2670           if (NodeHasInFlag || HasImpInputs)
2671             emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2672           else if (NodeHasOptInFlag) {
2673             emitCode("if (HasInFlag)");
2674             emitCode("  Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2675           }
2676           Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2677             ".size()";
2678         } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2679             AllOps.push_back("InFlag");
2680
2681         unsigned NumOps = AllOps.size();
2682         if (NumOps) {
2683           if (!NodeHasOptInFlag && NumOps < 4) {
2684             for (unsigned i = 0; i != NumOps; ++i)
2685               Code += ", " + AllOps[i];
2686           } else {
2687             std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2688             for (unsigned i = 0; i != NumOps; ++i) {
2689               OpsCode += AllOps[i];
2690               if (i != NumOps-1)
2691                 OpsCode += ", ";
2692             }
2693             emitCode(OpsCode + " };");
2694             Code += ", Ops" + utostr(OpsNo) + ", ";
2695             if (NodeHasOptInFlag) {
2696               Code += "HasInFlag ? ";
2697               Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2698             } else
2699               Code += utostr(NumOps);
2700           }
2701         }
2702             
2703         if (!isRoot)
2704           Code += "), 0";
2705         emitCode(Code2 + Code + ");");
2706
2707         if (NodeHasChain)
2708           // Remember which op produces the chain.
2709           if (!isRoot)
2710             emitCode(ChainName + " = SDOperand(" + NodeName +
2711                      ".Val, " + utostr(PatResults) + ");");
2712           else
2713             emitCode(ChainName + " = SDOperand(" + NodeName +
2714                      ", " + utostr(PatResults) + ");");
2715
2716         if (!isRoot) {
2717           NodeOps.push_back("Tmp" + utostr(ResNo));
2718           return NodeOps;
2719         }
2720
2721         bool NeedReplace = false;
2722         if (NodeHasOutFlag) {
2723           if (!InFlagDecled) {
2724             emitCode("SDOperand InFlag = SDOperand(ResNode, " + 
2725                      utostr(NumResults + (unsigned)NodeHasChain) + ");");
2726             InFlagDecled = true;
2727           } else
2728             emitCode("InFlag = SDOperand(ResNode, " + 
2729                      utostr(NumResults + (unsigned)NodeHasChain) + ");");
2730         }
2731
2732         if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
2733           emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
2734           NumResults = 1;
2735         }
2736
2737         if (FoldedChains.size() > 0) {
2738           std::string Code;
2739           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2740             emitCode("ReplaceUses(SDOperand(" +
2741                      FoldedChains[j].first + ".Val, " + 
2742                      utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2743                      utostr(NumResults) + "));");
2744           NeedReplace = true;
2745         }
2746
2747         if (NodeHasOutFlag) {
2748           emitCode("ReplaceUses(SDOperand(N.Val, " +
2749                    utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
2750           NeedReplace = true;
2751         }
2752
2753         if (NeedReplace) {
2754           for (unsigned i = 0; i < NumResults; i++)
2755             emitCode("ReplaceUses(SDOperand(N.Val, " +
2756                      utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
2757           if (InputHasChain)
2758             emitCode("ReplaceUses(SDOperand(N.Val, " + 
2759                      utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " +
2760                      ChainName + ".ResNo" + "));");
2761         } else
2762           RetSelected = true;
2763
2764         // User does not expect the instruction would produce a chain!
2765         if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
2766           ;
2767         } else if (InputHasChain && !NodeHasChain) {
2768           // One of the inner node produces a chain.
2769           if (NodeHasOutFlag)
2770             emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
2771                      "), SDOperand(ResNode, N.ResNo-1));");
2772           for (unsigned i = 0; i < PatResults; ++i)
2773             emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
2774                      "), SDOperand(ResNode, " + utostr(i) + "));");
2775           emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
2776                    "), " + ChainName + ");");
2777           RetSelected = false;
2778         }
2779
2780         if (RetSelected)
2781           emitCode("return ResNode;");
2782         else
2783           emitCode("return NULL;");
2784       } else {
2785         std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
2786           utostr(OpcNo);
2787         if (N->getTypeNum(0) != MVT::isVoid)
2788           Code += ", VT" + utostr(VTNo);
2789         if (NodeHasOutFlag)
2790           Code += ", MVT::Flag";
2791
2792         if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2793           AllOps.push_back("InFlag");
2794
2795         unsigned NumOps = AllOps.size();
2796         if (NumOps) {
2797           if (!NodeHasOptInFlag && NumOps < 4) {
2798             for (unsigned i = 0; i != NumOps; ++i)
2799               Code += ", " + AllOps[i];
2800           } else {
2801             std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
2802             for (unsigned i = 0; i != NumOps; ++i) {
2803               OpsCode += AllOps[i];
2804               if (i != NumOps-1)
2805                 OpsCode += ", ";
2806             }
2807             emitCode(OpsCode + " };");
2808             Code += ", Ops" + utostr(OpcNo) + ", ";
2809             Code += utostr(NumOps);
2810           }
2811         }
2812         emitCode(Code + ");");
2813         emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2814         if (N->getTypeNum(0) != MVT::isVoid)
2815           emitVT(getEnumName(N->getTypeNum(0)));
2816       }
2817
2818       return NodeOps;
2819     } else if (Op->isSubClassOf("SDNodeXForm")) {
2820       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2821       // PatLeaf node - the operand may or may not be a leaf node. But it should
2822       // behave like one.
2823       std::vector<std::string> Ops =
2824         EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
2825                        ResNodeDecled, true);
2826       unsigned ResNo = TmpNo++;
2827       emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2828                + "(" + Ops.back() + ".Val);");
2829       NodeOps.push_back("Tmp" + utostr(ResNo));
2830       emitCode("AddToISelQueue(Tmp" + utostr(ResNo) + ");");
2831       if (isRoot)
2832         emitCode("return Tmp" + utostr(ResNo) + ".Val;");
2833       return NodeOps;
2834     } else {
2835       N->dump();
2836       std::cerr << "\n";
2837       throw std::string("Unknown node in result pattern!");
2838     }
2839   }
2840
2841   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2842   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2843   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2844   /// for, this returns true otherwise false if Pat has all types.
2845   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2846                           const std::string &Prefix, bool isRoot = false) {
2847     // Did we find one?
2848     if (Pat->getExtTypes() != Other->getExtTypes()) {
2849       // Move a type over from 'other' to 'pat'.
2850       Pat->setTypes(Other->getExtTypes());
2851       // The top level node type is checked outside of the select function.
2852       if (!isRoot)
2853         emitCheck(Prefix + ".Val->getValueType(0) == " +
2854                   getName(Pat->getTypeNum(0)));
2855       return true;
2856     }
2857   
2858     unsigned OpNo =
2859       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2860     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2861       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2862                              Prefix + utostr(OpNo)))
2863         return true;
2864     return false;
2865   }
2866
2867 private:
2868   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2869   /// being built.
2870   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2871                             bool &ChainEmitted, bool &InFlagDecled,
2872                             bool &ResNodeDecled, bool isRoot = false) {
2873     const CodeGenTarget &T = ISE.getTargetInfo();
2874     unsigned OpNo =
2875       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2876     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2877     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2878       TreePatternNode *Child = N->getChild(i);
2879       if (!Child->isLeaf()) {
2880         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
2881                              InFlagDecled, ResNodeDecled);
2882       } else {
2883         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2884           if (!Child->getName().empty()) {
2885             std::string Name = RootName + utostr(OpNo);
2886             if (Duplicates.find(Name) != Duplicates.end())
2887               // A duplicate! Do not emit a copy for this node.
2888               continue;
2889           }
2890
2891           Record *RR = DI->getDef();
2892           if (RR->isSubClassOf("Register")) {
2893             MVT::ValueType RVT = getRegisterValueType(RR, T);
2894             if (RVT == MVT::Flag) {
2895               if (!InFlagDecled) {
2896                 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
2897                 InFlagDecled = true;
2898               } else
2899                 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
2900               emitCode("AddToISelQueue(InFlag);");
2901             } else {
2902               if (!ChainEmitted) {
2903                 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2904                 ChainName = "Chain";
2905                 ChainEmitted = true;
2906               }
2907               emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
2908               if (!InFlagDecled) {
2909                 emitCode("SDOperand InFlag(0, 0);");
2910                 InFlagDecled = true;
2911               }
2912               std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2913               emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
2914                        ", " + ISE.getQualifiedName(RR) +
2915                        ", " +  RootName + utostr(OpNo) + ", InFlag).Val;");
2916               ResNodeDecled = true;
2917               emitCode(ChainName + " = SDOperand(ResNode, 0);");
2918               emitCode("InFlag = SDOperand(ResNode, 1);");
2919             }
2920           }
2921         }
2922       }
2923     }
2924
2925     if (HasInFlag) {
2926       if (!InFlagDecled) {
2927         emitCode("SDOperand InFlag = " + RootName +
2928                ".getOperand(" + utostr(OpNo) + ");");
2929         InFlagDecled = true;
2930       } else
2931         emitCode("InFlag = " + RootName +
2932                ".getOperand(" + utostr(OpNo) + ");");
2933       emitCode("AddToISelQueue(InFlag);");
2934     }
2935   }
2936
2937   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2938   /// as specified by the instruction. It returns true if any copy is
2939   /// emitted.
2940   bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
2941                         bool &ChainEmitted) {
2942     bool RetVal = false;
2943     Record *Op = N->getOperator();
2944     if (Op->isSubClassOf("Instruction")) {
2945       const DAGInstruction &Inst = ISE.getInstruction(Op);
2946       const CodeGenTarget &CGT = ISE.getTargetInfo();
2947       unsigned NumImpResults  = Inst.getNumImpResults();
2948       for (unsigned i = 0; i < NumImpResults; i++) {
2949         Record *RR = Inst.getImpResult(i);
2950         if (RR->isSubClassOf("Register")) {
2951           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2952           if (RVT != MVT::Flag) {
2953             if (!ChainEmitted) {
2954               emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2955               ChainEmitted = true;
2956               ChainName = "Chain";
2957             }
2958             std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2959             emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
2960                      ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
2961                      ", InFlag).Val;");
2962             ResNodeDecled = true;
2963             emitCode(ChainName + " = SDOperand(ResNode, 1);");
2964             emitCode("InFlag = SDOperand(ResNode, 2);");
2965             RetVal = true;
2966           }
2967         }
2968       }
2969     }
2970     return RetVal;
2971   }
2972 };
2973
2974 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2975 /// stream to match the pattern, and generate the code for the match if it
2976 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2977 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2978                   std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
2979                                            std::set<std::string> &GeneratedDecl,
2980                                         std::vector<std::string> &TargetOpcodes,
2981                                           std::vector<std::string> &TargetVTs) {
2982   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2983                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2984                              GeneratedCode, GeneratedDecl,
2985                              TargetOpcodes, TargetVTs);
2986
2987   // Emit the matcher, capturing named arguments in VariableMap.
2988   bool FoundChain = false;
2989   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "",
2990                         FoundChain);
2991
2992   // TP - Get *SOME* tree pattern, we don't care which.
2993   TreePattern &TP = *PatternFragments.begin()->second;
2994   
2995   // At this point, we know that we structurally match the pattern, but the
2996   // types of the nodes may not match.  Figure out the fewest number of type 
2997   // comparisons we need to emit.  For example, if there is only one integer
2998   // type supported by a target, there should be no type comparisons at all for
2999   // integer patterns!
3000   //
3001   // To figure out the fewest number of type checks needed, clone the pattern,
3002   // remove the types, then perform type inference on the pattern as a whole.
3003   // If there are unresolved types, emit an explicit check for those types,
3004   // apply the type to the tree, then rerun type inference.  Iterate until all
3005   // types are resolved.
3006   //
3007   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3008   RemoveAllTypes(Pat);
3009   
3010   do {
3011     // Resolve/propagate as many types as possible.
3012     try {
3013       bool MadeChange = true;
3014       while (MadeChange)
3015         MadeChange = Pat->ApplyTypeConstraints(TP,
3016                                                true/*Ignore reg constraints*/);
3017     } catch (...) {
3018       assert(0 && "Error: could not find consistent types for something we"
3019              " already decided was ok!");
3020       abort();
3021     }
3022
3023     // Insert a check for an unresolved type and add it to the tree.  If we find
3024     // an unresolved type to add a check for, this returns true and we iterate,
3025     // otherwise we are done.
3026   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
3027
3028   Emitter.EmitResultCode(Pattern.getDstPattern(),
3029                          false, false, false, false, true);
3030   delete Pat;
3031 }
3032
3033 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
3034 /// a line causes any of them to be empty, remove them and return true when
3035 /// done.
3036 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
3037                           std::vector<std::pair<unsigned, std::string> > > >
3038                           &Patterns) {
3039   bool ErasedPatterns = false;
3040   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3041     Patterns[i].second.pop_back();
3042     if (Patterns[i].second.empty()) {
3043       Patterns.erase(Patterns.begin()+i);
3044       --i; --e;
3045       ErasedPatterns = true;
3046     }
3047   }
3048   return ErasedPatterns;
3049 }
3050
3051 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3052 /// code together between the patterns.
3053 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
3054                               std::vector<std::pair<unsigned, std::string> > > >
3055                                   &Patterns, unsigned Indent,
3056                                   std::ostream &OS) {
3057   typedef std::pair<unsigned, std::string> CodeLine;
3058   typedef std::vector<CodeLine> CodeList;
3059   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3060   
3061   if (Patterns.empty()) return;
3062   
3063   // Figure out how many patterns share the next code line.  Explicitly copy
3064   // FirstCodeLine so that we don't invalidate a reference when changing
3065   // Patterns.
3066   const CodeLine FirstCodeLine = Patterns.back().second.back();
3067   unsigned LastMatch = Patterns.size()-1;
3068   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3069     --LastMatch;
3070   
3071   // If not all patterns share this line, split the list into two pieces.  The
3072   // first chunk will use this line, the second chunk won't.
3073   if (LastMatch != 0) {
3074     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3075     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3076     
3077     // FIXME: Emit braces?
3078     if (Shared.size() == 1) {
3079       PatternToMatch &Pattern = *Shared.back().first;
3080       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3081       Pattern.getSrcPattern()->print(OS);
3082       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3083       Pattern.getDstPattern()->print(OS);
3084       OS << "\n";
3085       unsigned AddedComplexity = Pattern.getAddedComplexity();
3086       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3087          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3088          << "  cost = "
3089          << getResultPatternCost(Pattern.getDstPattern(), *this)
3090          << "  size = "
3091          << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3092     }
3093     if (FirstCodeLine.first != 1) {
3094       OS << std::string(Indent, ' ') << "{\n";
3095       Indent += 2;
3096     }
3097     EmitPatterns(Shared, Indent, OS);
3098     if (FirstCodeLine.first != 1) {
3099       Indent -= 2;
3100       OS << std::string(Indent, ' ') << "}\n";
3101     }
3102     
3103     if (Other.size() == 1) {
3104       PatternToMatch &Pattern = *Other.back().first;
3105       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3106       Pattern.getSrcPattern()->print(OS);
3107       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3108       Pattern.getDstPattern()->print(OS);
3109       OS << "\n";
3110       unsigned AddedComplexity = Pattern.getAddedComplexity();
3111       OS << std::string(Indent, ' ') << "// Pattern complexity = "
3112          << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3113          << "  cost = "
3114          << getResultPatternCost(Pattern.getDstPattern(), *this)
3115          << "  size = "
3116          << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3117     }
3118     EmitPatterns(Other, Indent, OS);
3119     return;
3120   }
3121   
3122   // Remove this code from all of the patterns that share it.
3123   bool ErasedPatterns = EraseCodeLine(Patterns);
3124   
3125   bool isPredicate = FirstCodeLine.first == 1;
3126   
3127   // Otherwise, every pattern in the list has this line.  Emit it.
3128   if (!isPredicate) {
3129     // Normal code.
3130     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3131   } else {
3132     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3133     
3134     // If the next code line is another predicate, and if all of the pattern
3135     // in this group share the same next line, emit it inline now.  Do this
3136     // until we run out of common predicates.
3137     while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
3138       // Check that all of fhe patterns in Patterns end with the same predicate.
3139       bool AllEndWithSamePredicate = true;
3140       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3141         if (Patterns[i].second.back() != Patterns.back().second.back()) {
3142           AllEndWithSamePredicate = false;
3143           break;
3144         }
3145       // If all of the predicates aren't the same, we can't share them.
3146       if (!AllEndWithSamePredicate) break;
3147       
3148       // Otherwise we can.  Emit it shared now.
3149       OS << " &&\n" << std::string(Indent+4, ' ')
3150          << Patterns.back().second.back().second;
3151       ErasedPatterns = EraseCodeLine(Patterns);
3152     }
3153     
3154     OS << ") {\n";
3155     Indent += 2;
3156   }
3157   
3158   EmitPatterns(Patterns, Indent, OS);
3159   
3160   if (isPredicate)
3161     OS << std::string(Indent-2, ' ') << "}\n";
3162 }
3163
3164
3165
3166 namespace {
3167   /// CompareByRecordName - An ordering predicate that implements less-than by
3168   /// comparing the names records.
3169   struct CompareByRecordName {
3170     bool operator()(const Record *LHS, const Record *RHS) const {
3171       // Sort by name first.
3172       if (LHS->getName() < RHS->getName()) return true;
3173       // If both names are equal, sort by pointer.
3174       return LHS->getName() == RHS->getName() && LHS < RHS;
3175     }
3176   };
3177 }
3178
3179 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3180   std::string InstNS = Target.inst_begin()->second.Namespace;
3181   if (!InstNS.empty()) InstNS += "::";
3182   
3183   // Group the patterns by their top-level opcodes.
3184   std::map<Record*, std::vector<PatternToMatch*>,
3185     CompareByRecordName> PatternsByOpcode;
3186   // All unique target node emission functions.
3187   std::map<std::string, unsigned> EmitFunctions;
3188   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3189     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3190     if (!Node->isLeaf()) {
3191       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3192     } else {
3193       const ComplexPattern *CP;
3194       if (IntInit *II = 
3195           dynamic_cast<IntInit*>(Node->getLeafValue())) {
3196         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3197       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3198         std::vector<Record*> OpNodes = CP->getRootNodes();
3199         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3200           PatternsByOpcode[OpNodes[j]]
3201             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3202         }
3203       } else {
3204         std::cerr << "Unrecognized opcode '";
3205         Node->dump();
3206         std::cerr << "' on tree pattern '";
3207         std::cerr << 
3208            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3209         std::cerr << "'!\n";
3210         exit(1);
3211       }
3212     }
3213   }
3214
3215   // For each opcode, there might be multiple select functions, one per
3216   // ValueType of the node (or its first operand if it doesn't produce a
3217   // non-chain result.
3218   std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3219
3220   // Emit one Select_* method for each top-level opcode.  We do this instead of
3221   // emitting one giant switch statement to support compilers where this will
3222   // result in the recursive functions taking less stack space.
3223   for (std::map<Record*, std::vector<PatternToMatch*>,
3224        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3225        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3226     const std::string &OpName = PBOI->first->getName();
3227     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3228     std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3229     assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3230
3231     // We want to emit all of the matching code now.  However, we want to emit
3232     // the matches in order of minimal cost.  Sort the patterns so the least
3233     // cost one is at the start.
3234     std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
3235                      PatternSortingPredicate(*this));
3236
3237     // Split them into groups by type.
3238     std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3239     for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3240       PatternToMatch *Pat = PatternsOfOp[i];
3241       TreePatternNode *SrcPat = Pat->getSrcPattern();
3242       if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0)
3243         SrcPat = SrcPat->getChild(0);
3244       MVT::ValueType VT = SrcPat->getTypeNum(0);
3245       std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI = 
3246         PatternsByType.find(VT);
3247       if (TI != PatternsByType.end())
3248         TI->second.push_back(Pat);
3249       else {
3250         std::vector<PatternToMatch*> PVec;
3251         PVec.push_back(Pat);
3252         PatternsByType.insert(std::make_pair(VT, PVec));
3253       }
3254     }
3255
3256     for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3257            II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3258          ++II) {
3259       MVT::ValueType OpVT = II->first;
3260       std::vector<PatternToMatch*> &Patterns = II->second;
3261       typedef std::vector<std::pair<unsigned, std::string> > CodeList;
3262       typedef std::vector<std::pair<unsigned, std::string> >::iterator CodeListI;
3263     
3264       std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3265       std::vector<std::vector<std::string> > PatternOpcodes;
3266       std::vector<std::vector<std::string> > PatternVTs;
3267       std::vector<std::set<std::string> > PatternDecls;
3268       for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3269         CodeList GeneratedCode;
3270         std::set<std::string> GeneratedDecl;
3271         std::vector<std::string> TargetOpcodes;
3272         std::vector<std::string> TargetVTs;
3273         GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3274                                TargetOpcodes, TargetVTs);
3275         CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3276         PatternDecls.push_back(GeneratedDecl);
3277         PatternOpcodes.push_back(TargetOpcodes);
3278         PatternVTs.push_back(TargetVTs);
3279       }
3280     
3281       // Scan the code to see if all of the patterns are reachable and if it is
3282       // possible that the last one might not match.
3283       bool mightNotMatch = true;
3284       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3285         CodeList &GeneratedCode = CodeForPatterns[i].second;
3286         mightNotMatch = false;
3287
3288         for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3289           if (GeneratedCode[j].first == 1) { // predicate.
3290             mightNotMatch = true;
3291             break;
3292           }
3293         }
3294       
3295         // If this pattern definitely matches, and if it isn't the last one, the
3296         // patterns after it CANNOT ever match.  Error out.
3297         if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3298           std::cerr << "Pattern '";
3299           CodeForPatterns[i].first->getSrcPattern()->print(std::cerr);
3300           std::cerr << "' is impossible to select!\n";
3301           exit(1);
3302         }
3303       }
3304
3305       // Factor target node emission code (emitted by EmitResultCode) into
3306       // separate functions. Uniquing and share them among all instruction
3307       // selection routines.
3308       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3309         CodeList &GeneratedCode = CodeForPatterns[i].second;
3310         std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3311         std::vector<std::string> &TargetVTs = PatternVTs[i];
3312         std::set<std::string> Decls = PatternDecls[i];
3313         std::vector<std::string> AddedInits;
3314         int CodeSize = (int)GeneratedCode.size();
3315         int LastPred = -1;
3316         for (int j = CodeSize-1; j >= 0; --j) {
3317           if (LastPred == -1 && GeneratedCode[j].first == 1)
3318             LastPred = j;
3319           else if (LastPred != -1 && GeneratedCode[j].first == 2)
3320             AddedInits.push_back(GeneratedCode[j].second);
3321         }
3322
3323         std::string CalleeCode = "(const SDOperand &N";
3324         std::string CallerCode = "(N";
3325         for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3326           CalleeCode += ", unsigned Opc" + utostr(j);
3327           CallerCode += ", " + TargetOpcodes[j];
3328         }
3329         for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3330           CalleeCode += ", MVT::ValueType VT" + utostr(j);
3331           CallerCode += ", " + TargetVTs[j];
3332         }
3333         for (std::set<std::string>::iterator
3334                I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3335           std::string Name = *I;
3336           CalleeCode += ", SDOperand &" + Name;
3337           CallerCode += ", " + Name;
3338         }
3339         CallerCode += ");";
3340         CalleeCode += ") ";
3341         // Prevent emission routines from being inlined to reduce selection
3342         // routines stack frame sizes.
3343         CalleeCode += "DISABLE_INLINE ";
3344         CalleeCode += "{\n";
3345
3346         for (std::vector<std::string>::const_reverse_iterator
3347                I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3348           CalleeCode += "  " + *I + "\n";
3349
3350         for (int j = LastPred+1; j < CodeSize; ++j)
3351           CalleeCode += "  " + GeneratedCode[j].second + "\n";
3352         for (int j = LastPred+1; j < CodeSize; ++j)
3353           GeneratedCode.pop_back();
3354         CalleeCode += "}\n";
3355
3356         // Uniquing the emission routines.
3357         unsigned EmitFuncNum;
3358         std::map<std::string, unsigned>::iterator EFI =
3359           EmitFunctions.find(CalleeCode);
3360         if (EFI != EmitFunctions.end()) {
3361           EmitFuncNum = EFI->second;
3362         } else {
3363           EmitFuncNum = EmitFunctions.size();
3364           EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3365           OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
3366         }
3367
3368         // Replace the emission code within selection routines with calls to the
3369         // emission functions.
3370         CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
3371         GeneratedCode.push_back(std::make_pair(false, CallerCode));
3372       }
3373
3374       // Print function.
3375       std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR)
3376         ? getEnumName(OpVT).substr(5) : "" ;
3377       std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3378         OpcodeVTMap.find(OpName);
3379       if (OpVTI == OpcodeVTMap.end()) {
3380         std::vector<std::string> VTSet;
3381         VTSet.push_back(OpVTStr);
3382         OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3383       } else
3384         OpVTI->second.push_back(OpVTStr);
3385
3386       OS << "SDNode *Select_" << OpName << (OpVTStr != "" ? "_" : "")
3387          << OpVTStr << "(const SDOperand &N) {\n";    
3388
3389       // Loop through and reverse all of the CodeList vectors, as we will be
3390       // accessing them from their logical front, but accessing the end of a
3391       // vector is more efficient.
3392       for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3393         CodeList &GeneratedCode = CodeForPatterns[i].second;
3394         std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3395       }
3396     
3397       // Next, reverse the list of patterns itself for the same reason.
3398       std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3399     
3400       // Emit all of the patterns now, grouped together to share code.
3401       EmitPatterns(CodeForPatterns, 2, OS);
3402     
3403       // If the last pattern has predicates (which could fail) emit code to catch
3404       // the case where nothing handles a pattern.
3405       if (mightNotMatch) {
3406         OS << "  std::cerr << \"Cannot yet select: \";\n";
3407         if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3408             OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3409             OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3410           OS << "  N.Val->dump(CurDAG);\n";
3411         } else {
3412           OS << "  unsigned iid = cast<ConstantSDNode>(N.getOperand("
3413             "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3414              << "  std::cerr << \"intrinsic %\"<< "
3415             "Intrinsic::getName((Intrinsic::ID)iid);\n";
3416         }
3417         OS << "  std::cerr << '\\n';\n"
3418            << "  abort();\n"
3419            << "  return NULL;\n";
3420       }
3421       OS << "}\n\n";
3422     }
3423   }
3424   
3425   // Emit boilerplate.
3426   OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
3427      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3428      << "  AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
3429      << "  // Select the flag operand.\n"
3430      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
3431      << "    AddToISelQueue(Ops.back());\n"
3432      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3433      << "  std::vector<MVT::ValueType> VTs;\n"
3434      << "  VTs.push_back(MVT::Other);\n"
3435      << "  VTs.push_back(MVT::Flag);\n"
3436      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3437                  "Ops.size());\n"
3438      << "  return New.Val;\n"
3439      << "}\n\n";
3440   
3441   OS << "// The main instruction selector code.\n"
3442      << "SDNode *SelectCode(SDOperand N) {\n"
3443      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3444      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3445      << "INSTRUCTION_LIST_END)) {\n"
3446      << "    return NULL;   // Already selected.\n"
3447      << "  }\n\n"
3448      << "  switch (N.getOpcode()) {\n"
3449      << "  default: break;\n"
3450      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
3451      << "  case ISD::BasicBlock:\n"
3452      << "  case ISD::Register:\n"
3453      << "  case ISD::HANDLENODE:\n"
3454      << "  case ISD::TargetConstant:\n"
3455      << "  case ISD::TargetConstantPool:\n"
3456      << "  case ISD::TargetFrameIndex:\n"
3457      << "  case ISD::TargetJumpTable:\n"
3458      << "  case ISD::TargetGlobalAddress: {\n"
3459      << "    return NULL;\n"
3460      << "  }\n"
3461      << "  case ISD::AssertSext:\n"
3462      << "  case ISD::AssertZext: {\n"
3463      << "    AddToISelQueue(N.getOperand(0));\n"
3464      << "    ReplaceUses(N, N.getOperand(0));\n"
3465      << "    return NULL;\n"
3466      << "  }\n"
3467      << "  case ISD::TokenFactor:\n"
3468      << "  case ISD::CopyFromReg:\n"
3469      << "  case ISD::CopyToReg: {\n"
3470      << "    for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3471      << "      AddToISelQueue(N.getOperand(i));\n"
3472      << "    return NULL;\n"
3473      << "  }\n"
3474      << "  case ISD::INLINEASM:  return Select_INLINEASM(N);\n";
3475
3476     
3477   // Loop over all of the case statements, emiting a call to each method we
3478   // emitted above.
3479   for (std::map<Record*, std::vector<PatternToMatch*>,
3480                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3481        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3482     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3483     const std::string &OpName = PBOI->first->getName();
3484     // Potentially multiple versions of select for this opcode. One for each
3485     // ValueType of the node (or its first true operand if it doesn't produce a
3486     // result.
3487     std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3488       OpcodeVTMap.find(OpName);
3489     std::vector<std::string> &OpVTs = OpVTI->second;
3490     OS << "  case " << OpcodeInfo.getEnumName() << ": {\n";
3491     if (OpVTs.size() == 1) {
3492       std::string &VTStr = OpVTs[0];
3493       OS << "    return Select_" << OpName
3494          << (VTStr != "" ? "_" : "") << VTStr << "(N);\n";
3495     } else {
3496       if (OpcodeInfo.getNumResults())
3497         OS << "    MVT::ValueType NVT = N.Val->getValueType(0);\n";
3498       else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain))
3499         OS << "    MVT::ValueType NVT = (N.getNumOperands() > 1) ?"
3500            << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n";
3501       else
3502         OS << "    MVT::ValueType NVT = (N.getNumOperands() > 0) ?"
3503            << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n";
3504       int Default = -1;
3505       OS << "    switch (NVT) {\n";
3506       for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3507         std::string &VTStr = OpVTs[i];
3508         if (VTStr == "") {
3509           Default = i;
3510           continue;
3511         }
3512         OS << "    case MVT::" << VTStr << ":\n"
3513            << "      return Select_" << OpName
3514            << "_" << VTStr << "(N);\n";
3515       }
3516       OS << "    default:\n";
3517       if (Default != -1)
3518         OS << "      return Select_" << OpName << "(N);\n";
3519       else
3520         OS << "      break;\n";
3521       OS << "    }\n";
3522       OS << "    break;\n";
3523     }
3524     OS << "  }\n";
3525   }
3526
3527   OS << "  } // end of big switch.\n\n"
3528      << "  std::cerr << \"Cannot yet select: \";\n"
3529      << "  if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3530      << "      N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3531      << "      N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3532      << "    N.Val->dump(CurDAG);\n"
3533      << "  } else {\n"
3534      << "    unsigned iid = cast<ConstantSDNode>(N.getOperand("
3535                "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3536      << "    std::cerr << \"intrinsic %\"<< "
3537                         "Intrinsic::getName((Intrinsic::ID)iid);\n"
3538      << "  }\n"
3539      << "  std::cerr << '\\n';\n"
3540      << "  abort();\n"
3541      << "  return NULL;\n"
3542      << "}\n";
3543 }
3544
3545 void DAGISelEmitter::run(std::ostream &OS) {
3546   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3547                        " target", OS);
3548   
3549   OS << "// *** NOTE: This file is #included into the middle of the target\n"
3550      << "// *** instruction selector class.  These functions are really "
3551      << "methods.\n\n";
3552   
3553   OS << "#include \"llvm/Support/Compiler.h\"\n";
3554
3555   OS << "// Instruction selector priority queue:\n"
3556      << "std::vector<SDNode*> ISelQueue;\n";
3557   OS << "/// Keep track of nodes which have already been added to queue.\n"
3558      << "unsigned char *ISelQueued;\n";
3559   OS << "/// Keep track of nodes which have already been selected.\n"
3560      << "unsigned char *ISelSelected;\n";
3561   OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3562      << "std::vector<SDNode*> ISelKilled;\n\n";
3563
3564   OS << "/// Sorting functions for the selection queue.\n"
3565      << "struct isel_sort : public std::binary_function"
3566      << "<SDNode*, SDNode*, bool> {\n"
3567      << "  bool operator()(const SDNode* left, const SDNode* right) "
3568      << "const {\n"
3569      << "    return (left->getNodeId() > right->getNodeId());\n"
3570      << "  }\n"
3571      << "};\n\n";
3572
3573   OS << "inline void setQueued(int Id) {\n";
3574   OS << "  ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
3575   OS << "}\n";
3576   OS << "inline bool isQueued(int Id) {\n";
3577   OS << "  return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
3578   OS << "}\n";
3579   OS << "inline void setSelected(int Id) {\n";
3580   OS << "  ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
3581   OS << "}\n";
3582   OS << "inline bool isSelected(int Id) {\n";
3583   OS << "  return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3584   OS << "}\n\n";
3585
3586   OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
3587   OS << "  int Id = N.Val->getNodeId();\n";
3588   OS << "  if (Id != -1 && !isQueued(Id)) {\n";
3589   OS << "    ISelQueue.push_back(N.Val);\n";
3590  OS << "    std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3591   OS << "    setQueued(Id);\n";
3592   OS << "  }\n";
3593   OS << "}\n\n";
3594
3595   OS << "inline void RemoveKilled() {\n";
3596 OS << "  unsigned NumKilled = ISelKilled.size();\n";
3597   OS << "  if (NumKilled) {\n";
3598   OS << "    for (unsigned i = 0; i != NumKilled; ++i) {\n";
3599   OS << "      SDNode *Temp = ISelKilled[i];\n";
3600   OS << "      std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n";
3601   OS << "    };\n";
3602  OS << "    std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3603   OS << "    ISelKilled.clear();\n";
3604   OS << "  }\n";
3605   OS << "}\n\n";
3606
3607   OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
3608   OS << "  CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3609   OS << "  setSelected(F.Val->getNodeId());\n";
3610   OS << "  RemoveKilled();\n";
3611   OS << "}\n";
3612   OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3613   OS << "  CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3614   OS << "  setSelected(F->getNodeId());\n";
3615   OS << "  RemoveKilled();\n";
3616   OS << "}\n\n";
3617
3618   OS << "void DeleteNode(SDNode *N) {\n";
3619   OS << "  CurDAG->DeleteNode(N);\n";
3620   OS << "  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); "
3621      << "I != E; ++I) {\n";
3622   OS << "    SDNode *Operand = I->Val;\n";
3623   OS << "    if (Operand->use_empty())\n";
3624   OS << "      DeleteNode(Operand);\n";
3625   OS << "  }\n";
3626   OS << "}\n";
3627
3628   OS << "// SelectRoot - Top level entry to DAG isel.\n";
3629   OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3630   OS << "  SelectRootInit();\n";
3631   OS << "  unsigned NumBytes = (DAGSize + 7) / 8;\n";
3632   OS << "  ISelQueued   = new unsigned char[NumBytes];\n";
3633   OS << "  ISelSelected = new unsigned char[NumBytes];\n";
3634   OS << "  memset(ISelQueued,   0, NumBytes);\n";
3635   OS << "  memset(ISelSelected, 0, NumBytes);\n";
3636   OS << "\n";
3637   OS << "  // Create a dummy node (which is not added to allnodes), that adds\n"
3638      << "  // a reference to the root node, preventing it from being deleted,\n"
3639      << "  // and tracking any changes of the root.\n"
3640      << "  HandleSDNode Dummy(CurDAG->getRoot());\n"
3641      << "  ISelQueue.push_back(CurDAG->getRoot().Val);\n";
3642   OS << "  while (!ISelQueue.empty()) {\n";
3643   OS << "    SDNode *Node = ISelQueue.front();\n";
3644   OS << "    std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3645   OS << "    ISelQueue.pop_back();\n";
3646   OS << "    if (!isSelected(Node->getNodeId())) {\n";
3647   OS << "      SDNode *ResNode = Select(SDOperand(Node, 0));\n";
3648   OS << "      if (ResNode != Node) {\n";
3649   OS << "        if (ResNode)\n";
3650   OS << "          ReplaceUses(Node, ResNode);\n";
3651   OS << "        if (Node->use_empty()) // Don't delete EntryToken, etc.\n";
3652   OS << "          DeleteNode(Node);\n";
3653   OS << "      }\n";
3654   OS << "    }\n";
3655   OS << "  }\n";
3656   OS << "\n";
3657   OS << "  delete[] ISelQueued;\n";
3658   OS << "  ISelQueued = NULL;\n";
3659   OS << "  delete[] ISelSelected;\n";
3660   OS << "  ISelSelected = NULL;\n";
3661   OS << "  return Dummy.getValue();\n";
3662   OS << "}\n";
3663   
3664   Intrinsics = LoadIntrinsics(Records);
3665   ParseNodeInfo();
3666   ParseNodeTransforms(OS);
3667   ParseComplexPatterns();
3668   ParsePatternFragments(OS);
3669   ParseInstructions();
3670   ParsePatterns();
3671   
3672   // Generate variants.  For example, commutative patterns can match
3673   // multiple ways.  Add them to PatternsToMatch as well.
3674   GenerateVariants();
3675
3676   
3677   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3678         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3679           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3680           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3681           std::cerr << "\n";
3682         });
3683   
3684   // At this point, we have full information about the 'Patterns' we need to
3685   // parse, both implicitly from instructions as well as from explicit pattern
3686   // definitions.  Emit the resultant instruction selector.
3687   EmitInstructionSelector(OS);  
3688   
3689   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3690        E = PatternFragments.end(); I != E; ++I)
3691     delete I->second;
3692   PatternFragments.clear();
3693
3694   Instructions.clear();
3695 }