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