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