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