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