Temporarily revert the last change, which breaks PPC and other targets that
[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) {
1753   if (P->isLeaf()) return 0;
1754   
1755   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1756   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1757     Cost += getResultPatternCost(P->getChild(i));
1758   return Cost;
1759 }
1760
1761 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1762 // In particular, we want to match maximal patterns first and lowest cost within
1763 // a particular complexity first.
1764 struct PatternSortingPredicate {
1765   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1766   DAGISelEmitter &ISE;
1767
1768   bool operator()(PatternToMatch *LHS,
1769                   PatternToMatch *RHS) {
1770     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1771     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1772     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1773     if (LHSSize < RHSSize) return false;
1774     
1775     // If the patterns have equal complexity, compare generated instruction cost
1776     return getResultPatternCost(LHS->getDstPattern()) <
1777       getResultPatternCost(RHS->getDstPattern());
1778   }
1779 };
1780
1781 /// getRegisterValueType - Look up and return the first ValueType of specified 
1782 /// RegisterClass record
1783 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1784   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1785     return RC->getValueTypeNum(0);
1786   return MVT::Other;
1787 }
1788
1789
1790 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1791 /// type information from it.
1792 static void RemoveAllTypes(TreePatternNode *N) {
1793   N->removeTypes();
1794   if (!N->isLeaf())
1795     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1796       RemoveAllTypes(N->getChild(i));
1797 }
1798
1799 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1800   Record *N = Records.getDef(Name);
1801   assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1802   return N;
1803 }
1804
1805 /// NodeHasProperty - return true if TreePatternNode has the specified
1806 /// property.
1807 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1808                             DAGISelEmitter &ISE)
1809 {
1810   if (N->isLeaf()) return false;
1811   Record *Operator = N->getOperator();
1812   if (!Operator->isSubClassOf("SDNode")) return false;
1813
1814   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1815   return NodeInfo.hasProperty(Property);
1816 }
1817
1818 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1819                                DAGISelEmitter &ISE)
1820 {
1821   if (NodeHasProperty(N, Property, ISE))
1822     return true;
1823
1824   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1825     TreePatternNode *Child = N->getChild(i);
1826     if (PatternHasProperty(Child, Property, ISE))
1827       return true;
1828   }
1829
1830   return false;
1831 }
1832
1833 class PatternCodeEmitter {
1834 private:
1835   DAGISelEmitter &ISE;
1836
1837   // Predicates.
1838   ListInit *Predicates;
1839   // Instruction selector pattern.
1840   TreePatternNode *Pattern;
1841   // Matched instruction.
1842   TreePatternNode *Instruction;
1843   
1844   // Node to name mapping
1845   std::map<std::string, std::string> VariableMap;
1846   // Node to operator mapping
1847   std::map<std::string, Record*> OperatorMap;
1848   // Names of all the folded nodes which produce chains.
1849   std::vector<std::pair<std::string, unsigned> > FoldedChains;
1850   std::set<std::string> Duplicates;
1851
1852   /// GeneratedCode - This is the buffer that we emit code to.  The first bool
1853   /// indicates whether this is an exit predicate (something that should be
1854   /// tested, and if true, the match fails) [when true] or normal code to emit
1855   /// [when false].
1856   std::vector<std::pair<bool, std::string> > &GeneratedCode;
1857
1858   std::string ChainName;
1859   unsigned TmpNo;
1860   
1861   void emitCheck(const std::string &S) {
1862     if (!S.empty())
1863       GeneratedCode.push_back(std::make_pair(true, S));
1864   }
1865   void emitCode(const std::string &S) {
1866     if (!S.empty())
1867       GeneratedCode.push_back(std::make_pair(false, S));
1868   }
1869 public:
1870   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1871                      TreePatternNode *pattern, TreePatternNode *instr,
1872                      std::vector<std::pair<bool, std::string> > &gc)
1873   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1874     GeneratedCode(gc), TmpNo(0) {}
1875
1876   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1877   /// if the match fails. At this point, we already know that the opcode for N
1878   /// matches, and the SDNode for the result has the RootName specified name.
1879   void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1880                      const std::string &ChainSuffix, bool &FoundChain,
1881                      bool isRoot = false) {
1882
1883     // Emit instruction predicates. Each predicate is just a string for now.
1884     if (isRoot) {
1885       std::string PredicateCheck;
1886       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1887         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1888           Record *Def = Pred->getDef();
1889           if (!Def->isSubClassOf("Predicate")) {
1890             Def->dump();
1891             assert(0 && "Unknown predicate type!");
1892           }
1893           if (!PredicateCheck.empty())
1894             PredicateCheck += " || ";
1895           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
1896         }
1897       }
1898       
1899       emitCheck(PredicateCheck);
1900     }
1901
1902     if (N->isLeaf()) {
1903       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1904         emitCheck("cast<ConstantSDNode>(" + RootName +
1905                   ")->getSignExtended() == " + itostr(II->getValue()));
1906         return;
1907       } else if (!NodeIsComplexPattern(N)) {
1908         assert(0 && "Cannot match this as a leaf value!");
1909         abort();
1910       }
1911     }
1912   
1913     // If this node has a name associated with it, capture it in VariableMap. If
1914     // we already saw this in the pattern, emit code to verify dagness.
1915     if (!N->getName().empty()) {
1916       std::string &VarMapEntry = VariableMap[N->getName()];
1917       if (VarMapEntry.empty()) {
1918         VarMapEntry = RootName;
1919       } else {
1920         // If we get here, this is a second reference to a specific name.  Since
1921         // we already have checked that the first reference is valid, we don't
1922         // have to recursively match it, just check that it's the same as the
1923         // previously named thing.
1924         emitCheck(VarMapEntry + " == " + RootName);
1925         return;
1926       }
1927
1928       if (!N->isLeaf())
1929         OperatorMap[N->getName()] = N->getOperator();
1930     }
1931
1932
1933     // Emit code to load the child nodes and match their contents recursively.
1934     unsigned OpNo = 0;
1935     bool NodeHasChain = NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1936     bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1937     bool EmittedUseCheck = false;
1938     bool EmittedSlctedCheck = false;
1939     if (HasChain) {
1940       if (NodeHasChain)
1941         OpNo = 1;
1942       if (!isRoot) {
1943         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1944         // Multiple uses of actual result?
1945         emitCheck(RootName + ".hasOneUse()");
1946         EmittedUseCheck = true;
1947         // hasOneUse() check is not strong enough. If the original node has
1948         // already been selected, it may have been replaced with another.
1949         for (unsigned j = 0; j != CInfo.getNumResults(); j++)
1950           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
1951                     "))");
1952         
1953         EmittedSlctedCheck = true;
1954         if (NodeHasChain)
1955           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" +
1956                     utostr(CInfo.getNumResults()) + "))");
1957       }
1958       if (NodeHasChain) {
1959         if (FoundChain)
1960           emitCheck("Chain.Val == " + RootName + ".Val");
1961         else
1962           FoundChain = true;
1963         ChainName = "Chain" + ChainSuffix;
1964         emitCode("SDOperand " + ChainName + " = " + RootName +
1965                  ".getOperand(0);");
1966       }
1967     }
1968
1969     // Don't fold any node which reads or writes a flag and has multiple uses.
1970     // FIXME: we really need to separate the concepts of flag and "glue". Those
1971     // real flag results, e.g. X86CMP output, can have multiple uses.
1972     // FIXME: If the incoming flag is optional. Then it is ok to fold it.
1973     if (!isRoot &&
1974         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
1975          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
1976          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
1977       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1978       if (!EmittedUseCheck) {
1979         // Multiple uses of actual result?
1980         emitCheck(RootName + ".hasOneUse()");
1981       }
1982       if (!EmittedSlctedCheck)
1983         // hasOneUse() check is not strong enough. If the original node has
1984         // already been selected, it may have been replaced with another.
1985         for (unsigned j = 0; j < CInfo.getNumResults(); j++)
1986           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
1987                     "))");
1988     }
1989
1990     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1991       emitCode("SDOperand " + RootName + utostr(OpNo) + " = " +
1992                RootName + ".getOperand(" +utostr(OpNo) + ");");
1993       TreePatternNode *Child = N->getChild(i);
1994     
1995       if (!Child->isLeaf()) {
1996         // If it's not a leaf, recursively match.
1997         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1998         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
1999                   CInfo.getEnumName());
2000         EmitMatchCode(Child, RootName + utostr(OpNo), ChainSuffix + utostr(OpNo),
2001                       FoundChain);
2002         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2003           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2004                                                 CInfo.getNumResults()));
2005       } else {
2006         // If this child has a name associated with it, capture it in VarMap. If
2007         // we already saw this in the pattern, emit code to verify dagness.
2008         if (!Child->getName().empty()) {
2009           std::string &VarMapEntry = VariableMap[Child->getName()];
2010           if (VarMapEntry.empty()) {
2011             VarMapEntry = RootName + utostr(OpNo);
2012           } else {
2013             // If we get here, this is a second reference to a specific name.
2014             // Since we already have checked that the first reference is valid,
2015             // we don't have to recursively match it, just check that it's the
2016             // same as the previously named thing.
2017             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2018             Duplicates.insert(RootName + utostr(OpNo));
2019             continue;
2020           }
2021         }
2022       
2023         // Handle leaves of various types.
2024         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2025           Record *LeafRec = DI->getDef();
2026           if (LeafRec->isSubClassOf("RegisterClass")) {
2027             // Handle register references.  Nothing to do here.
2028           } else if (LeafRec->isSubClassOf("Register")) {
2029             // Handle register references.
2030           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2031             // Handle complex pattern. Nothing to do here.
2032           } else if (LeafRec->getName() == "srcvalue") {
2033             // Place holder for SRCVALUE nodes. Nothing to do here.
2034           } else if (LeafRec->isSubClassOf("ValueType")) {
2035             // Make sure this is the specified value type.
2036             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2037                       ")->getVT() == MVT::" + LeafRec->getName());
2038           } else if (LeafRec->isSubClassOf("CondCode")) {
2039             // Make sure this is the specified cond code.
2040             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2041                       ")->get() == ISD::" + LeafRec->getName());
2042           } else {
2043             Child->dump();
2044             std::cerr << " ";
2045             assert(0 && "Unknown leaf type!");
2046           }
2047         } else if (IntInit *II =
2048                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2049           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2050           unsigned CTmp = TmpNo++;
2051           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2052                    RootName + utostr(OpNo) + ")->getSignExtended();");
2053
2054           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2055         } else {
2056           Child->dump();
2057           assert(0 && "Unknown leaf type!");
2058         }
2059       }
2060     }
2061
2062     // If there is a node predicate for this, emit the call.
2063     if (!N->getPredicateFn().empty())
2064       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2065   }
2066
2067   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2068   /// we actually have to build a DAG!
2069   std::pair<unsigned, unsigned>
2070   EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2071     // This is something selected from the pattern we matched.
2072     if (!N->getName().empty()) {
2073       assert(!isRoot && "Root of pattern cannot be a leaf!");
2074       std::string &Val = VariableMap[N->getName()];
2075       assert(!Val.empty() &&
2076              "Variable referenced but not defined and not caught earlier!");
2077       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2078         // Already selected this operand, just return the tmpval.
2079         return std::make_pair(1, atoi(Val.c_str()+3));
2080       }
2081
2082       const ComplexPattern *CP;
2083       unsigned ResNo = TmpNo++;
2084       unsigned NumRes = 1;
2085       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2086         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2087         std::string CastType;
2088         switch (N->getTypeNum(0)) {
2089         default: assert(0 && "Unknown type for constant node!");
2090         case MVT::i1:  CastType = "bool"; break;
2091         case MVT::i8:  CastType = "unsigned char"; break;
2092         case MVT::i16: CastType = "unsigned short"; break;
2093         case MVT::i32: CastType = "unsigned"; break;
2094         case MVT::i64: CastType = "uint64_t"; break;
2095         }
2096         emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType + 
2097                  ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2098         emitCode("SDOperand Tmp" + utostr(ResNo) + 
2099                  " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) + 
2100                  "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2101       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2102         Record *Op = OperatorMap[N->getName()];
2103         // Transform ExternalSymbol to TargetExternalSymbol
2104         if (Op && Op->getName() == "externalsym") {
2105           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2106                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2107                    Val + ")->getSymbol(), MVT::" +
2108                    getEnumName(N->getTypeNum(0)) + ");");
2109         } else {
2110           emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2111         }
2112       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2113         Record *Op = OperatorMap[N->getName()];
2114         // Transform GlobalAddress to TargetGlobalAddress
2115         if (Op && Op->getName() == "globaladdr") {
2116           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2117                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2118                    ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2119                    ");");
2120         } else {
2121           emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2122         }
2123       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2124         emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2125       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2126         emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2127       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2128         std::string Fn = CP->getSelectFunc();
2129         NumRes = CP->getNumOperands();
2130         std::string Code = "SDOperand ";
2131         for (unsigned i = 0; i < NumRes - 1; ++i)
2132           Code += "Tmp" + utostr(i+ResNo) + ", ";
2133         emitCode(Code + "Tmp" + utostr(NumRes - 1 + ResNo) + ";");
2134
2135         Code = Fn + "(" + Val;
2136         for (unsigned i = 0; i < NumRes; i++)
2137           Code += ", Tmp" + utostr(i + ResNo);
2138         emitCheck(Code + ")");
2139
2140         // This breaks ppc
2141         //for (unsigned i = 0; i < NumRes; ++i)
2142         //  emitCode("Tmp" + utostr(i+ResNo) + " = Select(Tmp" +
2143         //           utostr(i+ResNo) + ");");
2144
2145         TmpNo = ResNo + NumRes;
2146       } else {
2147         emitCode("SDOperand Tmp" + utostr(ResNo) + " = Select(" + Val + ");");
2148       }
2149       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2150       // value if used multiple times by this pattern result.
2151       Val = "Tmp"+utostr(ResNo);
2152       return std::make_pair(NumRes, ResNo);
2153     }
2154   
2155     if (N->isLeaf()) {
2156       // If this is an explicit register reference, handle it.
2157       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2158         unsigned ResNo = TmpNo++;
2159         if (DI->getDef()->isSubClassOf("Register")) {
2160           emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2161                    ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2162                    getEnumName(N->getTypeNum(0)) + ");");
2163           return std::make_pair(1, ResNo);
2164         }
2165       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2166         unsigned ResNo = TmpNo++;
2167         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2168         emitCode("SDOperand Tmp" + utostr(ResNo) + 
2169                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2170                  ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2171         return std::make_pair(1, ResNo);
2172       }
2173     
2174       N->dump();
2175       assert(0 && "Unknown leaf type!");
2176       return std::make_pair(1, ~0U);
2177     }
2178
2179     Record *Op = N->getOperator();
2180     if (Op->isSubClassOf("Instruction")) {
2181       const CodeGenTarget &CGT = ISE.getTargetInfo();
2182       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2183       const DAGInstruction &Inst = ISE.getInstruction(Op);
2184       bool HasImpInputs  = Inst.getNumImpOperands() > 0;
2185       bool HasImpResults = Inst.getNumImpResults() > 0;
2186       bool HasOptInFlag = isRoot &&
2187         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2188       bool HasInFlag  = isRoot &&
2189         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2190       bool NodeHasOutFlag = HasImpResults ||
2191         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2192       bool NodeHasChain =
2193         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2194       bool HasChain   = II.hasCtrlDep ||
2195         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2196
2197       if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2198         emitCode("SDOperand InFlag = SDOperand(0, 0);");
2199       if (HasOptInFlag)
2200         emitCode("bool HasOptInFlag = false;");
2201
2202       // How many results is this pattern expected to produce?
2203       unsigned NumExpectedResults = 0;
2204       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2205         MVT::ValueType VT = Pattern->getTypeNum(i);
2206         if (VT != MVT::isVoid && VT != MVT::Flag)
2207           NumExpectedResults++;
2208       }
2209
2210       // Determine operand emission order. Complex pattern first.
2211       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2212       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2213       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2214         TreePatternNode *Child = N->getChild(i);
2215         if (i == 0) {
2216           EmitOrder.push_back(std::make_pair(i, Child));
2217           OI = EmitOrder.begin();
2218         } else if (NodeIsComplexPattern(Child)) {
2219           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2220         } else {
2221           EmitOrder.push_back(std::make_pair(i, Child));
2222         }
2223       }
2224
2225       // Emit all of the operands.
2226       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2227       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2228         unsigned OpOrder       = EmitOrder[i].first;
2229         TreePatternNode *Child = EmitOrder[i].second;
2230         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2231         NumTemps[OpOrder] = NumTemp;
2232       }
2233
2234       // List all the operands in the right order.
2235       std::vector<unsigned> Ops;
2236       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2237         for (unsigned j = 0; j < NumTemps[i].first; j++)
2238           Ops.push_back(NumTemps[i].second + j);
2239       }
2240
2241       // Emit all the chain and CopyToReg stuff.
2242       bool ChainEmitted = HasChain;
2243       if (HasChain)
2244         emitCode(ChainName + " = Select(" + ChainName + ");");
2245       if (HasInFlag || HasOptInFlag || HasImpInputs)
2246         EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2247
2248       unsigned NumResults = Inst.getNumResults();    
2249       unsigned ResNo = TmpNo++;
2250       if (!isRoot) {
2251         std::string Code =
2252           "SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTargetNode(" +
2253           II.Namespace + "::" + II.TheDef->getName();
2254         if (N->getTypeNum(0) != MVT::isVoid)
2255           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2256         if (NodeHasOutFlag)
2257           Code += ", MVT::Flag";
2258
2259         unsigned LastOp = 0;
2260         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2261           LastOp = Ops[i];
2262           Code += ", Tmp" + utostr(LastOp);
2263         }
2264         emitCode(Code + ");");
2265         if (HasChain) {
2266           // Must have at least one result
2267           emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2268                    utostr(NumResults) + ");");
2269         }
2270       } else if (HasChain || NodeHasOutFlag) {
2271         if (HasOptInFlag) {
2272           emitCode("SDOperand Result = SDOperand(0, 0);");
2273           unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2274           emitCode("if (HasOptInFlag)");
2275           std::string Code = "  Result = CurDAG->getTargetNode(" +
2276              II.Namespace + "::" + II.TheDef->getName();
2277
2278           // Output order: results, chain, flags
2279           // Result types.
2280           if (NumResults > 0) { 
2281             if (N->getTypeNum(0) != MVT::isVoid)
2282               Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2283           }
2284           if (HasChain)
2285             Code += ", MVT::Other";
2286           if (NodeHasOutFlag)
2287             Code += ", MVT::Flag";
2288
2289           // Inputs.
2290           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2291             Code += ", Tmp" + utostr(Ops[i]);
2292           if (HasChain)  Code += ", " + ChainName;
2293           emitCode(Code + ", InFlag);");
2294
2295           emitCode("else");
2296           Code = "  Result = CurDAG->getTargetNode(" + II.Namespace + "::" +
2297                  II.TheDef->getName();
2298
2299           // Output order: results, chain, flags
2300           // Result types.
2301           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2302             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2303           if (HasChain)
2304             Code += ", MVT::Other";
2305           if (NodeHasOutFlag)
2306             Code += ", MVT::Flag";
2307
2308           // Inputs.
2309           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2310             Code += ", Tmp" + utostr(Ops[i]);
2311           if (HasChain) Code += ", " + ChainName + ");";
2312           emitCode(Code);
2313         } else {
2314           std::string Code = "SDOperand Result = CurDAG->getTargetNode(" +
2315             II.Namespace + "::" + II.TheDef->getName();
2316
2317           // Output order: results, chain, flags
2318           // Result types.
2319           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2320             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2321           if (HasChain)
2322             Code += ", MVT::Other";
2323           if (NodeHasOutFlag)
2324             Code += ", MVT::Flag";
2325
2326           // Inputs.
2327           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2328             Code += ", Tmp" + utostr(Ops[i]);
2329           if (HasChain) Code += ", " + ChainName;
2330           if (HasInFlag || HasImpInputs) Code += ", InFlag";
2331           emitCode(Code + ");");
2332         }
2333
2334         unsigned ValNo = 0;
2335         for (unsigned i = 0; i < NumResults; i++) {
2336           emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = Result"
2337                    ".getValue(" + utostr(ValNo) + ");");
2338           ValNo++;
2339         }
2340
2341         if (HasChain)
2342           emitCode(ChainName + " = Result.getValue(" + utostr(ValNo) + ");");
2343
2344         if (NodeHasOutFlag)
2345           emitCode("InFlag = Result.getValue(" + 
2346                    utostr(ValNo + (unsigned)HasChain) + ");");
2347
2348         if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2349           emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = "
2350                    "Result.getValue(" + utostr(ValNo) + ");");
2351           ValNo++;
2352         }
2353
2354         // User does not expect that the instruction produces a chain!
2355         bool AddedChain = HasChain && !NodeHasChain;
2356         if (NodeHasChain)
2357           emitCode("CodeGenMap[N.getValue(" + utostr(ValNo++) + ")] = " +
2358                    ChainName + ";");
2359
2360         if (FoldedChains.size() > 0) {
2361           std::string Code;
2362           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2363             Code += "CodeGenMap[" + FoldedChains[j].first + ".getValue(" +
2364               utostr(FoldedChains[j].second) + ")] = ";
2365           emitCode(Code + ChainName + ";");
2366         }
2367
2368         if (NodeHasOutFlag)
2369           emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = InFlag;");
2370
2371         if (AddedChain && NodeHasOutFlag) {
2372           if (NumExpectedResults == 0) {
2373             emitCode("return Result.getValue(N.ResNo+1);");
2374           } else {
2375             emitCode("if (N.ResNo < " + utostr(NumExpectedResults) + ")");
2376             emitCode("  return Result.getValue(N.ResNo);");
2377             emitCode("else");
2378             emitCode("  return Result.getValue(N.ResNo+1);");
2379           }
2380         } else {
2381           emitCode("return Result.getValue(N.ResNo);");
2382         }
2383       } else {
2384         // If this instruction is the root, and if there is only one use of it,
2385         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2386         emitCode("if (N.Val->hasOneUse()) {");
2387         std::string Code = "  return CurDAG->SelectNodeTo(N.Val, " +
2388           II.Namespace + "::" + II.TheDef->getName();
2389         if (N->getTypeNum(0) != MVT::isVoid)
2390           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2391         if (NodeHasOutFlag)
2392           Code += ", MVT::Flag";
2393         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2394           Code += ", Tmp" + utostr(Ops[i]);
2395         if (HasInFlag || HasImpInputs)
2396           Code += ", InFlag";
2397         emitCode(Code + ");");
2398         emitCode("} else {");
2399         Code = "  return CodeGenMap[N] = CurDAG->getTargetNode(" +
2400                II.Namespace + "::" + II.TheDef->getName();
2401         if (N->getTypeNum(0) != MVT::isVoid)
2402           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2403         if (NodeHasOutFlag)
2404           Code += ", MVT::Flag";
2405         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2406           Code += ", Tmp" + utostr(Ops[i]);
2407         if (HasInFlag || HasImpInputs)
2408           Code += ", InFlag";
2409         emitCode(Code + ");");
2410         emitCode("}");
2411       }
2412
2413       return std::make_pair(1, ResNo);
2414     } else if (Op->isSubClassOf("SDNodeXForm")) {
2415       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2416       unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2417       unsigned ResNo = TmpNo++;
2418       emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2419                + "(Tmp" + utostr(OpVal) + ".Val);");
2420       if (isRoot) {
2421         emitCode("CodeGenMap[N] = Tmp" +utostr(ResNo) + ";");
2422         emitCode("return Tmp" + utostr(ResNo) + ";");
2423       }
2424       return std::make_pair(1, ResNo);
2425     } else {
2426       N->dump();
2427       std::cerr << "\n";
2428       throw std::string("Unknown node in result pattern!");
2429     }
2430   }
2431
2432   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2433   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2434   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2435   /// for, this returns true otherwise false if Pat has all types.
2436   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2437                           const std::string &Prefix) {
2438     // Did we find one?
2439     if (!Pat->hasTypeSet()) {
2440       // Move a type over from 'other' to 'pat'.
2441       Pat->setTypes(Other->getExtTypes());
2442       emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2443                 getName(Pat->getTypeNum(0)));
2444       return true;
2445     }
2446   
2447     unsigned OpNo =
2448       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2449     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2450       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2451                              Prefix + utostr(OpNo)))
2452         return true;
2453     return false;
2454   }
2455
2456 private:
2457   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2458   /// being built.
2459   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2460                             bool &ChainEmitted, bool isRoot = false) {
2461     const CodeGenTarget &T = ISE.getTargetInfo();
2462     unsigned OpNo =
2463       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2464     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2465     bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2466     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2467       TreePatternNode *Child = N->getChild(i);
2468       if (!Child->isLeaf()) {
2469         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2470       } else {
2471         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2472           if (!Child->getName().empty()) {
2473             std::string Name = RootName + utostr(OpNo);
2474             if (Duplicates.find(Name) != Duplicates.end())
2475               // A duplicate! Do not emit a copy for this node.
2476               continue;
2477           }
2478
2479           Record *RR = DI->getDef();
2480           if (RR->isSubClassOf("Register")) {
2481             MVT::ValueType RVT = getRegisterValueType(RR, T);
2482             if (RVT == MVT::Flag) {
2483               emitCode("InFlag = Select(" + RootName + utostr(OpNo) + ");");
2484             } else {
2485               if (!ChainEmitted) {
2486                 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2487                 ChainName = "Chain";
2488                 ChainEmitted = true;
2489               }
2490               emitCode("SDOperand " + RootName + "CR" + utostr(i) + ";");
2491               emitCode(RootName + "CR" + utostr(i) +
2492                        "  = CurDAG->getCopyToReg(" + ChainName +
2493                        ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2494                        ", MVT::" + getEnumName(RVT) + "), Select(" + RootName +
2495                        utostr(OpNo) + "), InFlag);");
2496               emitCode(ChainName + " = " + RootName + "CR" + utostr(i) + 
2497                        ".getValue(0);");
2498               emitCode("InFlag = " + RootName + "CR" + utostr(i) +
2499                        ".getValue(1);");
2500             }
2501           }
2502         }
2503       }
2504     }
2505
2506     if (HasInFlag || HasOptInFlag) {
2507       std::string Code;
2508       if (HasOptInFlag) {
2509         emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2510                  ") {");
2511         Code = "  ";
2512       }
2513       emitCode(Code + "InFlag = Select(" + RootName + ".getOperand(" + 
2514                utostr(OpNo) + "));");
2515       if (HasOptInFlag) {
2516         emitCode("  HasOptInFlag = true;");
2517         emitCode("}");
2518       }
2519     }
2520   }
2521
2522   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2523   /// as specified by the instruction. It returns true if any copy is
2524   /// emitted.
2525   bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2526     bool RetVal = false;
2527     Record *Op = N->getOperator();
2528     if (Op->isSubClassOf("Instruction")) {
2529       const DAGInstruction &Inst = ISE.getInstruction(Op);
2530       const CodeGenTarget &CGT = ISE.getTargetInfo();
2531       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2532       unsigned NumImpResults  = Inst.getNumImpResults();
2533       for (unsigned i = 0; i < NumImpResults; i++) {
2534         Record *RR = Inst.getImpResult(i);
2535         if (RR->isSubClassOf("Register")) {
2536           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2537           if (RVT != MVT::Flag) {
2538             if (!ChainEmitted) {
2539               emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2540               ChainEmitted = true;
2541               ChainName = "Chain";
2542             }
2543             emitCode("Result = CurDAG->getCopyFromReg(" + ChainName + ", " +
2544                      ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2545                      ", InFlag);");
2546             emitCode(ChainName + " = Result.getValue(1);");
2547             emitCode("InFlag = Result.getValue(2);");
2548             RetVal = true;
2549           }
2550         }
2551       }
2552     }
2553     return RetVal;
2554   }
2555 };
2556
2557 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2558 /// stream to match the pattern, and generate the code for the match if it
2559 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2560 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2561                     std::vector<std::pair<bool, std::string> > &GeneratedCode) {
2562   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2563                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2564                              GeneratedCode);
2565
2566   // Emit the matcher, capturing named arguments in VariableMap.
2567   bool FoundChain = false;
2568   Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", "", FoundChain,
2569                         true /*the root*/);
2570
2571   // TP - Get *SOME* tree pattern, we don't care which.
2572   TreePattern &TP = *PatternFragments.begin()->second;
2573   
2574   // At this point, we know that we structurally match the pattern, but the
2575   // types of the nodes may not match.  Figure out the fewest number of type 
2576   // comparisons we need to emit.  For example, if there is only one integer
2577   // type supported by a target, there should be no type comparisons at all for
2578   // integer patterns!
2579   //
2580   // To figure out the fewest number of type checks needed, clone the pattern,
2581   // remove the types, then perform type inference on the pattern as a whole.
2582   // If there are unresolved types, emit an explicit check for those types,
2583   // apply the type to the tree, then rerun type inference.  Iterate until all
2584   // types are resolved.
2585   //
2586   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2587   RemoveAllTypes(Pat);
2588   
2589   do {
2590     // Resolve/propagate as many types as possible.
2591     try {
2592       bool MadeChange = true;
2593       while (MadeChange)
2594         MadeChange = Pat->ApplyTypeConstraints(TP,
2595                                                true/*Ignore reg constraints*/);
2596     } catch (...) {
2597       assert(0 && "Error: could not find consistent types for something we"
2598              " already decided was ok!");
2599       abort();
2600     }
2601
2602     // Insert a check for an unresolved type and add it to the tree.  If we find
2603     // an unresolved type to add a check for, this returns true and we iterate,
2604     // otherwise we are done.
2605   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2606
2607   Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2608   delete Pat;
2609 }
2610
2611 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
2612 /// a line causes any of them to be empty, remove them and return true when
2613 /// done.
2614 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
2615                           std::vector<std::pair<bool, std::string> > > >
2616                           &Patterns) {
2617   bool ErasedPatterns = false;
2618   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2619     Patterns[i].second.pop_back();
2620     if (Patterns[i].second.empty()) {
2621       Patterns.erase(Patterns.begin()+i);
2622       --i; --e;
2623       ErasedPatterns = true;
2624     }
2625   }
2626   return ErasedPatterns;
2627 }
2628
2629 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2630 /// code together between the patterns.
2631 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
2632                                   std::vector<std::pair<bool, std::string> > > >
2633                                   &Patterns, unsigned Indent,
2634                                   std::ostream &OS) {
2635   typedef std::pair<bool, std::string> CodeLine;
2636   typedef std::vector<CodeLine> CodeList;
2637   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2638   
2639   if (Patterns.empty()) return;
2640   
2641   // Figure out how many patterns share the next code line.  Explicitly copy
2642   // FirstCodeLine so that we don't invalidate a reference when changing
2643   // Patterns.
2644   const CodeLine FirstCodeLine = Patterns.back().second.back();
2645   unsigned LastMatch = Patterns.size()-1;
2646   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2647     --LastMatch;
2648   
2649   // If not all patterns share this line, split the list into two pieces.  The
2650   // first chunk will use this line, the second chunk won't.
2651   if (LastMatch != 0) {
2652     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2653     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2654     
2655     // FIXME: Emit braces?
2656     if (Shared.size() == 1) {
2657       PatternToMatch &Pattern = *Shared.back().first;
2658       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2659       Pattern.getSrcPattern()->print(OS);
2660       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2661       Pattern.getDstPattern()->print(OS);
2662       OS << "\n";
2663       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2664          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2665          << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2666     }
2667     if (!FirstCodeLine.first) {
2668       OS << std::string(Indent, ' ') << "{\n";
2669       Indent += 2;
2670     }
2671     EmitPatterns(Shared, Indent, OS);
2672     if (!FirstCodeLine.first) {
2673       Indent -= 2;
2674       OS << std::string(Indent, ' ') << "}\n";
2675     }
2676     
2677     if (Other.size() == 1) {
2678       PatternToMatch &Pattern = *Other.back().first;
2679       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2680       Pattern.getSrcPattern()->print(OS);
2681       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2682       Pattern.getDstPattern()->print(OS);
2683       OS << "\n";
2684       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2685          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2686          << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2687     }
2688     EmitPatterns(Other, Indent, OS);
2689     return;
2690   }
2691   
2692   // Remove this code from all of the patterns that share it.
2693   bool ErasedPatterns = EraseCodeLine(Patterns);
2694   
2695   bool isPredicate = FirstCodeLine.first;
2696   
2697   // Otherwise, every pattern in the list has this line.  Emit it.
2698   if (!isPredicate) {
2699     // Normal code.
2700     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2701   } else {
2702     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2703     
2704     // If the next code line is another predicate, and if all of the pattern
2705     // in this group share the same next line, emit it inline now.  Do this
2706     // until we run out of common predicates.
2707     while (!ErasedPatterns && Patterns.back().second.back().first) {
2708       // Check that all of fhe patterns in Patterns end with the same predicate.
2709       bool AllEndWithSamePredicate = true;
2710       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2711         if (Patterns[i].second.back() != Patterns.back().second.back()) {
2712           AllEndWithSamePredicate = false;
2713           break;
2714         }
2715       // If all of the predicates aren't the same, we can't share them.
2716       if (!AllEndWithSamePredicate) break;
2717       
2718       // Otherwise we can.  Emit it shared now.
2719       OS << " &&\n" << std::string(Indent+4, ' ')
2720          << Patterns.back().second.back().second;
2721       ErasedPatterns = EraseCodeLine(Patterns);
2722     }
2723     
2724     OS << ") {\n";
2725     Indent += 2;
2726   }
2727   
2728   EmitPatterns(Patterns, Indent, OS);
2729   
2730   if (isPredicate)
2731     OS << std::string(Indent-2, ' ') << "}\n";
2732 }
2733
2734
2735
2736 namespace {
2737   /// CompareByRecordName - An ordering predicate that implements less-than by
2738   /// comparing the names records.
2739   struct CompareByRecordName {
2740     bool operator()(const Record *LHS, const Record *RHS) const {
2741       // Sort by name first.
2742       if (LHS->getName() < RHS->getName()) return true;
2743       // If both names are equal, sort by pointer.
2744       return LHS->getName() == RHS->getName() && LHS < RHS;
2745     }
2746   };
2747 }
2748
2749 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2750   std::string InstNS = Target.inst_begin()->second.Namespace;
2751   if (!InstNS.empty()) InstNS += "::";
2752   
2753   // Group the patterns by their top-level opcodes.
2754   std::map<Record*, std::vector<PatternToMatch*>,
2755     CompareByRecordName> PatternsByOpcode;
2756   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2757     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2758     if (!Node->isLeaf()) {
2759       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2760     } else {
2761       const ComplexPattern *CP;
2762       if (IntInit *II = 
2763           dynamic_cast<IntInit*>(Node->getLeafValue())) {
2764         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2765       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2766         std::vector<Record*> OpNodes = CP->getRootNodes();
2767         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2768           PatternsByOpcode[OpNodes[j]]
2769             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
2770         }
2771       } else {
2772         std::cerr << "Unrecognized opcode '";
2773         Node->dump();
2774         std::cerr << "' on tree pattern '";
2775         std::cerr << 
2776            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2777         std::cerr << "'!\n";
2778         exit(1);
2779       }
2780     }
2781   }
2782   
2783   // Emit one Select_* method for each top-level opcode.  We do this instead of
2784   // emitting one giant switch statement to support compilers where this will
2785   // result in the recursive functions taking less stack space.
2786   for (std::map<Record*, std::vector<PatternToMatch*>,
2787        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2788        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2789     OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2790     
2791     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2792     std::vector<PatternToMatch*> &Patterns = PBOI->second;
2793     assert(!Patterns.empty() && "No patterns but map has entry?");
2794     
2795     // We want to emit all of the matching code now.  However, we want to emit
2796     // the matches in order of minimal cost.  Sort the patterns so the least
2797     // cost one is at the start.
2798     std::stable_sort(Patterns.begin(), Patterns.end(),
2799                      PatternSortingPredicate(*this));
2800     
2801     typedef std::vector<std::pair<bool, std::string> > CodeList;
2802     
2803     std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
2804     for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2805       CodeList GeneratedCode;
2806       GenerateCodeForPattern(*Patterns[i], GeneratedCode);
2807       CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2808     }
2809     
2810     // Scan the code to see if all of the patterns are reachable and if it is
2811     // possible that the last one might not match.
2812     bool mightNotMatch = true;
2813     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2814       CodeList &GeneratedCode = CodeForPatterns[i].second;
2815       mightNotMatch = false;
2816
2817       for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2818         if (GeneratedCode[j].first) { // predicate.
2819           mightNotMatch = true;
2820           break;
2821         }
2822       }
2823       
2824       // If this pattern definitely matches, and if it isn't the last one, the
2825       // patterns after it CANNOT ever match.  Error out.
2826       if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2827         std::cerr << "Pattern '";
2828         CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2829         std::cerr << "' is impossible to select!\n";
2830         exit(1);
2831       }
2832     }
2833     
2834     // Loop through and reverse all of the CodeList vectors, as we will be
2835     // accessing them from their logical front, but accessing the end of a
2836     // vector is more efficient.
2837     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2838       CodeList &GeneratedCode = CodeForPatterns[i].second;
2839       std::reverse(GeneratedCode.begin(), GeneratedCode.end());
2840     }
2841     
2842     // Next, reverse the list of patterns itself for the same reason.
2843     std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
2844     
2845     // Emit all of the patterns now, grouped together to share code.
2846     EmitPatterns(CodeForPatterns, 2, OS);
2847     
2848     // If the last pattern has predicates (which could fail) emit code to catch
2849     // the case where nothing handles a pattern.
2850     if (mightNotMatch)
2851       OS << "  std::cerr << \"Cannot yet select: \";\n"
2852          << "  N.Val->dump(CurDAG);\n"
2853          << "  std::cerr << '\\n';\n"
2854          << "  abort();\n";
2855
2856     OS << "}\n\n";
2857   }
2858   
2859   // Emit boilerplate.
2860   OS << "SDOperand Select_INLINEASM(SDOperand N) {\n"
2861      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
2862      << "  Ops[0] = Select(N.getOperand(0)); // Select the chain.\n\n"
2863      << "  // Select the flag operand.\n"
2864      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
2865      << "    Ops.back() = Select(Ops.back());\n"
2866      << "  std::vector<MVT::ValueType> VTs;\n"
2867      << "  VTs.push_back(MVT::Other);\n"
2868      << "  VTs.push_back(MVT::Flag);\n"
2869      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
2870      << "  CodeGenMap[N.getValue(0)] = New;\n"
2871      << "  CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2872      << "  return New.getValue(N.ResNo);\n"
2873      << "}\n\n";
2874   
2875   OS << "// The main instruction selector code.\n"
2876      << "SDOperand SelectCode(SDOperand N) {\n"
2877      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2878      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2879      << "INSTRUCTION_LIST_END))\n"
2880      << "    return N;   // Already selected.\n\n"
2881     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2882      << "  if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2883      << "  switch (N.getOpcode()) {\n"
2884      << "  default: break;\n"
2885      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
2886      << "  case ISD::BasicBlock:\n"
2887      << "  case ISD::Register:\n"
2888      << "    return N;\n"
2889      << "  case ISD::AssertSext:\n"
2890      << "  case ISD::AssertZext: {\n"
2891      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
2892      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2893      << "    return Tmp0;\n"
2894      << "  }\n"
2895      << "  case ISD::TokenFactor:\n"
2896      << "    if (N.getNumOperands() == 2) {\n"
2897      << "      SDOperand Op0 = Select(N.getOperand(0));\n"
2898      << "      SDOperand Op1 = Select(N.getOperand(1));\n"
2899      << "      return CodeGenMap[N] =\n"
2900      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2901      << "    } else {\n"
2902      << "      std::vector<SDOperand> Ops;\n"
2903      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2904      << "        Ops.push_back(Select(N.getOperand(i)));\n"
2905      << "       return CodeGenMap[N] = \n"
2906      << "               CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2907      << "    }\n"
2908      << "  case ISD::CopyFromReg: {\n"
2909      << "    SDOperand Chain = Select(N.getOperand(0));\n"
2910      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2911      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
2912      << "    if (N.Val->getNumValues() == 2) {\n"
2913      << "      if (Chain == N.getOperand(0)) return N; // No change\n"
2914      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2915      << "      CodeGenMap[N.getValue(0)] = New;\n"
2916      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2917      << "      return New.getValue(N.ResNo);\n"
2918      << "    } else {\n"
2919      << "      SDOperand Flag(0, 0);\n"
2920      << "      if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2921      << "      if (Chain == N.getOperand(0) &&\n"
2922      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2923      << "        return N; // No change\n"
2924      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2925      << "      CodeGenMap[N.getValue(0)] = New;\n"
2926      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2927      << "      CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2928      << "      return New.getValue(N.ResNo);\n"
2929      << "    }\n"
2930      << "  }\n"
2931      << "  case ISD::CopyToReg: {\n"
2932      << "    SDOperand Chain = Select(N.getOperand(0));\n"
2933      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2934      << "    SDOperand Val = Select(N.getOperand(2));\n"
2935      << "    SDOperand Result = N;\n"
2936      << "    if (N.Val->getNumValues() == 1) {\n"
2937      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2938      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2939      << "      return CodeGenMap[N] = Result;\n"
2940      << "    } else {\n"
2941      << "      SDOperand Flag(0, 0);\n"
2942      << "      if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2943      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2944      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2945      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2946      << "      CodeGenMap[N.getValue(0)] = Result;\n"
2947      << "      CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2948      << "      return Result.getValue(N.ResNo);\n"
2949      << "    }\n"
2950      << "  }\n"
2951      << "  case ISD::INLINEASM:           return Select_INLINEASM(N);\n";
2952
2953     
2954   // Loop over all of the case statements, emiting a call to each method we
2955   // emitted above.
2956   for (std::map<Record*, std::vector<PatternToMatch*>,
2957                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2958        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2959     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2960     OS << "  case " << OpcodeInfo.getEnumName() << ": "
2961        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
2962        << "return Select_" << PBOI->first->getName() << "(N);\n";
2963   }
2964
2965   OS << "  } // end of big switch.\n\n"
2966      << "  std::cerr << \"Cannot yet select: \";\n"
2967      << "  N.Val->dump(CurDAG);\n"
2968      << "  std::cerr << '\\n';\n"
2969      << "  abort();\n"
2970      << "}\n";
2971 }
2972
2973 void DAGISelEmitter::run(std::ostream &OS) {
2974   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2975                        " target", OS);
2976   
2977   OS << "// *** NOTE: This file is #included into the middle of the target\n"
2978      << "// *** instruction selector class.  These functions are really "
2979      << "methods.\n\n";
2980   
2981   OS << "// Instance var to keep track of multiply used nodes that have \n"
2982      << "// already been selected.\n"
2983      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2984   
2985   ParseNodeInfo();
2986   ParseNodeTransforms(OS);
2987   ParseComplexPatterns();
2988   ParsePatternFragments(OS);
2989   ParseInstructions();
2990   ParsePatterns();
2991   
2992   // Generate variants.  For example, commutative patterns can match
2993   // multiple ways.  Add them to PatternsToMatch as well.
2994   GenerateVariants();
2995
2996   
2997   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2998         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2999           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3000           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3001           std::cerr << "\n";
3002         });
3003   
3004   // At this point, we have full information about the 'Patterns' we need to
3005   // parse, both implicitly from instructions as well as from explicit pattern
3006   // definitions.  Emit the resultant instruction selector.
3007   EmitInstructionSelector(OS);  
3008   
3009   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3010        E = PatternFragments.end(); I != E; ++I)
3011     delete I->second;
3012   PatternFragments.clear();
3013
3014   Instructions.clear();
3015 }