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