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