Change approach so that we get codegen for free for intrinsics. With this,
[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 (i == 0)
1346         Res0Node = RNode;
1347       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1348       if (R == 0)
1349         I->error("Operand $" + OpName + " should be a set destination: all "
1350                  "outputs must occur before inputs in operand list!");
1351       
1352       if (CGI.OperandList[i].Rec != R)
1353         I->error("Operand $" + OpName + " class mismatch!");
1354       
1355       // Remember the return type.
1356       Results.push_back(CGI.OperandList[i].Rec);
1357       
1358       // Okay, this one checks out.
1359       InstResults.erase(OpName);
1360     }
1361
1362     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1363     // the copy while we're checking the inputs.
1364     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1365
1366     std::vector<TreePatternNode*> ResultNodeOperands;
1367     std::vector<Record*> Operands;
1368     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1369       const std::string &OpName = CGI.OperandList[i].Name;
1370       if (OpName.empty())
1371         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1372
1373       if (!InstInputsCheck.count(OpName))
1374         I->error("Operand $" + OpName +
1375                  " does not appear in the instruction pattern");
1376       TreePatternNode *InVal = InstInputsCheck[OpName];
1377       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1378       
1379       if (InVal->isLeaf() &&
1380           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1381         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1382         if (CGI.OperandList[i].Rec != InRec &&
1383             !InRec->isSubClassOf("ComplexPattern"))
1384           I->error("Operand $" + OpName + "'s register class disagrees"
1385                    " between the operand and pattern");
1386       }
1387       Operands.push_back(CGI.OperandList[i].Rec);
1388       
1389       // Construct the result for the dest-pattern operand list.
1390       TreePatternNode *OpNode = InVal->clone();
1391       
1392       // No predicate is useful on the result.
1393       OpNode->setPredicateFn("");
1394       
1395       // Promote the xform function to be an explicit node if set.
1396       if (Record *Xform = OpNode->getTransformFn()) {
1397         OpNode->setTransformFn(0);
1398         std::vector<TreePatternNode*> Children;
1399         Children.push_back(OpNode);
1400         OpNode = new TreePatternNode(Xform, Children);
1401       }
1402       
1403       ResultNodeOperands.push_back(OpNode);
1404     }
1405     
1406     if (!InstInputsCheck.empty())
1407       I->error("Input operand $" + InstInputsCheck.begin()->first +
1408                " occurs in pattern but not in operands list!");
1409
1410     TreePatternNode *ResultPattern =
1411       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1412     // Copy fully inferred output node type to instruction result pattern.
1413     if (NumResults > 0)
1414       ResultPattern->setTypes(Res0Node->getExtTypes());
1415
1416     // Create and insert the instruction.
1417     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1418     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1419
1420     // Use a temporary tree pattern to infer all types and make sure that the
1421     // constructed result is correct.  This depends on the instruction already
1422     // being inserted into the Instructions map.
1423     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1424     Temp.InferAllTypes();
1425
1426     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1427     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1428     
1429     DEBUG(I->dump());
1430   }
1431    
1432   // If we can, convert the instructions to be patterns that are matched!
1433   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1434        E = Instructions.end(); II != E; ++II) {
1435     DAGInstruction &TheInst = II->second;
1436     TreePattern *I = TheInst.getPattern();
1437     if (I == 0) continue;  // No pattern.
1438
1439     if (I->getNumTrees() != 1) {
1440       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1441       continue;
1442     }
1443     TreePatternNode *Pattern = I->getTree(0);
1444     TreePatternNode *SrcPattern;
1445     if (Pattern->getOperator()->getName() == "set") {
1446       if (Pattern->getNumChildren() != 2)
1447         continue;  // Not a set of a single value (not handled so far)
1448
1449       SrcPattern = Pattern->getChild(1)->clone();    
1450     } else{
1451       // Not a set (store or something?)
1452       SrcPattern = Pattern;
1453     }
1454     
1455     std::string Reason;
1456     if (!SrcPattern->canPatternMatch(Reason, *this))
1457       I->error("Instruction can never match: " + Reason);
1458     
1459     Record *Instr = II->first;
1460     TreePatternNode *DstPattern = TheInst.getResultPattern();
1461     PatternsToMatch.
1462       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1463                                SrcPattern, DstPattern));
1464   }
1465 }
1466
1467 void DAGISelEmitter::ParsePatterns() {
1468   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1469
1470   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1471     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1472     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1473
1474     // Inline pattern fragments into it.
1475     Pattern->InlinePatternFragments();
1476     
1477     // Infer as many types as possible.  If we cannot infer all of them, we can
1478     // never do anything with this pattern: report it to the user.
1479     if (!Pattern->InferAllTypes())
1480       Pattern->error("Could not infer all types in pattern!");
1481
1482     // Validate that the input pattern is correct.
1483     {
1484       std::map<std::string, TreePatternNode*> InstInputs;
1485       std::map<std::string, TreePatternNode*> InstResults;
1486       std::vector<Record*> InstImpInputs;
1487       std::vector<Record*> InstImpResults;
1488       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1489                                   InstInputs, InstResults,
1490                                   InstImpInputs, InstImpResults);
1491     }
1492     
1493     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1494     if (LI->getSize() == 0) continue;  // no pattern.
1495     
1496     // Parse the instruction.
1497     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1498     
1499     // Inline pattern fragments into it.
1500     Result->InlinePatternFragments();
1501     
1502     // Infer as many types as possible.  If we cannot infer all of them, we can
1503     // never do anything with this pattern: report it to the user.
1504     if (!Result->InferAllTypes())
1505       Result->error("Could not infer all types in pattern result!");
1506    
1507     if (Result->getNumTrees() != 1)
1508       Result->error("Cannot handle instructions producing instructions "
1509                     "with temporaries yet!");
1510
1511     // Promote the xform function to be an explicit node if set.
1512     std::vector<TreePatternNode*> ResultNodeOperands;
1513     TreePatternNode *DstPattern = Result->getOnlyTree();
1514     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1515       TreePatternNode *OpNode = DstPattern->getChild(ii);
1516       if (Record *Xform = OpNode->getTransformFn()) {
1517         OpNode->setTransformFn(0);
1518         std::vector<TreePatternNode*> Children;
1519         Children.push_back(OpNode);
1520         OpNode = new TreePatternNode(Xform, Children);
1521       }
1522       ResultNodeOperands.push_back(OpNode);
1523     }
1524     DstPattern = Result->getOnlyTree();
1525     if (!DstPattern->isLeaf())
1526       DstPattern = new TreePatternNode(DstPattern->getOperator(),
1527                                        ResultNodeOperands);
1528     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1529     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1530     Temp.InferAllTypes();
1531
1532     std::string Reason;
1533     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1534       Pattern->error("Pattern can never match: " + Reason);
1535     
1536     PatternsToMatch.
1537       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1538                                Pattern->getOnlyTree(),
1539                                Temp.getOnlyTree()));
1540   }
1541 }
1542
1543 /// CombineChildVariants - Given a bunch of permutations of each child of the
1544 /// 'operator' node, put them together in all possible ways.
1545 static void CombineChildVariants(TreePatternNode *Orig, 
1546                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1547                                  std::vector<TreePatternNode*> &OutVariants,
1548                                  DAGISelEmitter &ISE) {
1549   // Make sure that each operand has at least one variant to choose from.
1550   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1551     if (ChildVariants[i].empty())
1552       return;
1553         
1554   // The end result is an all-pairs construction of the resultant pattern.
1555   std::vector<unsigned> Idxs;
1556   Idxs.resize(ChildVariants.size());
1557   bool NotDone = true;
1558   while (NotDone) {
1559     // Create the variant and add it to the output list.
1560     std::vector<TreePatternNode*> NewChildren;
1561     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1562       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1563     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1564     
1565     // Copy over properties.
1566     R->setName(Orig->getName());
1567     R->setPredicateFn(Orig->getPredicateFn());
1568     R->setTransformFn(Orig->getTransformFn());
1569     R->setTypes(Orig->getExtTypes());
1570     
1571     // If this pattern cannot every match, do not include it as a variant.
1572     std::string ErrString;
1573     if (!R->canPatternMatch(ErrString, ISE)) {
1574       delete R;
1575     } else {
1576       bool AlreadyExists = false;
1577       
1578       // Scan to see if this pattern has already been emitted.  We can get
1579       // duplication due to things like commuting:
1580       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1581       // which are the same pattern.  Ignore the dups.
1582       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1583         if (R->isIsomorphicTo(OutVariants[i])) {
1584           AlreadyExists = true;
1585           break;
1586         }
1587       
1588       if (AlreadyExists)
1589         delete R;
1590       else
1591         OutVariants.push_back(R);
1592     }
1593     
1594     // Increment indices to the next permutation.
1595     NotDone = false;
1596     // Look for something we can increment without causing a wrap-around.
1597     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1598       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1599         NotDone = true;   // Found something to increment.
1600         break;
1601       }
1602       Idxs[IdxsIdx] = 0;
1603     }
1604   }
1605 }
1606
1607 /// CombineChildVariants - A helper function for binary operators.
1608 ///
1609 static void CombineChildVariants(TreePatternNode *Orig, 
1610                                  const std::vector<TreePatternNode*> &LHS,
1611                                  const std::vector<TreePatternNode*> &RHS,
1612                                  std::vector<TreePatternNode*> &OutVariants,
1613                                  DAGISelEmitter &ISE) {
1614   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1615   ChildVariants.push_back(LHS);
1616   ChildVariants.push_back(RHS);
1617   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1618 }  
1619
1620
1621 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1622                                      std::vector<TreePatternNode *> &Children) {
1623   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1624   Record *Operator = N->getOperator();
1625   
1626   // Only permit raw nodes.
1627   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1628       N->getTransformFn()) {
1629     Children.push_back(N);
1630     return;
1631   }
1632
1633   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1634     Children.push_back(N->getChild(0));
1635   else
1636     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1637
1638   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1639     Children.push_back(N->getChild(1));
1640   else
1641     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1642 }
1643
1644 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1645 /// the (potentially recursive) pattern by using algebraic laws.
1646 ///
1647 static void GenerateVariantsOf(TreePatternNode *N,
1648                                std::vector<TreePatternNode*> &OutVariants,
1649                                DAGISelEmitter &ISE) {
1650   // We cannot permute leaves.
1651   if (N->isLeaf()) {
1652     OutVariants.push_back(N);
1653     return;
1654   }
1655
1656   // Look up interesting info about the node.
1657   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1658
1659   // If this node is associative, reassociate.
1660   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1661     // Reassociate by pulling together all of the linked operators 
1662     std::vector<TreePatternNode*> MaximalChildren;
1663     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1664
1665     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1666     // permutations.
1667     if (MaximalChildren.size() == 3) {
1668       // Find the variants of all of our maximal children.
1669       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1670       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1671       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1672       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1673       
1674       // There are only two ways we can permute the tree:
1675       //   (A op B) op C    and    A op (B op C)
1676       // Within these forms, we can also permute A/B/C.
1677       
1678       // Generate legal pair permutations of A/B/C.
1679       std::vector<TreePatternNode*> ABVariants;
1680       std::vector<TreePatternNode*> BAVariants;
1681       std::vector<TreePatternNode*> ACVariants;
1682       std::vector<TreePatternNode*> CAVariants;
1683       std::vector<TreePatternNode*> BCVariants;
1684       std::vector<TreePatternNode*> CBVariants;
1685       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1686       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1687       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1688       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1689       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1690       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1691
1692       // Combine those into the result: (x op x) op x
1693       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1694       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1695       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1696       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1697       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1698       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1699
1700       // Combine those into the result: x op (x op x)
1701       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1702       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1703       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1704       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1705       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1706       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1707       return;
1708     }
1709   }
1710   
1711   // Compute permutations of all children.
1712   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1713   ChildVariants.resize(N->getNumChildren());
1714   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1715     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1716
1717   // Build all permutations based on how the children were formed.
1718   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1719
1720   // If this node is commutative, consider the commuted order.
1721   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1722     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1723     // Consider the commuted order.
1724     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1725                          OutVariants, ISE);
1726   }
1727 }
1728
1729
1730 // GenerateVariants - Generate variants.  For example, commutative patterns can
1731 // match multiple ways.  Add them to PatternsToMatch as well.
1732 void DAGISelEmitter::GenerateVariants() {
1733   
1734   DEBUG(std::cerr << "Generating instruction variants.\n");
1735   
1736   // Loop over all of the patterns we've collected, checking to see if we can
1737   // generate variants of the instruction, through the exploitation of
1738   // identities.  This permits the target to provide agressive matching without
1739   // the .td file having to contain tons of variants of instructions.
1740   //
1741   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1742   // intentionally do not reconsider these.  Any variants of added patterns have
1743   // already been added.
1744   //
1745   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1746     std::vector<TreePatternNode*> Variants;
1747     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1748
1749     assert(!Variants.empty() && "Must create at least original variant!");
1750     Variants.erase(Variants.begin());  // Remove the original pattern.
1751
1752     if (Variants.empty())  // No variants for this pattern.
1753       continue;
1754
1755     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1756           PatternsToMatch[i].getSrcPattern()->dump();
1757           std::cerr << "\n");
1758
1759     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1760       TreePatternNode *Variant = Variants[v];
1761
1762       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1763             Variant->dump();
1764             std::cerr << "\n");
1765       
1766       // Scan to see if an instruction or explicit pattern already matches this.
1767       bool AlreadyExists = false;
1768       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1769         // Check to see if this variant already exists.
1770         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1771           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1772           AlreadyExists = true;
1773           break;
1774         }
1775       }
1776       // If we already have it, ignore the variant.
1777       if (AlreadyExists) continue;
1778
1779       // Otherwise, add it to the list of patterns we have.
1780       PatternsToMatch.
1781         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1782                                  Variant, PatternsToMatch[i].getDstPattern()));
1783     }
1784
1785     DEBUG(std::cerr << "\n");
1786   }
1787 }
1788
1789
1790 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1791 // ComplexPattern.
1792 static bool NodeIsComplexPattern(TreePatternNode *N)
1793 {
1794   return (N->isLeaf() &&
1795           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1796           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1797           isSubClassOf("ComplexPattern"));
1798 }
1799
1800 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1801 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1802 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1803                                                    DAGISelEmitter &ISE)
1804 {
1805   if (N->isLeaf() &&
1806       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1807       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1808       isSubClassOf("ComplexPattern")) {
1809     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1810                                   ->getDef());
1811   }
1812   return NULL;
1813 }
1814
1815 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1816 /// patterns before small ones.  This is used to determine the size of a
1817 /// pattern.
1818 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1819   assert(isExtIntegerInVTs(P->getExtTypes()) || 
1820          isExtFloatingPointInVTs(P->getExtTypes()) ||
1821          P->getExtTypeNum(0) == MVT::isVoid ||
1822          P->getExtTypeNum(0) == MVT::Flag && 
1823          "Not a valid pattern node to size!");
1824   unsigned Size = 2;  // The node itself.
1825   // If the root node is a ConstantSDNode, increases its size.
1826   // e.g. (set R32:$dst, 0).
1827   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1828     Size++;
1829
1830   // FIXME: This is a hack to statically increase the priority of patterns
1831   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1832   // Later we can allow complexity / cost for each pattern to be (optionally)
1833   // specified. To get best possible pattern match we'll need to dynamically
1834   // calculate the complexity of all patterns a dag can potentially map to.
1835   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1836   if (AM)
1837     Size += AM->getNumOperands() * 2;
1838
1839   // If this node has some predicate function that must match, it adds to the
1840   // complexity of this node.
1841   if (!P->getPredicateFn().empty())
1842     ++Size;
1843   
1844   // Count children in the count if they are also nodes.
1845   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1846     TreePatternNode *Child = P->getChild(i);
1847     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1848       Size += getPatternSize(Child, ISE);
1849     else if (Child->isLeaf()) {
1850       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1851         Size += 3;  // Matches a ConstantSDNode (+2) and a specific value (+1).
1852       else if (NodeIsComplexPattern(Child))
1853         Size += getPatternSize(Child, ISE);
1854       else if (!Child->getPredicateFn().empty())
1855         ++Size;
1856     }
1857   }
1858   
1859   return Size;
1860 }
1861
1862 /// getResultPatternCost - Compute the number of instructions for this pattern.
1863 /// This is a temporary hack.  We should really include the instruction
1864 /// latencies in this calculation.
1865 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1866   if (P->isLeaf()) return 0;
1867   
1868   unsigned Cost = 0;
1869   Record *Op = P->getOperator();
1870   if (Op->isSubClassOf("Instruction")) {
1871     Cost++;
1872     CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1873     if (II.usesCustomDAGSchedInserter)
1874       Cost += 10;
1875   }
1876   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1877     Cost += getResultPatternCost(P->getChild(i), ISE);
1878   return Cost;
1879 }
1880
1881 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1882 // In particular, we want to match maximal patterns first and lowest cost within
1883 // a particular complexity first.
1884 struct PatternSortingPredicate {
1885   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1886   DAGISelEmitter &ISE;
1887
1888   bool operator()(PatternToMatch *LHS,
1889                   PatternToMatch *RHS) {
1890     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1891     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1892     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1893     if (LHSSize < RHSSize) return false;
1894     
1895     // If the patterns have equal complexity, compare generated instruction cost
1896     return getResultPatternCost(LHS->getDstPattern(), ISE) <
1897       getResultPatternCost(RHS->getDstPattern(), ISE);
1898   }
1899 };
1900
1901 /// getRegisterValueType - Look up and return the first ValueType of specified 
1902 /// RegisterClass record
1903 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1904   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1905     return RC->getValueTypeNum(0);
1906   return MVT::Other;
1907 }
1908
1909
1910 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1911 /// type information from it.
1912 static void RemoveAllTypes(TreePatternNode *N) {
1913   N->removeTypes();
1914   if (!N->isLeaf())
1915     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1916       RemoveAllTypes(N->getChild(i));
1917 }
1918
1919 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1920   Record *N = Records.getDef(Name);
1921   if (!N || !N->isSubClassOf("SDNode")) {
1922     std::cerr << "Error getting SDNode '" << Name << "'!\n";
1923     exit(1);
1924   }
1925   return N;
1926 }
1927
1928 /// NodeHasProperty - return true if TreePatternNode has the specified
1929 /// property.
1930 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1931                             DAGISelEmitter &ISE)
1932 {
1933   if (N->isLeaf()) return false;
1934   Record *Operator = N->getOperator();
1935   if (!Operator->isSubClassOf("SDNode")) return false;
1936
1937   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1938   return NodeInfo.hasProperty(Property);
1939 }
1940
1941 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1942                                DAGISelEmitter &ISE)
1943 {
1944   if (NodeHasProperty(N, Property, ISE))
1945     return true;
1946
1947   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1948     TreePatternNode *Child = N->getChild(i);
1949     if (PatternHasProperty(Child, Property, ISE))
1950       return true;
1951   }
1952
1953   return false;
1954 }
1955
1956 class PatternCodeEmitter {
1957 private:
1958   DAGISelEmitter &ISE;
1959
1960   // Predicates.
1961   ListInit *Predicates;
1962   // Instruction selector pattern.
1963   TreePatternNode *Pattern;
1964   // Matched instruction.
1965   TreePatternNode *Instruction;
1966   
1967   // Node to name mapping
1968   std::map<std::string, std::string> VariableMap;
1969   // Node to operator mapping
1970   std::map<std::string, Record*> OperatorMap;
1971   // Names of all the folded nodes which produce chains.
1972   std::vector<std::pair<std::string, unsigned> > FoldedChains;
1973   std::set<std::string> Duplicates;
1974
1975   /// GeneratedCode - This is the buffer that we emit code to.  The first bool
1976   /// indicates whether this is an exit predicate (something that should be
1977   /// tested, and if true, the match fails) [when true] or normal code to emit
1978   /// [when false].
1979   std::vector<std::pair<bool, std::string> > &GeneratedCode;
1980   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1981   /// the set of patterns for each top-level opcode.
1982   std::set<std::pair<bool, std::string> > &GeneratedDecl;
1983
1984   std::string ChainName;
1985   bool NewTF;
1986   bool DoReplace;
1987   unsigned TmpNo;
1988   
1989   void emitCheck(const std::string &S) {
1990     if (!S.empty())
1991       GeneratedCode.push_back(std::make_pair(true, S));
1992   }
1993   void emitCode(const std::string &S) {
1994     if (!S.empty())
1995       GeneratedCode.push_back(std::make_pair(false, S));
1996   }
1997   void emitDecl(const std::string &S, bool isSDNode=false) {
1998     assert(!S.empty() && "Invalid declaration");
1999     GeneratedDecl.insert(std::make_pair(isSDNode, S));
2000   }
2001 public:
2002   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2003                      TreePatternNode *pattern, TreePatternNode *instr,
2004                      std::vector<std::pair<bool, std::string> > &gc,
2005                      std::set<std::pair<bool, std::string> > &gd,
2006                      bool dorep)
2007   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2008     GeneratedCode(gc), GeneratedDecl(gd),
2009     NewTF(false), DoReplace(dorep), TmpNo(0) {}
2010
2011   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2012   /// if the match fails. At this point, we already know that the opcode for N
2013   /// matches, and the SDNode for the result has the RootName specified name.
2014   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2015                      const std::string &RootName, const std::string &ParentName,
2016                      const std::string &ChainSuffix, bool &FoundChain) {
2017     bool isRoot = (P == NULL);
2018     // Emit instruction predicates. Each predicate is just a string for now.
2019     if (isRoot) {
2020       std::string PredicateCheck;
2021       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2022         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2023           Record *Def = Pred->getDef();
2024           if (!Def->isSubClassOf("Predicate")) {
2025             Def->dump();
2026             assert(0 && "Unknown predicate type!");
2027           }
2028           if (!PredicateCheck.empty())
2029             PredicateCheck += " || ";
2030           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2031         }
2032       }
2033       
2034       emitCheck(PredicateCheck);
2035     }
2036
2037     if (N->isLeaf()) {
2038       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2039         emitCheck("cast<ConstantSDNode>(" + RootName +
2040                   ")->getSignExtended() == " + itostr(II->getValue()));
2041         return;
2042       } else if (!NodeIsComplexPattern(N)) {
2043         assert(0 && "Cannot match this as a leaf value!");
2044         abort();
2045       }
2046     }
2047   
2048     // If this node has a name associated with it, capture it in VariableMap. If
2049     // we already saw this in the pattern, emit code to verify dagness.
2050     if (!N->getName().empty()) {
2051       std::string &VarMapEntry = VariableMap[N->getName()];
2052       if (VarMapEntry.empty()) {
2053         VarMapEntry = RootName;
2054       } else {
2055         // If we get here, this is a second reference to a specific name.  Since
2056         // we already have checked that the first reference is valid, we don't
2057         // have to recursively match it, just check that it's the same as the
2058         // previously named thing.
2059         emitCheck(VarMapEntry + " == " + RootName);
2060         return;
2061       }
2062
2063       if (!N->isLeaf())
2064         OperatorMap[N->getName()] = N->getOperator();
2065     }
2066
2067
2068     // Emit code to load the child nodes and match their contents recursively.
2069     unsigned OpNo = 0;
2070     bool NodeHasChain = NodeHasProperty   (N, SDNodeInfo::SDNPHasChain, ISE);
2071     bool HasChain     = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2072     bool HasOutFlag   = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag,  ISE);
2073     bool EmittedUseCheck = false;
2074     bool EmittedSlctedCheck = false;
2075     if (HasChain) {
2076       if (NodeHasChain)
2077         OpNo = 1;
2078       if (!isRoot) {
2079         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2080         // Multiple uses of actual result?
2081         emitCheck(RootName + ".hasOneUse()");
2082         EmittedUseCheck = true;
2083         // hasOneUse() check is not strong enough. If the original node has
2084         // already been selected, it may have been replaced with another.
2085         for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2086           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2087                     "))");
2088         
2089         EmittedSlctedCheck = true;
2090         if (NodeHasChain) {
2091           // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2092           // has a chain use.
2093           // This a workaround for this problem:
2094           //
2095           //          [ch, r : ld]
2096           //             ^ ^
2097           //             | |
2098           //      [XX]--/   \- [flag : cmp]
2099           //       ^             ^
2100           //       |             |
2101           //       \---[br flag]-
2102           //
2103           // cmp + br should be considered as a single node as they are flagged
2104           // together. So, if the ld is folded into the cmp, the XX node in the
2105           // graph is now both an operand and a use of the ld/cmp/br node.
2106           if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2107             emitCheck(ParentName + ".Val->isOnlyUse(" +  RootName + ".Val)");
2108
2109           // If the immediate use can somehow reach this node through another
2110           // path, then can't fold it either or it will create a cycle.
2111           // e.g. In the following diagram, XX can reach ld through YY. If
2112           // ld is folded into XX, then YY is both a predecessor and a successor
2113           // of XX.
2114           //
2115           //         [ld]
2116           //         ^  ^
2117           //         |  |
2118           //        /   \---
2119           //      /        [YY]
2120           //      |         ^
2121           //     [XX]-------|
2122           const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2123           if (PInfo.getNumOperands() > 1 ||
2124               PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2125               PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2126               PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2127             if (PInfo.getNumOperands() > 1) {
2128               emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2129                         ".Val)");
2130             } else {
2131               emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2132                         "isNonImmUse(" + ParentName + ".Val, " + RootName +
2133                         ".Val))");
2134             }
2135         }
2136       }
2137
2138       if (NodeHasChain) {
2139         ChainName = "Chain" + ChainSuffix;
2140         emitDecl(ChainName);
2141         if (FoundChain) {
2142          // FIXME: temporary workaround for a common case where chain
2143          // is a TokenFactor and the previous "inner" chain is an operand.
2144           NewTF = true;
2145           emitDecl("OldTF", true);
2146           emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2147                     RootName + ".Val, Chain.Val, OldTF)).Val");
2148         } else {
2149           FoundChain = true;
2150           emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2151         }
2152       }
2153     }
2154
2155     // Don't fold any node which reads or writes a flag and has multiple uses.
2156     // FIXME: We really need to separate the concepts of flag and "glue". Those
2157     // real flag results, e.g. X86CMP output, can have multiple uses.
2158     // FIXME: If the optional incoming flag does not exist. Then it is ok to
2159     // fold it.
2160     if (!isRoot &&
2161         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2162          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2163          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2164       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2165       if (!EmittedUseCheck) {
2166         // Multiple uses of actual result?
2167         emitCheck(RootName + ".hasOneUse()");
2168       }
2169       if (!EmittedSlctedCheck)
2170         // hasOneUse() check is not strong enough. If the original node has
2171         // already been selected, it may have been replaced with another.
2172         for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2173           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2174                     "))");
2175     }
2176
2177     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2178       emitDecl(RootName + utostr(OpNo));
2179       emitCode(RootName + utostr(OpNo) + " = " +
2180                RootName + ".getOperand(" +utostr(OpNo) + ");");
2181       TreePatternNode *Child = N->getChild(i);
2182     
2183       if (!Child->isLeaf()) {
2184         // If it's not a leaf, recursively match.
2185         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2186         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2187                   CInfo.getEnumName());
2188         EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2189                       ChainSuffix + utostr(OpNo), FoundChain);
2190         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2191           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2192                                                 CInfo.getNumResults()));
2193       } else {
2194         // If this child has a name associated with it, capture it in VarMap. If
2195         // we already saw this in the pattern, emit code to verify dagness.
2196         if (!Child->getName().empty()) {
2197           std::string &VarMapEntry = VariableMap[Child->getName()];
2198           if (VarMapEntry.empty()) {
2199             VarMapEntry = RootName + utostr(OpNo);
2200           } else {
2201             // If we get here, this is a second reference to a specific name.
2202             // Since we already have checked that the first reference is valid,
2203             // we don't have to recursively match it, just check that it's the
2204             // same as the previously named thing.
2205             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2206             Duplicates.insert(RootName + utostr(OpNo));
2207             continue;
2208           }
2209         }
2210       
2211         // Handle leaves of various types.
2212         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2213           Record *LeafRec = DI->getDef();
2214           if (LeafRec->isSubClassOf("RegisterClass")) {
2215             // Handle register references.  Nothing to do here.
2216           } else if (LeafRec->isSubClassOf("Register")) {
2217             // Handle register references.
2218           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2219             // Handle complex pattern. Nothing to do here.
2220           } else if (LeafRec->getName() == "srcvalue") {
2221             // Place holder for SRCVALUE nodes. Nothing to do here.
2222           } else if (LeafRec->isSubClassOf("ValueType")) {
2223             // Make sure this is the specified value type.
2224             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2225                       ")->getVT() == MVT::" + LeafRec->getName());
2226           } else if (LeafRec->isSubClassOf("CondCode")) {
2227             // Make sure this is the specified cond code.
2228             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2229                       ")->get() == ISD::" + LeafRec->getName());
2230           } else {
2231             Child->dump();
2232             std::cerr << " ";
2233             assert(0 && "Unknown leaf type!");
2234           }
2235         } else if (IntInit *II =
2236                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2237           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2238           unsigned CTmp = TmpNo++;
2239           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2240                    RootName + utostr(OpNo) + ")->getSignExtended();");
2241
2242           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2243         } else {
2244           Child->dump();
2245           assert(0 && "Unknown leaf type!");
2246         }
2247       }
2248     }
2249
2250     // If there is a node predicate for this, emit the call.
2251     if (!N->getPredicateFn().empty())
2252       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2253   }
2254
2255   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2256   /// we actually have to build a DAG!
2257   std::pair<unsigned, unsigned>
2258   EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2259                  bool isRoot = false) {
2260     // This is something selected from the pattern we matched.
2261     if (!N->getName().empty()) {
2262       std::string &Val = VariableMap[N->getName()];
2263       assert(!Val.empty() &&
2264              "Variable referenced but not defined and not caught earlier!");
2265       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2266         // Already selected this operand, just return the tmpval.
2267         return std::make_pair(1, atoi(Val.c_str()+3));
2268       }
2269
2270       const ComplexPattern *CP;
2271       unsigned ResNo = TmpNo++;
2272       unsigned NumRes = 1;
2273       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2274         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2275         std::string CastType;
2276         switch (N->getTypeNum(0)) {
2277         default: assert(0 && "Unknown type for constant node!");
2278         case MVT::i1:  CastType = "bool"; break;
2279         case MVT::i8:  CastType = "unsigned char"; break;
2280         case MVT::i16: CastType = "unsigned short"; break;
2281         case MVT::i32: CastType = "unsigned"; break;
2282         case MVT::i64: CastType = "uint64_t"; break;
2283         }
2284         emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType + 
2285                  ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2286         emitDecl("Tmp" + utostr(ResNo));
2287         emitCode("Tmp" + utostr(ResNo) + 
2288                  " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) + 
2289                  "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2290       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2291         Record *Op = OperatorMap[N->getName()];
2292         // Transform ExternalSymbol to TargetExternalSymbol
2293         if (Op && Op->getName() == "externalsym") {
2294           emitDecl("Tmp" + utostr(ResNo));
2295           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2296                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2297                    Val + ")->getSymbol(), MVT::" +
2298                    getEnumName(N->getTypeNum(0)) + ");");
2299         } else {
2300           emitDecl("Tmp" + utostr(ResNo));
2301           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2302         }
2303       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2304         Record *Op = OperatorMap[N->getName()];
2305         // Transform GlobalAddress to TargetGlobalAddress
2306         if (Op && Op->getName() == "globaladdr") {
2307           emitDecl("Tmp" + utostr(ResNo));
2308           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2309                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2310                    ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2311                    ");");
2312         } else {
2313           emitDecl("Tmp" + utostr(ResNo));
2314           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2315         }
2316       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2317         emitDecl("Tmp" + utostr(ResNo));
2318         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2319       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2320         emitDecl("Tmp" + utostr(ResNo));
2321         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2322       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2323         std::string Fn = CP->getSelectFunc();
2324         NumRes = CP->getNumOperands();
2325         for (unsigned i = 0; i < NumRes; ++i)
2326           emitDecl("Tmp" + utostr(i+ResNo));
2327
2328         std::string Code = Fn + "(" + Val;
2329         for (unsigned i = 0; i < NumRes; i++)
2330           Code += ", Tmp" + utostr(i + ResNo);
2331         emitCheck(Code + ")");
2332
2333         for (unsigned i = 0; i < NumRes; ++i)
2334           emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2335                    utostr(i+ResNo) + ");");
2336
2337         TmpNo = ResNo + NumRes;
2338       } else {
2339         emitDecl("Tmp" + utostr(ResNo));
2340         // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2341         // node even if it isn't one. Don't select it.
2342         if (LikeLeaf)
2343           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2344         else
2345           emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2346
2347         if (isRoot && N->isLeaf()) {
2348           emitCode("Result = Tmp" + utostr(ResNo) + ";");
2349           emitCode("return;");
2350         }
2351       }
2352       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2353       // value if used multiple times by this pattern result.
2354       Val = "Tmp"+utostr(ResNo);
2355       return std::make_pair(NumRes, ResNo);
2356     }
2357     if (N->isLeaf()) {
2358       // If this is an explicit register reference, handle it.
2359       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2360         unsigned ResNo = TmpNo++;
2361         if (DI->getDef()->isSubClassOf("Register")) {
2362           emitDecl("Tmp" + utostr(ResNo));
2363           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2364                    ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2365                    getEnumName(N->getTypeNum(0)) + ");");
2366           return std::make_pair(1, ResNo);
2367         }
2368       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2369         unsigned ResNo = TmpNo++;
2370         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2371         emitDecl("Tmp" + utostr(ResNo));
2372         emitCode("Tmp" + utostr(ResNo) + 
2373                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2374                  ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2375         return std::make_pair(1, ResNo);
2376       }
2377     
2378       N->dump();
2379       assert(0 && "Unknown leaf type!");
2380       return std::make_pair(1, ~0U);
2381     }
2382
2383     Record *Op = N->getOperator();
2384     if (Op->isSubClassOf("Instruction")) {
2385       const CodeGenTarget &CGT = ISE.getTargetInfo();
2386       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2387       const DAGInstruction &Inst = ISE.getInstruction(Op);
2388       bool HasImpInputs  = Inst.getNumImpOperands() > 0;
2389       bool HasImpResults = Inst.getNumImpResults() > 0;
2390       bool HasOptInFlag = isRoot &&
2391         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2392       bool HasInFlag  = isRoot &&
2393         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2394       bool NodeHasOutFlag = HasImpResults ||
2395         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2396       bool NodeHasChain =
2397         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2398       bool HasChain   = II.hasCtrlDep ||
2399         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2400
2401       if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2402         emitDecl("InFlag");
2403       if (HasOptInFlag)
2404         emitCode("bool HasOptInFlag = false;");
2405
2406       // How many results is this pattern expected to produce?
2407       unsigned PatResults = 0;
2408       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2409         MVT::ValueType VT = Pattern->getTypeNum(i);
2410         if (VT != MVT::isVoid && VT != MVT::Flag)
2411           PatResults++;
2412       }
2413
2414       // Determine operand emission order. Complex pattern first.
2415       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2416       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2417       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2418         TreePatternNode *Child = N->getChild(i);
2419         if (i == 0) {
2420           EmitOrder.push_back(std::make_pair(i, Child));
2421           OI = EmitOrder.begin();
2422         } else if (NodeIsComplexPattern(Child)) {
2423           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2424         } else {
2425           EmitOrder.push_back(std::make_pair(i, Child));
2426         }
2427       }
2428
2429       // Emit all of the operands.
2430       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2431       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2432         unsigned OpOrder       = EmitOrder[i].first;
2433         TreePatternNode *Child = EmitOrder[i].second;
2434         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2435         NumTemps[OpOrder] = NumTemp;
2436       }
2437
2438       // List all the operands in the right order.
2439       std::vector<unsigned> Ops;
2440       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2441         for (unsigned j = 0; j < NumTemps[i].first; j++)
2442           Ops.push_back(NumTemps[i].second + j);
2443       }
2444
2445       // Emit all the chain and CopyToReg stuff.
2446       bool ChainEmitted = HasChain;
2447       if (HasChain)
2448         emitCode("Select(" + ChainName + ", " + ChainName + ");");
2449       if (HasInFlag || HasOptInFlag || HasImpInputs)
2450         EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2451
2452       unsigned NumResults = Inst.getNumResults();    
2453       unsigned ResNo = TmpNo++;
2454       if (!isRoot) {
2455         emitDecl("Tmp" + utostr(ResNo));
2456         std::string Code =
2457           "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
2458           II.Namespace + "::" + II.TheDef->getName();
2459         if (N->getTypeNum(0) != MVT::isVoid)
2460           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2461         if (NodeHasOutFlag)
2462           Code += ", MVT::Flag";
2463
2464         unsigned LastOp = 0;
2465         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2466           LastOp = Ops[i];
2467           Code += ", Tmp" + utostr(LastOp);
2468         }
2469         emitCode(Code + "), 0);");
2470         if (HasChain) {
2471           // Must have at least one result
2472           emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2473                    utostr(NumResults) + ");");
2474         }
2475       } else if (HasChain || NodeHasOutFlag) {
2476         if (HasOptInFlag) {
2477           unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2478           emitDecl("ResNode", true);
2479           emitCode("if (HasOptInFlag)");
2480           std::string Code = "  ResNode = CurDAG->getTargetNode(" +
2481              II.Namespace + "::" + II.TheDef->getName();
2482
2483           // Output order: results, chain, flags
2484           // Result types.
2485           if (NumResults > 0) { 
2486             if (N->getTypeNum(0) != MVT::isVoid)
2487               Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2488           }
2489           if (HasChain)
2490             Code += ", MVT::Other";
2491           if (NodeHasOutFlag)
2492             Code += ", MVT::Flag";
2493
2494           // Inputs.
2495           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2496             Code += ", Tmp" + utostr(Ops[i]);
2497           if (HasChain)  Code += ", " + ChainName;
2498           emitCode(Code + ", InFlag);");
2499
2500           emitCode("else");
2501           Code = "  ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2502                  II.TheDef->getName();
2503
2504           // Output order: results, chain, flags
2505           // Result types.
2506           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2507             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2508           if (HasChain)
2509             Code += ", MVT::Other";
2510           if (NodeHasOutFlag)
2511             Code += ", MVT::Flag";
2512
2513           // Inputs.
2514           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2515             Code += ", Tmp" + utostr(Ops[i]);
2516           if (HasChain) Code += ", " + ChainName + ");";
2517           emitCode(Code);
2518         } else {
2519           emitDecl("ResNode", true);
2520           std::string Code = "ResNode = CurDAG->getTargetNode(" +
2521             II.Namespace + "::" + II.TheDef->getName();
2522
2523           // Output order: results, chain, flags
2524           // Result types.
2525           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2526             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2527           if (HasChain)
2528             Code += ", MVT::Other";
2529           if (NodeHasOutFlag)
2530             Code += ", MVT::Flag";
2531
2532           // Inputs.
2533           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2534             Code += ", Tmp" + utostr(Ops[i]);
2535           if (HasChain) Code += ", " + ChainName;
2536           if (HasInFlag || HasImpInputs) Code += ", InFlag";
2537           emitCode(Code + ");");
2538         }
2539
2540         if (NewTF)
2541           emitCode("if (OldTF) "
2542                    "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2543                    ChainName + ".Val, 0);");
2544
2545         for (unsigned i = 0; i < NumResults; i++)
2546           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2547                    utostr(i) + ", ResNode, " + utostr(i) + ");");
2548
2549         if (NodeHasOutFlag)
2550           emitCode("InFlag = SDOperand(ResNode, " + 
2551                    utostr(NumResults + (unsigned)HasChain) + ");");
2552
2553         if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2554           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2555                    "0, ResNode, 0);");
2556           NumResults = 1;
2557         }
2558
2559         if (NodeHasChain) {
2560           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + 
2561                    utostr(PatResults) + ", ResNode, " +
2562                    utostr(NumResults) + ");");
2563           if (DoReplace)
2564             emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2565                      utostr(PatResults) + ", " + "ResNode, " +
2566                      utostr(NumResults) + ");");
2567         }
2568
2569         if (FoldedChains.size() > 0) {
2570           std::string Code;
2571           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2572             emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2573                      FoldedChains[j].first + ".Val, " + 
2574                      utostr(FoldedChains[j].second) + ", ResNode, " +
2575                      utostr(NumResults) + ");");
2576
2577           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2578             std::string Code =
2579               FoldedChains[j].first + ".Val, " +
2580               utostr(FoldedChains[j].second) + ", ";
2581             emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2582                      utostr(NumResults) + ");");
2583           }
2584         }
2585
2586         if (NodeHasOutFlag)
2587           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2588                    utostr(PatResults + (unsigned)NodeHasChain) +
2589                    ", InFlag.Val, InFlag.ResNo);");
2590
2591         // User does not expect the instruction would produce a chain!
2592         bool AddedChain = HasChain && !NodeHasChain;
2593         if (AddedChain && NodeHasOutFlag) {
2594           if (PatResults == 0) {
2595             emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2596           } else {
2597             emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2598             emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2599             emitCode("else");
2600             emitCode("  Result = SDOperand(ResNode, N.ResNo+1);");
2601           }
2602         } else {
2603           emitCode("Result = SDOperand(ResNode, N.ResNo);");
2604         }
2605       } else {
2606         // If this instruction is the root, and if there is only one use of it,
2607         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2608         emitCode("if (N.Val->hasOneUse()) {");
2609         std::string Code = "  Result = CurDAG->SelectNodeTo(N.Val, " +
2610           II.Namespace + "::" + II.TheDef->getName();
2611         if (N->getTypeNum(0) != MVT::isVoid)
2612           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2613         if (NodeHasOutFlag)
2614           Code += ", MVT::Flag";
2615         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2616           Code += ", Tmp" + utostr(Ops[i]);
2617         if (HasInFlag || HasImpInputs)
2618           Code += ", InFlag";
2619         emitCode(Code + ");");
2620         emitCode("} else {");
2621         emitDecl("ResNode", true);
2622         Code = "  ResNode = CurDAG->getTargetNode(" +
2623                II.Namespace + "::" + II.TheDef->getName();
2624         if (N->getTypeNum(0) != MVT::isVoid)
2625           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2626         if (NodeHasOutFlag)
2627           Code += ", MVT::Flag";
2628         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2629           Code += ", Tmp" + utostr(Ops[i]);
2630         if (HasInFlag || HasImpInputs)
2631           Code += ", InFlag";
2632         emitCode(Code + ");");
2633         emitCode("  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2634                  "ResNode, 0);");
2635         emitCode("  Result = SDOperand(ResNode, 0);");
2636         emitCode("}");
2637       }
2638
2639       if (isRoot)
2640         emitCode("return;");
2641       return std::make_pair(1, ResNo);
2642     } else if (Op->isSubClassOf("SDNodeXForm")) {
2643       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2644       // PatLeaf node - the operand may or may not be a leaf node. But it should
2645       // behave like one.
2646       unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2647       unsigned ResNo = TmpNo++;
2648       emitDecl("Tmp" + utostr(ResNo));
2649       emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2650                + "(Tmp" + utostr(OpVal) + ".Val);");
2651       if (isRoot) {
2652         emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2653                  "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2654                  utostr(ResNo) + ".ResNo);");
2655         emitCode("Result = Tmp" + utostr(ResNo) + ";");
2656         emitCode("return;");
2657       }
2658       return std::make_pair(1, ResNo);
2659     } else {
2660       N->dump();
2661       std::cerr << "\n";
2662       throw std::string("Unknown node in result pattern!");
2663     }
2664   }
2665
2666   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2667   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2668   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2669   /// for, this returns true otherwise false if Pat has all types.
2670   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2671                           const std::string &Prefix) {
2672     // Did we find one?
2673     if (!Pat->hasTypeSet()) {
2674       // Move a type over from 'other' to 'pat'.
2675       Pat->setTypes(Other->getExtTypes());
2676       emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2677                 getName(Pat->getTypeNum(0)));
2678       return true;
2679     }
2680   
2681     unsigned OpNo =
2682       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2683     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2684       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2685                              Prefix + utostr(OpNo)))
2686         return true;
2687     return false;
2688   }
2689
2690 private:
2691   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2692   /// being built.
2693   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2694                             bool &ChainEmitted, bool isRoot = false) {
2695     const CodeGenTarget &T = ISE.getTargetInfo();
2696     unsigned OpNo =
2697       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2698     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2699     bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2700     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2701       TreePatternNode *Child = N->getChild(i);
2702       if (!Child->isLeaf()) {
2703         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2704       } else {
2705         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2706           if (!Child->getName().empty()) {
2707             std::string Name = RootName + utostr(OpNo);
2708             if (Duplicates.find(Name) != Duplicates.end())
2709               // A duplicate! Do not emit a copy for this node.
2710               continue;
2711           }
2712
2713           Record *RR = DI->getDef();
2714           if (RR->isSubClassOf("Register")) {
2715             MVT::ValueType RVT = getRegisterValueType(RR, T);
2716             if (RVT == MVT::Flag) {
2717               emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2718             } else {
2719               if (!ChainEmitted) {
2720                 emitDecl("Chain");
2721                 emitCode("Chain = CurDAG->getEntryNode();");
2722                 ChainName = "Chain";
2723                 ChainEmitted = true;
2724               }
2725               emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2726                        RootName + utostr(OpNo) + ");");
2727               emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2728                        ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2729                        ", MVT::" + getEnumName(RVT) + "), " +
2730                        RootName + utostr(OpNo) + ", InFlag).Val;");
2731               emitCode(ChainName + " = SDOperand(ResNode, 0);");
2732               emitCode("InFlag = SDOperand(ResNode, 1);");
2733             }
2734           }
2735         }
2736       }
2737     }
2738
2739     if (HasInFlag || HasOptInFlag) {
2740       std::string Code;
2741       if (HasOptInFlag) {
2742         emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2743                  ") {");
2744         Code = "  ";
2745       }
2746       emitCode(Code + "Select(InFlag, " + RootName +
2747                ".getOperand(" + utostr(OpNo) + "));");
2748       if (HasOptInFlag) {
2749         emitCode("  HasOptInFlag = true;");
2750         emitCode("}");
2751       }
2752     }
2753   }
2754
2755   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2756   /// as specified by the instruction. It returns true if any copy is
2757   /// emitted.
2758   bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2759     bool RetVal = false;
2760     Record *Op = N->getOperator();
2761     if (Op->isSubClassOf("Instruction")) {
2762       const DAGInstruction &Inst = ISE.getInstruction(Op);
2763       const CodeGenTarget &CGT = ISE.getTargetInfo();
2764       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2765       unsigned NumImpResults  = Inst.getNumImpResults();
2766       for (unsigned i = 0; i < NumImpResults; i++) {
2767         Record *RR = Inst.getImpResult(i);
2768         if (RR->isSubClassOf("Register")) {
2769           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2770           if (RVT != MVT::Flag) {
2771             if (!ChainEmitted) {
2772               emitDecl("Chain");
2773               emitCode("Chain = CurDAG->getEntryNode();");
2774               ChainEmitted = true;
2775               ChainName = "Chain";
2776             }
2777             emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2778                      ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2779                      ", InFlag).Val;");
2780             emitCode(ChainName + " = SDOperand(ResNode, 1);");
2781             emitCode("InFlag = SDOperand(ResNode, 2);");
2782             RetVal = true;
2783           }
2784         }
2785       }
2786     }
2787     return RetVal;
2788   }
2789 };
2790
2791 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2792 /// stream to match the pattern, and generate the code for the match if it
2793 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2794 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2795                       std::vector<std::pair<bool, std::string> > &GeneratedCode,
2796                          std::set<std::pair<bool, std::string> > &GeneratedDecl,
2797                                             bool DoReplace) {
2798   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2799                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2800                              GeneratedCode, GeneratedDecl, DoReplace);
2801
2802   // Emit the matcher, capturing named arguments in VariableMap.
2803   bool FoundChain = false;
2804   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2805
2806   // TP - Get *SOME* tree pattern, we don't care which.
2807   TreePattern &TP = *PatternFragments.begin()->second;
2808   
2809   // At this point, we know that we structurally match the pattern, but the
2810   // types of the nodes may not match.  Figure out the fewest number of type 
2811   // comparisons we need to emit.  For example, if there is only one integer
2812   // type supported by a target, there should be no type comparisons at all for
2813   // integer patterns!
2814   //
2815   // To figure out the fewest number of type checks needed, clone the pattern,
2816   // remove the types, then perform type inference on the pattern as a whole.
2817   // If there are unresolved types, emit an explicit check for those types,
2818   // apply the type to the tree, then rerun type inference.  Iterate until all
2819   // types are resolved.
2820   //
2821   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2822   RemoveAllTypes(Pat);
2823   
2824   do {
2825     // Resolve/propagate as many types as possible.
2826     try {
2827       bool MadeChange = true;
2828       while (MadeChange)
2829         MadeChange = Pat->ApplyTypeConstraints(TP,
2830                                                true/*Ignore reg constraints*/);
2831     } catch (...) {
2832       assert(0 && "Error: could not find consistent types for something we"
2833              " already decided was ok!");
2834       abort();
2835     }
2836
2837     // Insert a check for an unresolved type and add it to the tree.  If we find
2838     // an unresolved type to add a check for, this returns true and we iterate,
2839     // otherwise we are done.
2840   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2841
2842   Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2843   delete Pat;
2844 }
2845
2846 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
2847 /// a line causes any of them to be empty, remove them and return true when
2848 /// done.
2849 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
2850                           std::vector<std::pair<bool, std::string> > > >
2851                           &Patterns) {
2852   bool ErasedPatterns = false;
2853   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2854     Patterns[i].second.pop_back();
2855     if (Patterns[i].second.empty()) {
2856       Patterns.erase(Patterns.begin()+i);
2857       --i; --e;
2858       ErasedPatterns = true;
2859     }
2860   }
2861   return ErasedPatterns;
2862 }
2863
2864 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2865 /// code together between the patterns.
2866 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
2867                                   std::vector<std::pair<bool, std::string> > > >
2868                                   &Patterns, unsigned Indent,
2869                                   std::ostream &OS) {
2870   typedef std::pair<bool, std::string> CodeLine;
2871   typedef std::vector<CodeLine> CodeList;
2872   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2873   
2874   if (Patterns.empty()) return;
2875   
2876   // Figure out how many patterns share the next code line.  Explicitly copy
2877   // FirstCodeLine so that we don't invalidate a reference when changing
2878   // Patterns.
2879   const CodeLine FirstCodeLine = Patterns.back().second.back();
2880   unsigned LastMatch = Patterns.size()-1;
2881   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2882     --LastMatch;
2883   
2884   // If not all patterns share this line, split the list into two pieces.  The
2885   // first chunk will use this line, the second chunk won't.
2886   if (LastMatch != 0) {
2887     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2888     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2889     
2890     // FIXME: Emit braces?
2891     if (Shared.size() == 1) {
2892       PatternToMatch &Pattern = *Shared.back().first;
2893       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2894       Pattern.getSrcPattern()->print(OS);
2895       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2896       Pattern.getDstPattern()->print(OS);
2897       OS << "\n";
2898       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2899          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2900          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2901     }
2902     if (!FirstCodeLine.first) {
2903       OS << std::string(Indent, ' ') << "{\n";
2904       Indent += 2;
2905     }
2906     EmitPatterns(Shared, Indent, OS);
2907     if (!FirstCodeLine.first) {
2908       Indent -= 2;
2909       OS << std::string(Indent, ' ') << "}\n";
2910     }
2911     
2912     if (Other.size() == 1) {
2913       PatternToMatch &Pattern = *Other.back().first;
2914       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2915       Pattern.getSrcPattern()->print(OS);
2916       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2917       Pattern.getDstPattern()->print(OS);
2918       OS << "\n";
2919       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2920          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2921          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2922     }
2923     EmitPatterns(Other, Indent, OS);
2924     return;
2925   }
2926   
2927   // Remove this code from all of the patterns that share it.
2928   bool ErasedPatterns = EraseCodeLine(Patterns);
2929   
2930   bool isPredicate = FirstCodeLine.first;
2931   
2932   // Otherwise, every pattern in the list has this line.  Emit it.
2933   if (!isPredicate) {
2934     // Normal code.
2935     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2936   } else {
2937     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2938     
2939     // If the next code line is another predicate, and if all of the pattern
2940     // in this group share the same next line, emit it inline now.  Do this
2941     // until we run out of common predicates.
2942     while (!ErasedPatterns && Patterns.back().second.back().first) {
2943       // Check that all of fhe patterns in Patterns end with the same predicate.
2944       bool AllEndWithSamePredicate = true;
2945       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2946         if (Patterns[i].second.back() != Patterns.back().second.back()) {
2947           AllEndWithSamePredicate = false;
2948           break;
2949         }
2950       // If all of the predicates aren't the same, we can't share them.
2951       if (!AllEndWithSamePredicate) break;
2952       
2953       // Otherwise we can.  Emit it shared now.
2954       OS << " &&\n" << std::string(Indent+4, ' ')
2955          << Patterns.back().second.back().second;
2956       ErasedPatterns = EraseCodeLine(Patterns);
2957     }
2958     
2959     OS << ") {\n";
2960     Indent += 2;
2961   }
2962   
2963   EmitPatterns(Patterns, Indent, OS);
2964   
2965   if (isPredicate)
2966     OS << std::string(Indent-2, ' ') << "}\n";
2967 }
2968
2969
2970
2971 namespace {
2972   /// CompareByRecordName - An ordering predicate that implements less-than by
2973   /// comparing the names records.
2974   struct CompareByRecordName {
2975     bool operator()(const Record *LHS, const Record *RHS) const {
2976       // Sort by name first.
2977       if (LHS->getName() < RHS->getName()) return true;
2978       // If both names are equal, sort by pointer.
2979       return LHS->getName() == RHS->getName() && LHS < RHS;
2980     }
2981   };
2982 }
2983
2984 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2985   std::string InstNS = Target.inst_begin()->second.Namespace;
2986   if (!InstNS.empty()) InstNS += "::";
2987   
2988   // Group the patterns by their top-level opcodes.
2989   std::map<Record*, std::vector<PatternToMatch*>,
2990     CompareByRecordName> PatternsByOpcode;
2991   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2992     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2993     if (!Node->isLeaf()) {
2994       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2995     } else {
2996       const ComplexPattern *CP;
2997       if (IntInit *II = 
2998           dynamic_cast<IntInit*>(Node->getLeafValue())) {
2999         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3000       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3001         std::vector<Record*> OpNodes = CP->getRootNodes();
3002         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3003           PatternsByOpcode[OpNodes[j]]
3004             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3005         }
3006       } else {
3007         std::cerr << "Unrecognized opcode '";
3008         Node->dump();
3009         std::cerr << "' on tree pattern '";
3010         std::cerr << 
3011            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3012         std::cerr << "'!\n";
3013         exit(1);
3014       }
3015     }
3016   }
3017   
3018   // Emit one Select_* method for each top-level opcode.  We do this instead of
3019   // emitting one giant switch statement to support compilers where this will
3020   // result in the recursive functions taking less stack space.
3021   for (std::map<Record*, std::vector<PatternToMatch*>,
3022        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3023        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3024     const std::string &OpName = PBOI->first->getName();
3025     OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3026     
3027     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3028     bool OptSlctOrder = 
3029       (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3030        OpcodeInfo.getNumResults() > 0);
3031
3032     if (OptSlctOrder) {
3033       OS << "  if (N.ResNo == " << OpcodeInfo.getNumResults()
3034          << " && N.getValue(0).hasOneUse()) {\n"
3035          << "    SDOperand Dummy = "
3036          << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3037          << "    SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3038          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3039          << "    SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3040          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3041          << "    Result = Dummy;\n"
3042          << "    return;\n"
3043          << "  }\n";
3044     }
3045
3046     std::vector<PatternToMatch*> &Patterns = PBOI->second;
3047     assert(!Patterns.empty() && "No patterns but map has entry?");
3048     
3049     // We want to emit all of the matching code now.  However, we want to emit
3050     // the matches in order of minimal cost.  Sort the patterns so the least
3051     // cost one is at the start.
3052     std::stable_sort(Patterns.begin(), Patterns.end(),
3053                      PatternSortingPredicate(*this));
3054
3055     typedef std::vector<std::pair<bool, std::string> > CodeList;
3056     typedef std::set<std::string> DeclSet;
3057     
3058     std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3059     std::set<std::pair<bool, std::string> > GeneratedDecl;
3060     for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3061       CodeList GeneratedCode;
3062       GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3063                              OptSlctOrder);
3064       CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3065     }
3066     
3067     // Scan the code to see if all of the patterns are reachable and if it is
3068     // possible that the last one might not match.
3069     bool mightNotMatch = true;
3070     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3071       CodeList &GeneratedCode = CodeForPatterns[i].second;
3072       mightNotMatch = false;
3073
3074       for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3075         if (GeneratedCode[j].first) { // predicate.
3076           mightNotMatch = true;
3077           break;
3078         }
3079       }
3080       
3081       // If this pattern definitely matches, and if it isn't the last one, the
3082       // patterns after it CANNOT ever match.  Error out.
3083       if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3084         std::cerr << "Pattern '";
3085         CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3086         std::cerr << "' is impossible to select!\n";
3087         exit(1);
3088       }
3089     }
3090
3091     // Print all declarations.
3092     for (std::set<std::pair<bool, std::string> >::iterator
3093          I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3094       if (I->first)
3095         OS << "  SDNode *" << I->second << ";\n";
3096       else
3097         OS << "  SDOperand " << I->second << "(0, 0);\n";
3098
3099     // Loop through and reverse all of the CodeList vectors, as we will be
3100     // accessing them from their logical front, but accessing the end of a
3101     // vector is more efficient.
3102     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3103       CodeList &GeneratedCode = CodeForPatterns[i].second;
3104       std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3105     }
3106     
3107     // Next, reverse the list of patterns itself for the same reason.
3108     std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3109     
3110     // Emit all of the patterns now, grouped together to share code.
3111     EmitPatterns(CodeForPatterns, 2, OS);
3112     
3113     // If the last pattern has predicates (which could fail) emit code to catch
3114     // the case where nothing handles a pattern.
3115     if (mightNotMatch)
3116       OS << "  std::cerr << \"Cannot yet select: \";\n"
3117          << "  N.Val->dump(CurDAG);\n"
3118          << "  std::cerr << '\\n';\n"
3119          << "  abort();\n";
3120
3121     OS << "}\n\n";
3122   }
3123   
3124   // Emit boilerplate.
3125   OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3126      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3127      << "  Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3128      << "  // Select the flag operand.\n"
3129      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
3130      << "    Select(Ops.back(), Ops.back());\n"
3131      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3132      << "  std::vector<MVT::ValueType> VTs;\n"
3133      << "  VTs.push_back(MVT::Other);\n"
3134      << "  VTs.push_back(MVT::Flag);\n"
3135      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3136     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3137     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3138      << "  Result = New.getValue(N.ResNo);\n"
3139      << "  return;\n"
3140      << "}\n\n";
3141   
3142   OS << "// The main instruction selector code.\n"
3143      << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3144      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3145      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3146      << "INSTRUCTION_LIST_END)) {\n"
3147      << "    Result = N;\n"
3148      << "    return;   // Already selected.\n"
3149      << "  }\n\n"
3150     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3151      << "  if (CGMI != CodeGenMap.end()) {\n"
3152      << "    Result = CGMI->second;\n"
3153      << "    return;\n"
3154      << "  }\n\n"
3155      << "  switch (N.getOpcode()) {\n"
3156      << "  default: break;\n"
3157      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
3158      << "  case ISD::BasicBlock:\n"
3159      << "  case ISD::Register:\n"
3160      << "  case ISD::HANDLENODE:\n"
3161      << "  case ISD::TargetConstant:\n"
3162      << "  case ISD::TargetConstantPool:\n"
3163      << "  case ISD::TargetFrameIndex:\n"
3164      << "  case ISD::TargetGlobalAddress: {\n"
3165      << "    Result = N;\n"
3166      << "    return;\n"
3167      << "  }\n"
3168      << "  case ISD::AssertSext:\n"
3169      << "  case ISD::AssertZext: {\n"
3170      << "    SDOperand Tmp0;\n"
3171      << "    Select(Tmp0, N.getOperand(0));\n"
3172      << "    if (!N.Val->hasOneUse())\n"
3173      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3174      << "Tmp0.Val, Tmp0.ResNo);\n"
3175      << "    Result = Tmp0;\n"
3176      << "    return;\n"
3177      << "  }\n"
3178      << "  case ISD::TokenFactor:\n"
3179      << "    if (N.getNumOperands() == 2) {\n"
3180      << "      SDOperand Op0, Op1;\n"
3181      << "      Select(Op0, N.getOperand(0));\n"
3182      << "      Select(Op1, N.getOperand(1));\n"
3183      << "      Result = \n"
3184      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3185      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3186      << "Result.Val, Result.ResNo);\n"
3187      << "    } else {\n"
3188      << "      std::vector<SDOperand> Ops;\n"
3189      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3190      << "        SDOperand Val;\n"
3191      << "        Select(Val, N.getOperand(i));\n"
3192      << "        Ops.push_back(Val);\n"
3193      << "      }\n"
3194      << "      Result = \n"
3195      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3196      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3197      << "Result.Val, Result.ResNo);\n"
3198      << "    }\n"
3199      << "    return;\n"
3200      << "  case ISD::CopyFromReg: {\n"
3201      << "    SDOperand Chain;\n"
3202      << "    Select(Chain, N.getOperand(0));\n"
3203      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3204      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
3205      << "    if (N.Val->getNumValues() == 2) {\n"
3206      << "      if (Chain == N.getOperand(0)) {\n"
3207      << "        Result = N; // No change\n"
3208      << "        return;\n"
3209      << "      }\n"
3210      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3211      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3212      << "New.Val, 0);\n"
3213      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3214      << "New.Val, 1);\n"
3215      << "      Result = New.getValue(N.ResNo);\n"
3216      << "      return;\n"
3217      << "    } else {\n"
3218      << "      SDOperand Flag;\n"
3219      << "      if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3220      << "      if (Chain == N.getOperand(0) &&\n"
3221      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3222      << "        Result = N; // No change\n"
3223      << "        return;\n"
3224      << "      }\n"
3225      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3226      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3227      << "New.Val, 0);\n"
3228      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3229      << "New.Val, 1);\n"
3230      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3231      << "New.Val, 2);\n"
3232      << "      Result = New.getValue(N.ResNo);\n"
3233      << "      return;\n"
3234      << "    }\n"
3235      << "  }\n"
3236      << "  case ISD::CopyToReg: {\n"
3237      << "    SDOperand Chain;\n"
3238      << "    Select(Chain, N.getOperand(0));\n"
3239      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3240      << "    SDOperand Val;\n"
3241      << "    Select(Val, N.getOperand(2));\n"
3242      << "    Result = N;\n"
3243      << "    if (N.Val->getNumValues() == 1) {\n"
3244      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3245      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3246      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3247      << "Result.Val, 0);\n"
3248      << "    } else {\n"
3249      << "      SDOperand Flag(0, 0);\n"
3250      << "      if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3251      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3252      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3253      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3254      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3255      << "Result.Val, 0);\n"
3256      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3257      << "Result.Val, 1);\n"
3258      << "      Result = Result.getValue(N.ResNo);\n"
3259      << "    }\n"
3260      << "    return;\n"
3261      << "  }\n"
3262      << "  case ISD::INLINEASM:  Select_INLINEASM(Result, N); return;\n";
3263
3264     
3265   // Loop over all of the case statements, emiting a call to each method we
3266   // emitted above.
3267   for (std::map<Record*, std::vector<PatternToMatch*>,
3268                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3269        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3270     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3271     OS << "  case " << OpcodeInfo.getEnumName() << ": "
3272        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3273        << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3274   }
3275
3276   OS << "  } // end of big switch.\n\n"
3277      << "  std::cerr << \"Cannot yet select: \";\n"
3278      << "  N.Val->dump(CurDAG);\n"
3279      << "  std::cerr << '\\n';\n"
3280      << "  abort();\n"
3281      << "}\n";
3282 }
3283
3284 void DAGISelEmitter::run(std::ostream &OS) {
3285   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3286                        " target", OS);
3287   
3288   OS << "// *** NOTE: This file is #included into the middle of the target\n"
3289      << "// *** instruction selector class.  These functions are really "
3290      << "methods.\n\n";
3291   
3292   OS << "// Instance var to keep track of multiply used nodes that have \n"
3293      << "// already been selected.\n"
3294      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3295
3296   OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3297      << "// and their place handle nodes.\n";
3298   OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3299   OS << "// Instance var to keep track of mapping of place handle nodes\n"
3300      << "// and their replacement nodes.\n";
3301   OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3302
3303   OS << "\n";
3304   OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3305      << "std::set<SDNode *> &Visited) {\n";
3306   OS << "  if (found || !Visited.insert(Use).second) return;\n";
3307   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3308   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3309   OS << "    if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3310   OS << "      if (N != Def) {\n";
3311   OS << "        findNonImmUse(N, Def, found, Visited);\n";
3312   OS << "      } else {\n";
3313   OS << "        found = true;\n";
3314   OS << "        break;\n";
3315   OS << "      }\n";
3316   OS << "    }\n";
3317   OS << "  }\n";
3318   OS << "}\n";
3319
3320   OS << "\n";
3321   OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3322   OS << "  std::set<SDNode *> Visited;\n";
3323   OS << "  bool found = false;\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 != Def) {\n";
3327   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3328   OS << "      if (found) break;\n";
3329   OS << "    }\n";
3330   OS << "  }\n";
3331   OS << "  return found;\n";
3332   OS << "}\n";
3333
3334   OS << "\n";
3335   OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3336      << "// handle node in ReplaceMap.\n";
3337   OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3338      << "unsigned RNum) {\n";
3339   OS << "  SDOperand N(H, HNum);\n";
3340   OS << "  std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3341   OS << "  if (HMI != HandleMap.end()) {\n";
3342   OS << "    ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3343   OS << "    HandleMap.erase(N);\n";
3344   OS << "  }\n";
3345   OS << "}\n";
3346
3347   OS << "\n";
3348   OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3349   OS << "// handles.Some handles do not yet have replacements because the\n";
3350   OS << "// nodes they replacements have only dead readers.\n";
3351   OS << "void SelectDanglingHandles() {\n";
3352   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3353      << "HandleMap.begin(),\n"
3354      << "         E = HandleMap.end(); I != E; ++I) {\n";
3355   OS << "    SDOperand N = I->first;\n";
3356   OS << "    SDOperand R;\n";
3357   OS << "    Select(R, N.getValue(0));\n";
3358   OS << "    AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3359   OS << "  }\n";
3360   OS << "}\n";
3361   OS << "\n";
3362   OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3363   OS << "// specific nodes.\n";
3364   OS << "void ReplaceHandles() {\n";
3365   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3366      << "ReplaceMap.begin(),\n"
3367      << "        E = ReplaceMap.end(); I != E; ++I) {\n";
3368   OS << "    SDOperand From = I->first;\n";
3369   OS << "    SDOperand To   = I->second;\n";
3370   OS << "    for (SDNode::use_iterator UI = From.Val->use_begin(), "
3371      << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3372   OS << "      SDNode *Use = *UI;\n";
3373   OS << "      std::vector<SDOperand> Ops;\n";
3374   OS << "      for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3375   OS << "        SDOperand O = Use->getOperand(i);\n";
3376   OS << "        if (O.Val == From.Val)\n";
3377   OS << "          Ops.push_back(To);\n";
3378   OS << "        else\n";
3379   OS << "          Ops.push_back(O);\n";
3380   OS << "      }\n";
3381   OS << "      SDOperand U = SDOperand(Use, 0);\n";
3382   OS << "      CurDAG->UpdateNodeOperands(U, Ops);\n";
3383   OS << "    }\n";
3384   OS << "  }\n";
3385   OS << "}\n";
3386
3387   OS << "\n";
3388   OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3389   OS << "// if the folding were to happen. This is called when, for example,\n";
3390   OS << "// a load is folded into a store. If the store's chain is the load,\n";
3391   OS << "// then the resulting node's input chain would be the load's input\n";
3392   OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3393   OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3394   OS << "// with the other operands along with the input chain of the load.\n";
3395   OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3396      << "SDNode *Chain, SDNode* &OldTF) {\n";
3397   OS << "  OldTF = NULL;\n";
3398   OS << "  if (N == Chain) {\n";
3399   OS << "    return N->getOperand(0);\n";
3400   OS << "  } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3401   OS << "             N->isOperand(Chain)) {\n";
3402   OS << "    SDOperand Ch = SDOperand(Chain, 0);\n";
3403   OS << "    std::map<SDOperand, SDOperand>::iterator CGMI = "
3404      << "CodeGenMap.find(Ch);\n";
3405   OS << "    if (CGMI != CodeGenMap.end())\n";
3406   OS << "      return SDOperand(0, 0);\n";
3407   OS << "    OldTF = Chain;\n";
3408   OS << "    std::vector<SDOperand> Ops;\n";
3409   OS << "    for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3410   OS << "      SDOperand Op = Chain->getOperand(i);\n";
3411   OS << "      if (Op.Val == N)\n";
3412   OS << "        Ops.push_back(N->getOperand(0));\n";
3413   OS << "      else\n";
3414   OS << "        Ops.push_back(Op);\n";
3415   OS << "    }\n";
3416   OS << "    return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3417   OS << "  }\n";
3418   OS << "  return SDOperand(0, 0);\n";
3419   OS << "}\n";
3420
3421   OS << "\n";
3422   OS << "// SelectRoot - Top level entry to DAG isel.\n";
3423   OS << "SDOperand SelectRoot(SDOperand N) {\n";
3424   OS << "  SDOperand ResNode;\n";
3425   OS << "  Select(ResNode, N);\n";
3426   OS << "  SelectDanglingHandles();\n";
3427   OS << "  ReplaceHandles();\n";
3428   OS << "  ReplaceMap.clear();\n";
3429   OS << "  return ResNode;\n";
3430   OS << "}\n";
3431   
3432   Intrinsics = LoadIntrinsics(Records);
3433   ParseNodeInfo();
3434   ParseNodeTransforms(OS);
3435   ParseComplexPatterns();
3436   ParsePatternFragments(OS);
3437   ParseInstructions();
3438   ParsePatterns();
3439   
3440   // Generate variants.  For example, commutative patterns can match
3441   // multiple ways.  Add them to PatternsToMatch as well.
3442   GenerateVariants();
3443
3444   
3445   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3446         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3447           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3448           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3449           std::cerr << "\n";
3450         });
3451   
3452   // At this point, we have full information about the 'Patterns' we need to
3453   // parse, both implicitly from instructions as well as from explicit pattern
3454   // definitions.  Emit the resultant instruction selector.
3455   EmitInstructionSelector(OS);  
3456   
3457   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3458        E = PatternFragments.end(); I != E; ++I)
3459     delete I->second;
3460   PatternFragments.clear();
3461
3462   Instructions.clear();
3463 }