Make tblgen emit:
[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 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40   return VT == MVT::isInt ||
41         (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42 }
43
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47   return VT == MVT::isFP ||
48         (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49 }
50
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
53 //
54
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56   OperandNo = R->getValueAsInt("OperandNum");
57   
58   if (R->isSubClassOf("SDTCisVT")) {
59     ConstraintType = SDTCisVT;
60     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61   } else if (R->isSubClassOf("SDTCisInt")) {
62     ConstraintType = SDTCisInt;
63   } else if (R->isSubClassOf("SDTCisFP")) {
64     ConstraintType = SDTCisFP;
65   } else if (R->isSubClassOf("SDTCisSameAs")) {
66     ConstraintType = SDTCisSameAs;
67     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69     ConstraintType = SDTCisVTSmallerThanOp;
70     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
71       R->getValueAsInt("OtherOperandNum");
72   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73     ConstraintType = SDTCisOpSmallerThanOp;
74     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
75       R->getValueAsInt("BigOperandNum");
76   } else {
77     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
78     exit(1);
79   }
80 }
81
82 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
83 /// N, which has NumResults results.
84 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
85                                                  TreePatternNode *N,
86                                                  unsigned NumResults) const {
87   assert(NumResults == 1 && "We only work with single result nodes so far!");
88   
89   if (OpNo < NumResults)
90     return N;  // FIXME: need value #
91   else
92     return N->getChild(OpNo-NumResults);
93 }
94
95 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
96 /// constraint to the nodes operands.  This returns true if it makes a
97 /// change, false otherwise.  If a type contradiction is found, throw an
98 /// exception.
99 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100                                            const SDNodeInfo &NodeInfo,
101                                            TreePattern &TP) const {
102   unsigned NumResults = NodeInfo.getNumResults();
103   assert(NumResults == 1 && "We only work with single result nodes so far!");
104   
105   // Check that the number of operands is sane.
106   if (NodeInfo.getNumOperands() >= 0) {
107     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108       TP.error(N->getOperator()->getName() + " node requires exactly " +
109                itostr(NodeInfo.getNumOperands()) + " operands!");
110   }
111
112   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
113   
114   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
115   
116   switch (ConstraintType) {
117   default: assert(0 && "Unknown constraint type!");
118   case SDTCisVT:
119     // Operand must be a particular type.
120     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
121   case SDTCisInt: {
122     // If there is only one integer type supported, this must be it.
123     std::vector<MVT::ValueType> IntVTs =
124       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
125
126     // If we found exactly one supported integer type, apply it.
127     if (IntVTs.size() == 1)
128       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
129     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
130   }
131   case SDTCisFP: {
132     // If there is only one FP type supported, this must be it.
133     std::vector<MVT::ValueType> FPVTs =
134       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
135         
136     // If we found exactly one supported FP type, apply it.
137     if (FPVTs.size() == 1)
138       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
139     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
140   }
141   case SDTCisSameAs: {
142     TreePatternNode *OtherNode =
143       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
144     return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145            OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
146   }
147   case SDTCisVTSmallerThanOp: {
148     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
149     // have an integer type that is smaller than the VT.
150     if (!NodeToApply->isLeaf() ||
151         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153                ->isSubClassOf("ValueType"))
154       TP.error(N->getOperator()->getName() + " expects a VT operand!");
155     MVT::ValueType VT =
156      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157     if (!MVT::isInteger(VT))
158       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
159     
160     TreePatternNode *OtherNode =
161       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
162     
163     // It must be integer.
164     bool MadeChange = false;
165     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
166     
167     if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
168       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
169     return false;
170   }
171   case SDTCisOpSmallerThanOp: {
172     TreePatternNode *BigOperand =
173       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
174
175     // Both operands must be integer or FP, but we don't care which.
176     bool MadeChange = false;
177     
178     if (isExtIntegerVT(NodeToApply->getExtType()))
179       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180     else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182     if (isExtIntegerVT(BigOperand->getExtType()))
183       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184     else if (isExtFloatingPointVT(BigOperand->getExtType()))
185       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
186
187     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
188     
189     if (isExtIntegerVT(NodeToApply->getExtType())) {
190       VTs = FilterVTs(VTs, MVT::isInteger);
191     } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
193     } else {
194       VTs.clear();
195     }
196
197     switch (VTs.size()) {
198     default:         // Too many VT's to pick from.
199     case 0: break;   // No info yet.
200     case 1: 
201       // Only one VT of this flavor.  Cannot ever satisify the constraints.
202       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
203     case 2:
204       // If we have exactly two possible types, the little operand must be the
205       // small one, the big operand should be the big one.  Common with 
206       // float/double for example.
207       assert(VTs[0] < VTs[1] && "Should be sorted!");
208       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
210       break;
211     }    
212     return MadeChange;
213   }
214   }  
215   return false;
216 }
217
218
219 //===----------------------------------------------------------------------===//
220 // SDNodeInfo implementation
221 //
222 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223   EnumName    = R->getValueAsString("Opcode");
224   SDClassName = R->getValueAsString("SDClass");
225   Record *TypeProfile = R->getValueAsDef("TypeProfile");
226   NumResults = TypeProfile->getValueAsInt("NumResults");
227   NumOperands = TypeProfile->getValueAsInt("NumOperands");
228   
229   // Parse the properties.
230   Properties = 0;
231   ListInit *LI = R->getValueAsListInit("Properties");
232   for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
233     DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
234     assert(DI && "Properties list must be list of defs!");
235     if (DI->getDef()->getName() == "SDNPCommutative") {
236       Properties |= 1 << SDNPCommutative;
237     } else if (DI->getDef()->getName() == "SDNPAssociative") {
238       Properties |= 1 << SDNPAssociative;
239     } else {
240       std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
241                 << "' on node '" << R->getName() << "'!\n";
242       exit(1);
243     }
244   }
245   
246   
247   // Parse the type constraints.
248   ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
249   for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
250     assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
251            "Constraints list should contain constraint definitions!");
252     Record *Constraint = 
253       static_cast<DefInit*>(Constraints->getElement(i))->getDef();
254     TypeConstraints.push_back(Constraint);
255   }
256 }
257
258 //===----------------------------------------------------------------------===//
259 // TreePatternNode implementation
260 //
261
262 TreePatternNode::~TreePatternNode() {
263 #if 0 // FIXME: implement refcounted tree nodes!
264   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
265     delete getChild(i);
266 #endif
267 }
268
269 /// UpdateNodeType - Set the node type of N to VT if VT contains
270 /// information.  If N already contains a conflicting type, then throw an
271 /// exception.  This returns true if any information was updated.
272 ///
273 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
274   if (VT == MVT::isUnknown || getExtType() == VT) return false;
275   if (getExtType() == MVT::isUnknown) {
276     setType(VT);
277     return true;
278   }
279   
280   // If we are told this is to be an int or FP type, and it already is, ignore
281   // the advice.
282   if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
283       (VT == MVT::isFP  && isExtFloatingPointVT(getExtType())))
284     return false;
285       
286   // If we know this is an int or fp type, and we are told it is a specific one,
287   // take the advice.
288   if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
289       (getExtType() == MVT::isFP  && isExtFloatingPointVT(VT))) {
290     setType(VT);
291     return true;
292   }      
293
294   TP.error("Type inference contradiction found in node " + 
295            getOperator()->getName() + "!");
296   return true; // unreachable
297 }
298
299
300 void TreePatternNode::print(std::ostream &OS) const {
301   if (isLeaf()) {
302     OS << *getLeafValue();
303   } else {
304     OS << "(" << getOperator()->getName();
305   }
306   
307   switch (getExtType()) {
308   case MVT::Other: OS << ":Other"; break;
309   case MVT::isInt: OS << ":isInt"; break;
310   case MVT::isFP : OS << ":isFP"; break;
311   case MVT::isUnknown: ; /*OS << ":?";*/ break;
312   default:  OS << ":" << getType(); break;
313   }
314
315   if (!isLeaf()) {
316     if (getNumChildren() != 0) {
317       OS << " ";
318       getChild(0)->print(OS);
319       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
320         OS << ", ";
321         getChild(i)->print(OS);
322       }
323     }
324     OS << ")";
325   }
326   
327   if (!PredicateFn.empty())
328     OS << "<<P:" << PredicateFn << ">>";
329   if (TransformFn)
330     OS << "<<X:" << TransformFn->getName() << ">>";
331   if (!getName().empty())
332     OS << ":$" << getName();
333
334 }
335 void TreePatternNode::dump() const {
336   print(std::cerr);
337 }
338
339 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
340 /// the specified node.  For this comparison, all of the state of the node
341 /// is considered, except for the assigned name.  Nodes with differing names
342 /// that are otherwise identical are considered isomorphic.
343 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
344   if (N == this) return true;
345   if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
346       getPredicateFn() != N->getPredicateFn() ||
347       getTransformFn() != N->getTransformFn())
348     return false;
349
350   if (isLeaf()) {
351     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
352       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
353         return DI->getDef() == NDI->getDef();
354     return getLeafValue() == N->getLeafValue();
355   }
356   
357   if (N->getOperator() != getOperator() ||
358       N->getNumChildren() != getNumChildren()) return false;
359   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
360     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
361       return false;
362   return true;
363 }
364
365 /// clone - Make a copy of this tree and all of its children.
366 ///
367 TreePatternNode *TreePatternNode::clone() const {
368   TreePatternNode *New;
369   if (isLeaf()) {
370     New = new TreePatternNode(getLeafValue());
371   } else {
372     std::vector<TreePatternNode*> CChildren;
373     CChildren.reserve(Children.size());
374     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
375       CChildren.push_back(getChild(i)->clone());
376     New = new TreePatternNode(getOperator(), CChildren);
377   }
378   New->setName(getName());
379   New->setType(getExtType());
380   New->setPredicateFn(getPredicateFn());
381   New->setTransformFn(getTransformFn());
382   return New;
383 }
384
385 /// SubstituteFormalArguments - Replace the formal arguments in this tree
386 /// with actual values specified by ArgMap.
387 void TreePatternNode::
388 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
389   if (isLeaf()) return;
390   
391   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
392     TreePatternNode *Child = getChild(i);
393     if (Child->isLeaf()) {
394       Init *Val = Child->getLeafValue();
395       if (dynamic_cast<DefInit*>(Val) &&
396           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
397         // We found a use of a formal argument, replace it with its value.
398         Child = ArgMap[Child->getName()];
399         assert(Child && "Couldn't find formal argument!");
400         setChild(i, Child);
401       }
402     } else {
403       getChild(i)->SubstituteFormalArguments(ArgMap);
404     }
405   }
406 }
407
408
409 /// InlinePatternFragments - If this pattern refers to any pattern
410 /// fragments, inline them into place, giving us a pattern without any
411 /// PatFrag references.
412 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
413   if (isLeaf()) return this;  // nothing to do.
414   Record *Op = getOperator();
415   
416   if (!Op->isSubClassOf("PatFrag")) {
417     // Just recursively inline children nodes.
418     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
419       setChild(i, getChild(i)->InlinePatternFragments(TP));
420     return this;
421   }
422
423   // Otherwise, we found a reference to a fragment.  First, look up its
424   // TreePattern record.
425   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
426   
427   // Verify that we are passing the right number of operands.
428   if (Frag->getNumArgs() != Children.size())
429     TP.error("'" + Op->getName() + "' fragment requires " +
430              utostr(Frag->getNumArgs()) + " operands!");
431
432   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
433
434   // Resolve formal arguments to their actual value.
435   if (Frag->getNumArgs()) {
436     // Compute the map of formal to actual arguments.
437     std::map<std::string, TreePatternNode*> ArgMap;
438     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
439       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
440   
441     FragTree->SubstituteFormalArguments(ArgMap);
442   }
443   
444   FragTree->setName(getName());
445   
446   // Get a new copy of this fragment to stitch into here.
447   //delete this;    // FIXME: implement refcounting!
448   return FragTree;
449 }
450
451 /// getIntrinsicType - Check to see if the specified record has an intrinsic
452 /// type which should be applied to it.  This infer the type of register
453 /// references from the register file information, for example.
454 ///
455 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
456                                       TreePattern &TP) {
457   // Check to see if this is a register or a register class...
458   if (R->isSubClassOf("RegisterClass")) {
459     if (NotRegisters) return MVT::isUnknown;
460     return getValueType(R->getValueAsDef("RegType"));
461   } else if (R->isSubClassOf("PatFrag")) {
462     // Pattern fragment types will be resolved when they are inlined.
463     return MVT::isUnknown;
464   } else if (R->isSubClassOf("Register")) {
465     //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
466     // TODO: if a register appears in exactly one regclass, we could use that
467     // type info.
468     return MVT::isUnknown;
469   } else if (R->isSubClassOf("ValueType")) {
470     // Using a VTSDNode.
471     return MVT::Other;
472   } else if (R->getName() == "node") {
473     // Placeholder.
474     return MVT::isUnknown;
475   }
476   
477   TP.error("Unknown node flavor used in pattern: " + R->getName());
478   return MVT::Other;
479 }
480
481 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
482 /// this node and its children in the tree.  This returns true if it makes a
483 /// change, false otherwise.  If a type contradiction is found, throw an
484 /// exception.
485 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
486   if (isLeaf()) {
487     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488       // If it's a regclass or something else known, include the type.
489       return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
490                             TP);
491     return false;
492   }
493   
494   // special handling for set, which isn't really an SDNode.
495   if (getOperator()->getName() == "set") {
496     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
497     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
498     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
499     
500     // Types of operands must match.
501     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
502     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
503     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
504     return MadeChange;
505   } else if (getOperator()->isSubClassOf("SDNode")) {
506     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
507     
508     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
509     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
510       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
511     return MadeChange;  
512   } else if (getOperator()->isSubClassOf("Instruction")) {
513     const DAGInstruction &Inst =
514       TP.getDAGISelEmitter().getInstruction(getOperator());
515     
516     assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
517     // Apply the result type to the node
518     bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
519
520     if (getNumChildren() != Inst.getNumOperands())
521       TP.error("Instruction '" + getOperator()->getName() + " expects " +
522                utostr(Inst.getNumOperands()) + " operands, not " +
523                utostr(getNumChildren()) + " operands!");
524     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
525       MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
526       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
527     }
528     return MadeChange;
529   } else {
530     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
531     
532     // Node transforms always take one operand, and take and return the same
533     // type.
534     if (getNumChildren() != 1)
535       TP.error("Node transform '" + getOperator()->getName() +
536                "' requires one operand!");
537     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
538     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
539     return MadeChange;
540   }
541 }
542
543 /// canPatternMatch - If it is impossible for this pattern to match on this
544 /// target, fill in Reason and return false.  Otherwise, return true.  This is
545 /// used as a santity check for .td files (to prevent people from writing stuff
546 /// that can never possibly work), and to prevent the pattern permuter from
547 /// generating stuff that is useless.
548 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
549   if (isLeaf()) return true;
550
551   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
552     if (!getChild(i)->canPatternMatch(Reason, ISE))
553       return false;
554   
555   // If this node is a commutative operator, check that the LHS isn't an
556   // immediate.
557   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
558   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
559     // Scan all of the operands of the node and make sure that only the last one
560     // is a constant node.
561     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
562       if (!getChild(i)->isLeaf() && 
563           getChild(i)->getOperator()->getName() == "imm") {
564         Reason = "Immediate value must be on the RHS of commutative operators!";
565         return false;
566       }
567   }
568   
569   return true;
570 }
571
572 //===----------------------------------------------------------------------===//
573 // TreePattern implementation
574 //
575
576 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
577                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
578    isInputPattern = isInput;
579    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
580      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
581 }
582
583 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
584                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
585   isInputPattern = isInput;
586   Trees.push_back(ParseTreePattern(Pat));
587 }
588
589 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
590                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
591   isInputPattern = isInput;
592   Trees.push_back(Pat);
593 }
594
595
596
597 void TreePattern::error(const std::string &Msg) const {
598   dump();
599   throw "In " + TheRecord->getName() + ": " + Msg;
600 }
601
602 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
603   Record *Operator = Dag->getNodeType();
604   
605   if (Operator->isSubClassOf("ValueType")) {
606     // If the operator is a ValueType, then this must be "type cast" of a leaf
607     // node.
608     if (Dag->getNumArgs() != 1)
609       error("Type cast only takes one operand!");
610     
611     Init *Arg = Dag->getArg(0);
612     TreePatternNode *New;
613     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
614       Record *R = DI->getDef();
615       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
616         Dag->setArg(0, new DagInit(R,
617                                 std::vector<std::pair<Init*, std::string> >()));
618         TreePatternNode *TPN = ParseTreePattern(Dag);
619         TPN->setName(Dag->getArgName(0));
620         return TPN;
621       }   
622       
623       New = new TreePatternNode(DI);
624     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
625       New = ParseTreePattern(DI);
626     } else {
627       Arg->dump();
628       error("Unknown leaf value for tree pattern!");
629       return 0;
630     }
631     
632     // Apply the type cast.
633     New->UpdateNodeType(getValueType(Operator), *this);
634     return New;
635   }
636   
637   // Verify that this is something that makes sense for an operator.
638   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
639       !Operator->isSubClassOf("Instruction") && 
640       !Operator->isSubClassOf("SDNodeXForm") &&
641       Operator->getName() != "set")
642     error("Unrecognized node '" + Operator->getName() + "'!");
643   
644   //  Check to see if this is something that is illegal in an input pattern.
645   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
646       Operator->isSubClassOf("SDNodeXForm")))
647     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
648   
649   std::vector<TreePatternNode*> Children;
650   
651   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
652     Init *Arg = Dag->getArg(i);
653     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
654       Children.push_back(ParseTreePattern(DI));
655       Children.back()->setName(Dag->getArgName(i));
656     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
657       Record *R = DefI->getDef();
658       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
659       // TreePatternNode if its own.
660       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
661         Dag->setArg(i, new DagInit(R,
662                               std::vector<std::pair<Init*, std::string> >()));
663         --i;  // Revisit this node...
664       } else {
665         TreePatternNode *Node = new TreePatternNode(DefI);
666         Node->setName(Dag->getArgName(i));
667         Children.push_back(Node);
668         
669         // Input argument?
670         if (R->getName() == "node") {
671           if (Dag->getArgName(i).empty())
672             error("'node' argument requires a name to match with operand list");
673           Args.push_back(Dag->getArgName(i));
674         }
675       }
676     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
677       TreePatternNode *Node = new TreePatternNode(II);
678       if (!Dag->getArgName(i).empty())
679         error("Constant int argument should not have a name!");
680       Children.push_back(Node);
681     } else {
682       std::cerr << '"';
683       Arg->dump();
684       std::cerr << "\": ";
685       error("Unknown leaf value for tree pattern!");
686     }
687   }
688   
689   return new TreePatternNode(Operator, Children);
690 }
691
692 /// InferAllTypes - Infer/propagate as many types throughout the expression
693 /// patterns as possible.  Return true if all types are infered, false
694 /// otherwise.  Throw an exception if a type contradiction is found.
695 bool TreePattern::InferAllTypes() {
696   bool MadeChange = true;
697   while (MadeChange) {
698     MadeChange = false;
699     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
700       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
701   }
702   
703   bool HasUnresolvedTypes = false;
704   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
705     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
706   return !HasUnresolvedTypes;
707 }
708
709 void TreePattern::print(std::ostream &OS) const {
710   OS << getRecord()->getName();
711   if (!Args.empty()) {
712     OS << "(" << Args[0];
713     for (unsigned i = 1, e = Args.size(); i != e; ++i)
714       OS << ", " << Args[i];
715     OS << ")";
716   }
717   OS << ": ";
718   
719   if (Trees.size() > 1)
720     OS << "[\n";
721   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
722     OS << "\t";
723     Trees[i]->print(OS);
724     OS << "\n";
725   }
726
727   if (Trees.size() > 1)
728     OS << "]\n";
729 }
730
731 void TreePattern::dump() const { print(std::cerr); }
732
733
734
735 //===----------------------------------------------------------------------===//
736 // DAGISelEmitter implementation
737 //
738
739 // Parse all of the SDNode definitions for the target, populating SDNodes.
740 void DAGISelEmitter::ParseNodeInfo() {
741   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
742   while (!Nodes.empty()) {
743     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
744     Nodes.pop_back();
745   }
746 }
747
748 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
749 /// map, and emit them to the file as functions.
750 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
751   OS << "\n// Node transformations.\n";
752   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
753   while (!Xforms.empty()) {
754     Record *XFormNode = Xforms.back();
755     Record *SDNode = XFormNode->getValueAsDef("Opcode");
756     std::string Code = XFormNode->getValueAsCode("XFormFunction");
757     SDNodeXForms.insert(std::make_pair(XFormNode,
758                                        std::make_pair(SDNode, Code)));
759
760     if (!Code.empty()) {
761       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
762       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
763
764       OS << "inline SDOperand Transform_" << XFormNode->getName()
765          << "(SDNode *" << C2 << ") {\n";
766       if (ClassName != "SDNode")
767         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
768       OS << Code << "\n}\n";
769     }
770
771     Xforms.pop_back();
772   }
773 }
774
775
776
777 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
778 /// file, building up the PatternFragments map.  After we've collected them all,
779 /// inline fragments together as necessary, so that there are no references left
780 /// inside a pattern fragment to a pattern fragment.
781 ///
782 /// This also emits all of the predicate functions to the output file.
783 ///
784 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
785   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
786   
787   // First step, parse all of the fragments and emit predicate functions.
788   OS << "\n// Predicate functions.\n";
789   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
790     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
791     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
792     PatternFragments[Fragments[i]] = P;
793     
794     // Validate the argument list, converting it to map, to discard duplicates.
795     std::vector<std::string> &Args = P->getArgList();
796     std::set<std::string> OperandsMap(Args.begin(), Args.end());
797     
798     if (OperandsMap.count(""))
799       P->error("Cannot have unnamed 'node' values in pattern fragment!");
800     
801     // Parse the operands list.
802     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
803     if (OpsList->getNodeType()->getName() != "ops")
804       P->error("Operands list should start with '(ops ... '!");
805     
806     // Copy over the arguments.       
807     Args.clear();
808     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
809       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
810           static_cast<DefInit*>(OpsList->getArg(j))->
811           getDef()->getName() != "node")
812         P->error("Operands list should all be 'node' values.");
813       if (OpsList->getArgName(j).empty())
814         P->error("Operands list should have names for each operand!");
815       if (!OperandsMap.count(OpsList->getArgName(j)))
816         P->error("'" + OpsList->getArgName(j) +
817                  "' does not occur in pattern or was multiply specified!");
818       OperandsMap.erase(OpsList->getArgName(j));
819       Args.push_back(OpsList->getArgName(j));
820     }
821     
822     if (!OperandsMap.empty())
823       P->error("Operands list does not contain an entry for operand '" +
824                *OperandsMap.begin() + "'!");
825
826     // If there is a code init for this fragment, emit the predicate code and
827     // keep track of the fact that this fragment uses it.
828     std::string Code = Fragments[i]->getValueAsCode("Predicate");
829     if (!Code.empty()) {
830       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
831       std::string ClassName =
832         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
833       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
834       
835       OS << "inline bool Predicate_" << Fragments[i]->getName()
836          << "(SDNode *" << C2 << ") {\n";
837       if (ClassName != "SDNode")
838         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
839       OS << Code << "\n}\n";
840       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
841     }
842     
843     // If there is a node transformation corresponding to this, keep track of
844     // it.
845     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
846     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
847       P->getOnlyTree()->setTransformFn(Transform);
848   }
849   
850   OS << "\n\n";
851
852   // Now that we've parsed all of the tree fragments, do a closure on them so
853   // that there are not references to PatFrags left inside of them.
854   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
855        E = PatternFragments.end(); I != E; ++I) {
856     TreePattern *ThePat = I->second;
857     ThePat->InlinePatternFragments();
858         
859     // Infer as many types as possible.  Don't worry about it if we don't infer
860     // all of them, some may depend on the inputs of the pattern.
861     try {
862       ThePat->InferAllTypes();
863     } catch (...) {
864       // If this pattern fragment is not supported by this target (no types can
865       // satisfy its constraints), just ignore it.  If the bogus pattern is
866       // actually used by instructions, the type consistency error will be
867       // reported there.
868     }
869     
870     // If debugging, print out the pattern fragment result.
871     DEBUG(ThePat->dump());
872   }
873 }
874
875 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
876 /// instruction input.  Return true if this is a real use.
877 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
878                       std::map<std::string, TreePatternNode*> &InstInputs) {
879   // No name -> not interesting.
880   if (Pat->getName().empty()) {
881     if (Pat->isLeaf()) {
882       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
883       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
884         I->error("Input " + DI->getDef()->getName() + " must be named!");
885
886     }
887     return false;
888   }
889
890   Record *Rec;
891   if (Pat->isLeaf()) {
892     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
893     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
894     Rec = DI->getDef();
895   } else {
896     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
897     Rec = Pat->getOperator();
898   }
899
900   TreePatternNode *&Slot = InstInputs[Pat->getName()];
901   if (!Slot) {
902     Slot = Pat;
903   } else {
904     Record *SlotRec;
905     if (Slot->isLeaf()) {
906       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
907     } else {
908       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
909       SlotRec = Slot->getOperator();
910     }
911     
912     // Ensure that the inputs agree if we've already seen this input.
913     if (Rec != SlotRec)
914       I->error("All $" + Pat->getName() + " inputs must agree with each other");
915     if (Slot->getExtType() != Pat->getExtType())
916       I->error("All $" + Pat->getName() + " inputs must agree with each other");
917   }
918   return true;
919 }
920
921 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
922 /// part of "I", the instruction), computing the set of inputs and outputs of
923 /// the pattern.  Report errors if we see anything naughty.
924 void DAGISelEmitter::
925 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
926                             std::map<std::string, TreePatternNode*> &InstInputs,
927                             std::map<std::string, Record*> &InstResults) {
928   if (Pat->isLeaf()) {
929     bool isUse = HandleUse(I, Pat, InstInputs);
930     if (!isUse && Pat->getTransformFn())
931       I->error("Cannot specify a transform function for a non-input value!");
932     return;
933   } else if (Pat->getOperator()->getName() != "set") {
934     // If this is not a set, verify that the children nodes are not void typed,
935     // and recurse.
936     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
937       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
938         I->error("Cannot have void nodes inside of patterns!");
939       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
940     }
941     
942     // If this is a non-leaf node with no children, treat it basically as if
943     // it were a leaf.  This handles nodes like (imm).
944     bool isUse = false;
945     if (Pat->getNumChildren() == 0)
946       isUse = HandleUse(I, Pat, InstInputs);
947     
948     if (!isUse && Pat->getTransformFn())
949       I->error("Cannot specify a transform function for a non-input value!");
950     return;
951   } 
952   
953   // Otherwise, this is a set, validate and collect instruction results.
954   if (Pat->getNumChildren() == 0)
955     I->error("set requires operands!");
956   else if (Pat->getNumChildren() & 1)
957     I->error("set requires an even number of operands");
958   
959   if (Pat->getTransformFn())
960     I->error("Cannot specify a transform function on a set node!");
961   
962   // Check the set destinations.
963   unsigned NumValues = Pat->getNumChildren()/2;
964   for (unsigned i = 0; i != NumValues; ++i) {
965     TreePatternNode *Dest = Pat->getChild(i);
966     if (!Dest->isLeaf())
967       I->error("set destination should be a virtual register!");
968     
969     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
970     if (!Val)
971       I->error("set destination should be a virtual register!");
972     
973     if (!Val->getDef()->isSubClassOf("RegisterClass"))
974       I->error("set destination should be a virtual register!");
975     if (Dest->getName().empty())
976       I->error("set destination must have a name!");
977     if (InstResults.count(Dest->getName()))
978       I->error("cannot set '" + Dest->getName() +"' multiple times");
979     InstResults[Dest->getName()] = Val->getDef();
980
981     // Verify and collect info from the computation.
982     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
983                                 InstInputs, InstResults);
984   }
985 }
986
987
988 /// ParseInstructions - Parse all of the instructions, inlining and resolving
989 /// any fragments involved.  This populates the Instructions list with fully
990 /// resolved instructions.
991 void DAGISelEmitter::ParseInstructions() {
992   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
993   
994   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
995     ListInit *LI = 0;
996     
997     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
998       LI = Instrs[i]->getValueAsListInit("Pattern");
999     
1000     // If there is no pattern, only collect minimal information about the
1001     // instruction for its operand list.  We have to assume that there is one
1002     // result, as we have no detailed info.
1003     if (!LI || LI->getSize() == 0) {
1004       std::vector<MVT::ValueType> ResultTypes;
1005       std::vector<MVT::ValueType> OperandTypes;
1006       
1007       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1008       
1009       // Doesn't even define a result?
1010       if (InstInfo.OperandList.size() == 0)
1011         continue;
1012       
1013       // Assume the first operand is the result.
1014       ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1015       
1016       // The rest are inputs.
1017       for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1018         OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1019       
1020       // Create and insert the instruction.
1021       Instructions.insert(std::make_pair(Instrs[i], 
1022                             DAGInstruction(0, ResultTypes, OperandTypes)));
1023       continue;  // no pattern.
1024     }
1025     
1026     // Parse the instruction.
1027     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1028     // Inline pattern fragments into it.
1029     I->InlinePatternFragments();
1030     
1031     // Infer as many types as possible.  If we cannot infer all of them, we can
1032     // never do anything with this instruction pattern: report it to the user.
1033     if (!I->InferAllTypes())
1034       I->error("Could not infer all types in pattern!");
1035     
1036     // InstInputs - Keep track of all of the inputs of the instruction, along 
1037     // with the record they are declared as.
1038     std::map<std::string, TreePatternNode*> InstInputs;
1039     
1040     // InstResults - Keep track of all the virtual registers that are 'set'
1041     // in the instruction, including what reg class they are.
1042     std::map<std::string, Record*> InstResults;
1043     
1044     // Verify that the top-level forms in the instruction are of void type, and
1045     // fill in the InstResults map.
1046     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1047       TreePatternNode *Pat = I->getTree(j);
1048       if (Pat->getExtType() != MVT::isVoid) {
1049         I->dump();
1050         I->error("Top-level forms in instruction pattern should have"
1051                  " void types");
1052       }
1053
1054       // Find inputs and outputs, and verify the structure of the uses/defs.
1055       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1056     }
1057
1058     // Now that we have inputs and outputs of the pattern, inspect the operands
1059     // list for the instruction.  This determines the order that operands are
1060     // added to the machine instruction the node corresponds to.
1061     unsigned NumResults = InstResults.size();
1062
1063     // Parse the operands list from the (ops) list, validating it.
1064     std::vector<std::string> &Args = I->getArgList();
1065     assert(Args.empty() && "Args list should still be empty here!");
1066     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1067
1068     // Check that all of the results occur first in the list.
1069     std::vector<MVT::ValueType> ResultTypes;
1070     for (unsigned i = 0; i != NumResults; ++i) {
1071       if (i == CGI.OperandList.size())
1072         I->error("'" + InstResults.begin()->first +
1073                  "' set but does not appear in operand list!");
1074       const std::string &OpName = CGI.OperandList[i].Name;
1075       
1076       // Check that it exists in InstResults.
1077       Record *R = InstResults[OpName];
1078       if (R == 0)
1079         I->error("Operand $" + OpName + " should be a set destination: all "
1080                  "outputs must occur before inputs in operand list!");
1081       
1082       if (CGI.OperandList[i].Rec != R)
1083         I->error("Operand $" + OpName + " class mismatch!");
1084       
1085       // Remember the return type.
1086       ResultTypes.push_back(CGI.OperandList[i].Ty);
1087       
1088       // Okay, this one checks out.
1089       InstResults.erase(OpName);
1090     }
1091
1092     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1093     // the copy while we're checking the inputs.
1094     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1095
1096     std::vector<TreePatternNode*> ResultNodeOperands;
1097     std::vector<MVT::ValueType> OperandTypes;
1098     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1099       const std::string &OpName = CGI.OperandList[i].Name;
1100       if (OpName.empty())
1101         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1102
1103       if (!InstInputsCheck.count(OpName))
1104         I->error("Operand $" + OpName +
1105                  " does not appear in the instruction pattern");
1106       TreePatternNode *InVal = InstInputsCheck[OpName];
1107       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1108       if (CGI.OperandList[i].Ty != InVal->getExtType())
1109         I->error("Operand $" + OpName +
1110                  "'s type disagrees between the operand and pattern");
1111       OperandTypes.push_back(InVal->getType());
1112       
1113       // Construct the result for the dest-pattern operand list.
1114       TreePatternNode *OpNode = InVal->clone();
1115       
1116       // No predicate is useful on the result.
1117       OpNode->setPredicateFn("");
1118       
1119       // Promote the xform function to be an explicit node if set.
1120       if (Record *Xform = OpNode->getTransformFn()) {
1121         OpNode->setTransformFn(0);
1122         std::vector<TreePatternNode*> Children;
1123         Children.push_back(OpNode);
1124         OpNode = new TreePatternNode(Xform, Children);
1125       }
1126       
1127       ResultNodeOperands.push_back(OpNode);
1128     }
1129     
1130     if (!InstInputsCheck.empty())
1131       I->error("Input operand $" + InstInputsCheck.begin()->first +
1132                " occurs in pattern but not in operands list!");
1133
1134     TreePatternNode *ResultPattern =
1135       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1136
1137     // Create and insert the instruction.
1138     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1139     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1140
1141     // Use a temporary tree pattern to infer all types and make sure that the
1142     // constructed result is correct.  This depends on the instruction already
1143     // being inserted into the Instructions map.
1144     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1145     Temp.InferAllTypes();
1146
1147     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1148     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1149     
1150     DEBUG(I->dump());
1151   }
1152    
1153   // If we can, convert the instructions to be patterns that are matched!
1154   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1155        E = Instructions.end(); II != E; ++II) {
1156     TreePattern *I = II->second.getPattern();
1157     if (I == 0) continue;  // No pattern.
1158     
1159     if (I->getNumTrees() != 1) {
1160       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1161       continue;
1162     }
1163     TreePatternNode *Pattern = I->getTree(0);
1164     if (Pattern->getOperator()->getName() != "set")
1165       continue;  // Not a set (store or something?)
1166     
1167     if (Pattern->getNumChildren() != 2)
1168       continue;  // Not a set of a single value (not handled so far)
1169     
1170     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1171     
1172     std::string Reason;
1173     if (!SrcPattern->canPatternMatch(Reason, *this))
1174       I->error("Instruction can never match: " + Reason);
1175     
1176     TreePatternNode *DstPattern = II->second.getResultPattern();
1177     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1178   }
1179 }
1180
1181 void DAGISelEmitter::ParsePatterns() {
1182   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1183
1184   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1185     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1186     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1187
1188     // Inline pattern fragments into it.
1189     Pattern->InlinePatternFragments();
1190     
1191     // Infer as many types as possible.  If we cannot infer all of them, we can
1192     // never do anything with this pattern: report it to the user.
1193     if (!Pattern->InferAllTypes())
1194       Pattern->error("Could not infer all types in pattern!");
1195     
1196     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1197     if (LI->getSize() == 0) continue;  // no pattern.
1198     
1199     // Parse the instruction.
1200     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1201     
1202     // Inline pattern fragments into it.
1203     Result->InlinePatternFragments();
1204     
1205     // Infer as many types as possible.  If we cannot infer all of them, we can
1206     // never do anything with this pattern: report it to the user.
1207     if (!Result->InferAllTypes())
1208       Result->error("Could not infer all types in pattern result!");
1209    
1210     if (Result->getNumTrees() != 1)
1211       Result->error("Cannot handle instructions producing instructions "
1212                     "with temporaries yet!");
1213
1214     std::string Reason;
1215     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1216       Pattern->error("Pattern can never match: " + Reason);
1217     
1218     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1219                                              Result->getOnlyTree()));
1220   }
1221 }
1222
1223 /// CombineChildVariants - Given a bunch of permutations of each child of the
1224 /// 'operator' node, put them together in all possible ways.
1225 static void CombineChildVariants(TreePatternNode *Orig, 
1226                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1227                                  std::vector<TreePatternNode*> &OutVariants,
1228                                  DAGISelEmitter &ISE) {
1229   // Make sure that each operand has at least one variant to choose from.
1230   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1231     if (ChildVariants[i].empty())
1232       return;
1233         
1234   // The end result is an all-pairs construction of the resultant pattern.
1235   std::vector<unsigned> Idxs;
1236   Idxs.resize(ChildVariants.size());
1237   bool NotDone = true;
1238   while (NotDone) {
1239     // Create the variant and add it to the output list.
1240     std::vector<TreePatternNode*> NewChildren;
1241     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1242       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1243     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1244     
1245     // Copy over properties.
1246     R->setName(Orig->getName());
1247     R->setPredicateFn(Orig->getPredicateFn());
1248     R->setTransformFn(Orig->getTransformFn());
1249     R->setType(Orig->getExtType());
1250     
1251     // If this pattern cannot every match, do not include it as a variant.
1252     std::string ErrString;
1253     if (!R->canPatternMatch(ErrString, ISE)) {
1254       delete R;
1255     } else {
1256       bool AlreadyExists = false;
1257       
1258       // Scan to see if this pattern has already been emitted.  We can get
1259       // duplication due to things like commuting:
1260       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1261       // which are the same pattern.  Ignore the dups.
1262       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1263         if (R->isIsomorphicTo(OutVariants[i])) {
1264           AlreadyExists = true;
1265           break;
1266         }
1267       
1268       if (AlreadyExists)
1269         delete R;
1270       else
1271         OutVariants.push_back(R);
1272     }
1273     
1274     // Increment indices to the next permutation.
1275     NotDone = false;
1276     // Look for something we can increment without causing a wrap-around.
1277     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1278       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1279         NotDone = true;   // Found something to increment.
1280         break;
1281       }
1282       Idxs[IdxsIdx] = 0;
1283     }
1284   }
1285 }
1286
1287 /// CombineChildVariants - A helper function for binary operators.
1288 ///
1289 static void CombineChildVariants(TreePatternNode *Orig, 
1290                                  const std::vector<TreePatternNode*> &LHS,
1291                                  const std::vector<TreePatternNode*> &RHS,
1292                                  std::vector<TreePatternNode*> &OutVariants,
1293                                  DAGISelEmitter &ISE) {
1294   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1295   ChildVariants.push_back(LHS);
1296   ChildVariants.push_back(RHS);
1297   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1298 }  
1299
1300
1301 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1302                                      std::vector<TreePatternNode *> &Children) {
1303   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1304   Record *Operator = N->getOperator();
1305   
1306   // Only permit raw nodes.
1307   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1308       N->getTransformFn()) {
1309     Children.push_back(N);
1310     return;
1311   }
1312
1313   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1314     Children.push_back(N->getChild(0));
1315   else
1316     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1317
1318   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1319     Children.push_back(N->getChild(1));
1320   else
1321     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1322 }
1323
1324 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1325 /// the (potentially recursive) pattern by using algebraic laws.
1326 ///
1327 static void GenerateVariantsOf(TreePatternNode *N,
1328                                std::vector<TreePatternNode*> &OutVariants,
1329                                DAGISelEmitter &ISE) {
1330   // We cannot permute leaves.
1331   if (N->isLeaf()) {
1332     OutVariants.push_back(N);
1333     return;
1334   }
1335
1336   // Look up interesting info about the node.
1337   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1338
1339   // If this node is associative, reassociate.
1340   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1341     // Reassociate by pulling together all of the linked operators 
1342     std::vector<TreePatternNode*> MaximalChildren;
1343     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1344
1345     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1346     // permutations.
1347     if (MaximalChildren.size() == 3) {
1348       // Find the variants of all of our maximal children.
1349       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1350       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1351       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1352       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1353       
1354       // There are only two ways we can permute the tree:
1355       //   (A op B) op C    and    A op (B op C)
1356       // Within these forms, we can also permute A/B/C.
1357       
1358       // Generate legal pair permutations of A/B/C.
1359       std::vector<TreePatternNode*> ABVariants;
1360       std::vector<TreePatternNode*> BAVariants;
1361       std::vector<TreePatternNode*> ACVariants;
1362       std::vector<TreePatternNode*> CAVariants;
1363       std::vector<TreePatternNode*> BCVariants;
1364       std::vector<TreePatternNode*> CBVariants;
1365       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1366       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1367       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1368       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1369       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1370       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1371
1372       // Combine those into the result: (x op x) op x
1373       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1374       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1375       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1376       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1377       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1378       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1379
1380       // Combine those into the result: x op (x op x)
1381       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1382       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1383       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1384       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1385       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1386       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1387       return;
1388     }
1389   }
1390   
1391   // Compute permutations of all children.
1392   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1393   ChildVariants.resize(N->getNumChildren());
1394   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1395     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1396
1397   // Build all permutations based on how the children were formed.
1398   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1399
1400   // If this node is commutative, consider the commuted order.
1401   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1402     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1403     // Consider the commuted order.
1404     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1405                          OutVariants, ISE);
1406   }
1407 }
1408
1409
1410 // GenerateVariants - Generate variants.  For example, commutative patterns can
1411 // match multiple ways.  Add them to PatternsToMatch as well.
1412 void DAGISelEmitter::GenerateVariants() {
1413   
1414   DEBUG(std::cerr << "Generating instruction variants.\n");
1415   
1416   // Loop over all of the patterns we've collected, checking to see if we can
1417   // generate variants of the instruction, through the exploitation of
1418   // identities.  This permits the target to provide agressive matching without
1419   // the .td file having to contain tons of variants of instructions.
1420   //
1421   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1422   // intentionally do not reconsider these.  Any variants of added patterns have
1423   // already been added.
1424   //
1425   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1426     std::vector<TreePatternNode*> Variants;
1427     GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1428
1429     assert(!Variants.empty() && "Must create at least original variant!");
1430     Variants.erase(Variants.begin());  // Remove the original pattern.
1431
1432     if (Variants.empty())  // No variants for this pattern.
1433       continue;
1434
1435     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1436           PatternsToMatch[i].first->dump();
1437           std::cerr << "\n");
1438
1439     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1440       TreePatternNode *Variant = Variants[v];
1441
1442       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1443             Variant->dump();
1444             std::cerr << "\n");
1445       
1446       // Scan to see if an instruction or explicit pattern already matches this.
1447       bool AlreadyExists = false;
1448       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1449         // Check to see if this variant already exists.
1450         if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1451           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1452           AlreadyExists = true;
1453           break;
1454         }
1455       }
1456       // If we already have it, ignore the variant.
1457       if (AlreadyExists) continue;
1458
1459       // Otherwise, add it to the list of patterns we have.
1460       PatternsToMatch.push_back(std::make_pair(Variant, 
1461                                                PatternsToMatch[i].second));
1462     }
1463
1464     DEBUG(std::cerr << "\n");
1465   }
1466 }
1467
1468
1469 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1470 /// patterns before small ones.  This is used to determine the size of a
1471 /// pattern.
1472 static unsigned getPatternSize(TreePatternNode *P) {
1473   assert(isExtIntegerVT(P->getExtType()) || 
1474          isExtFloatingPointVT(P->getExtType()) &&
1475          "Not a valid pattern node to size!");
1476   unsigned Size = 1;  // The node itself.
1477   
1478   // Count children in the count if they are also nodes.
1479   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1480     TreePatternNode *Child = P->getChild(i);
1481     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1482       Size += getPatternSize(Child);
1483     else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1484       ++Size;  // Matches a ConstantSDNode.
1485     }
1486   }
1487   
1488   return Size;
1489 }
1490
1491 /// getResultPatternCost - Compute the number of instructions for this pattern.
1492 /// This is a temporary hack.  We should really include the instruction
1493 /// latencies in this calculation.
1494 static unsigned getResultPatternCost(TreePatternNode *P) {
1495   if (P->isLeaf()) return 0;
1496   
1497   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1498   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1499     Cost += getResultPatternCost(P->getChild(i));
1500   return Cost;
1501 }
1502
1503 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1504 // In particular, we want to match maximal patterns first and lowest cost within
1505 // a particular complexity first.
1506 struct PatternSortingPredicate {
1507   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1508                   DAGISelEmitter::PatternToMatch *RHS) {
1509     unsigned LHSSize = getPatternSize(LHS->first);
1510     unsigned RHSSize = getPatternSize(RHS->first);
1511     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1512     if (LHSSize < RHSSize) return false;
1513     
1514     // If the patterns have equal complexity, compare generated instruction cost
1515     return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1516   }
1517 };
1518
1519 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1520 /// if the match fails.  At this point, we already know that the opcode for N
1521 /// matches, and the SDNode for the result has the RootName specified name.
1522 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1523                                          const std::string &RootName,
1524                                      std::map<std::string,std::string> &VarMap,
1525                                          unsigned PatternNo, std::ostream &OS) {
1526   assert(!N->isLeaf() && "Cannot match against a leaf!");
1527   
1528   // If this node has a name associated with it, capture it in VarMap.  If
1529   // we already saw this in the pattern, emit code to verify dagness.
1530   if (!N->getName().empty()) {
1531     std::string &VarMapEntry = VarMap[N->getName()];
1532     if (VarMapEntry.empty()) {
1533       VarMapEntry = RootName;
1534     } else {
1535       // If we get here, this is a second reference to a specific name.  Since
1536       // we already have checked that the first reference is valid, we don't
1537       // have to recursively match it, just check that it's the same as the
1538       // previously named thing.
1539       OS << "      if (" << VarMapEntry << " != " << RootName
1540          << ") goto P" << PatternNo << "Fail;\n";
1541       return;
1542     }
1543   }
1544   
1545   // Emit code to load the child nodes and match their contents recursively.
1546   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1547     OS << "      SDOperand " << RootName << i <<" = " << RootName
1548        << ".getOperand(" << i << ");\n";
1549     TreePatternNode *Child = N->getChild(i);
1550     
1551     if (!Child->isLeaf()) {
1552       // If it's not a leaf, recursively match.
1553       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1554       OS << "      if (" << RootName << i << ".getOpcode() != "
1555          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1556       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1557     } else {
1558       // If this child has a name associated with it, capture it in VarMap.  If
1559       // we already saw this in the pattern, emit code to verify dagness.
1560       if (!Child->getName().empty()) {
1561         std::string &VarMapEntry = VarMap[Child->getName()];
1562         if (VarMapEntry.empty()) {
1563           VarMapEntry = RootName + utostr(i);
1564         } else {
1565           // If we get here, this is a second reference to a specific name.  Since
1566           // we already have checked that the first reference is valid, we don't
1567           // have to recursively match it, just check that it's the same as the
1568           // previously named thing.
1569           OS << "      if (" << VarMapEntry << " != " << RootName << i
1570           << ") goto P" << PatternNo << "Fail;\n";
1571           continue;
1572         }
1573       }
1574       
1575       // Handle leaves of various types.
1576       if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1577         Record *LeafRec = DI->getDef();
1578         if (LeafRec->isSubClassOf("RegisterClass")) {
1579           // Handle register references.  Nothing to do here.
1580         } else if (LeafRec->isSubClassOf("ValueType")) {
1581           // Make sure this is the specified value type.
1582           OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1583           << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1584           << "Fail;\n";
1585         } else {
1586           Child->dump();
1587           assert(0 && "Unknown leaf type!");
1588         }
1589       } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1590         OS << "      if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1591            << "          cast<ConstantSDNode>(" << RootName << i
1592            << ")->getValue() != " << II->getValue() << ")\n"
1593            << "        goto P" << PatternNo << "Fail;\n";
1594       } else {
1595         Child->dump();
1596         assert(0 && "Unknown leaf type!");
1597       }
1598     }
1599   }
1600   
1601   // If there is a node predicate for this, emit the call.
1602   if (!N->getPredicateFn().empty())
1603     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1604        << ".Val)) goto P" << PatternNo << "Fail;\n";
1605 }
1606
1607 /// CodeGenPatternResult - Emit the action for a pattern.  Now that it has
1608 /// matched, we actually have to build a DAG!
1609 unsigned DAGISelEmitter::
1610 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1611                      std::map<std::string,std::string> &VariableMap, 
1612                      std::ostream &OS, bool isRoot) {
1613   // This is something selected from the pattern we matched.
1614   if (!N->getName().empty()) {
1615     assert(!isRoot && "Root of pattern cannot be a leaf!");
1616     std::string &Val = VariableMap[N->getName()];
1617     assert(!Val.empty() &&
1618            "Variable referenced but not defined and not caught earlier!");
1619     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1620       // Already selected this operand, just return the tmpval.
1621       return atoi(Val.c_str()+3);
1622     }
1623     
1624     unsigned ResNo = Ctr++;
1625     if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1626       switch (N->getType()) {
1627       default: assert(0 && "Unknown type for constant node!");
1628       case MVT::i1:  OS << "      bool Tmp"; break;
1629       case MVT::i8:  OS << "      unsigned char Tmp"; break;
1630       case MVT::i16: OS << "      unsigned short Tmp"; break;
1631       case MVT::i32: OS << "      unsigned Tmp"; break;
1632       case MVT::i64: OS << "      uint64_t Tmp"; break;
1633       }
1634       OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1635       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1636          << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1637     } else {
1638       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1639     }
1640     // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1641     // value if used multiple times by this pattern result.
1642     Val = "Tmp"+utostr(ResNo);
1643     return ResNo;
1644   }
1645   
1646   if (N->isLeaf()) {
1647     // If this is an explicit register reference, handle it.
1648     if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1649       unsigned ResNo = Ctr++;
1650       if (DI->getDef()->isSubClassOf("Register")) {
1651         OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1652            << getQualifiedName(DI->getDef()) << ", MVT::"
1653            << getEnumName(N->getType())
1654            << ");\n";
1655         return ResNo;
1656       }
1657     } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1658       unsigned ResNo = Ctr++;
1659       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1660          << II->getValue() << ", MVT::"
1661         << getEnumName(N->getType())
1662         << ");\n";
1663       return ResNo;
1664     }
1665     
1666     N->dump();
1667     assert(0 && "Unknown leaf type!");
1668     return ~0U;
1669   }
1670
1671   Record *Op = N->getOperator();
1672   if (Op->isSubClassOf("Instruction")) {
1673     // Emit all of the operands.
1674     std::vector<unsigned> Ops;
1675     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1676       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1677
1678     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1679     unsigned ResNo = Ctr++;
1680     
1681     if (!isRoot) {
1682       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1683          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1684          << getEnumName(N->getType());
1685       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1686         OS << ", Tmp" << Ops[i];
1687       OS << ");\n";
1688     } else {
1689       // If this instruction is the root, and if there is only one use of it,
1690       // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1691       OS << "      if (N.Val->hasOneUse()) {\n";
1692       OS << "        CurDAG->SelectNodeTo(N.Val, "
1693          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1694          << getEnumName(N->getType());
1695       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1696         OS << ", Tmp" << Ops[i];
1697       OS << ");\n";
1698       OS << "        return N;\n";
1699       OS << "      } else {\n";
1700       OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
1701       << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1702       << getEnumName(N->getType());
1703       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1704         OS << ", Tmp" << Ops[i];
1705       OS << ");\n";
1706       OS << "      }\n";
1707     }
1708     return ResNo;
1709   } else if (Op->isSubClassOf("SDNodeXForm")) {
1710     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1711     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1712     
1713     unsigned ResNo = Ctr++;
1714     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1715        << "(Tmp" << OpVal << ".Val);\n";
1716     if (isRoot) {
1717       OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
1718       OS << "      return Tmp" << ResNo << ";\n";
1719     }
1720     return ResNo;
1721   } else {
1722     N->dump();
1723     assert(0 && "Unknown node in result pattern!");
1724     return ~0U;
1725   }
1726 }
1727
1728 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1729 /// type information from it.
1730 static void RemoveAllTypes(TreePatternNode *N) {
1731   N->setType(MVT::isUnknown);
1732   if (!N->isLeaf())
1733     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1734       RemoveAllTypes(N->getChild(i));
1735 }
1736
1737 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1738 /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
1739 /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1740 /// for, this returns true otherwise false if Pat has all types.
1741 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1742                                const std::string &Prefix, unsigned PatternNo,
1743                                std::ostream &OS) {
1744   // Did we find one?
1745   if (!Pat->hasTypeSet()) {
1746     // Move a type over from 'other' to 'pat'.
1747     Pat->setType(Other->getType());
1748     OS << "      if (" << Prefix << ".getValueType() != MVT::"
1749        << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1750     return true;
1751   } else if (Pat->isLeaf()) {
1752     return false;
1753   }
1754   
1755   for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1756     if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1757                            Prefix + utostr(i), PatternNo, OS))
1758       return true;
1759   return false;
1760 }
1761
1762 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1763 /// stream to match the pattern, and generate the code for the match if it
1764 /// succeeds.
1765 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1766                                         std::ostream &OS) {
1767   static unsigned PatternCount = 0;
1768   unsigned PatternNo = PatternCount++;
1769   OS << "    { // Pattern #" << PatternNo << ": ";
1770   Pattern.first->print(OS);
1771   OS << "\n      // Emits: ";
1772   Pattern.second->print(OS);
1773   OS << "\n";
1774   OS << "      // Pattern complexity = " << getPatternSize(Pattern.first)
1775      << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
1776
1777   // Emit the matcher, capturing named arguments in VariableMap.
1778   std::map<std::string,std::string> VariableMap;
1779   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1780   
1781   // TP - Get *SOME* tree pattern, we don't care which.
1782   TreePattern &TP = *PatternFragments.begin()->second;
1783   
1784   // At this point, we know that we structurally match the pattern, but the
1785   // types of the nodes may not match.  Figure out the fewest number of type 
1786   // comparisons we need to emit.  For example, if there is only one integer
1787   // type supported by a target, there should be no type comparisons at all for
1788   // integer patterns!
1789   //
1790   // To figure out the fewest number of type checks needed, clone the pattern,
1791   // remove the types, then perform type inference on the pattern as a whole.
1792   // If there are unresolved types, emit an explicit check for those types,
1793   // apply the type to the tree, then rerun type inference.  Iterate until all
1794   // types are resolved.
1795   //
1796   TreePatternNode *Pat = Pattern.first->clone();
1797   RemoveAllTypes(Pat);
1798   
1799   do {
1800     // Resolve/propagate as many types as possible.
1801     try {
1802       bool MadeChange = true;
1803       while (MadeChange)
1804         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1805     } catch (...) {
1806       assert(0 && "Error: could not find consistent types for something we"
1807              " already decided was ok!");
1808       abort();
1809     }
1810
1811     // Insert a check for an unresolved type and add it to the tree.  If we find
1812     // an unresolved type to add a check for, this returns true and we iterate,
1813     // otherwise we are done.
1814   } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1815   
1816   unsigned TmpNo = 0;
1817   CodeGenPatternResult(Pattern.second, TmpNo,
1818                        VariableMap, OS, true /*the root*/);
1819   delete Pat;
1820   
1821   OS << "    }\n  P" << PatternNo << "Fail:\n";
1822 }
1823
1824
1825 namespace {
1826   /// CompareByRecordName - An ordering predicate that implements less-than by
1827   /// comparing the names records.
1828   struct CompareByRecordName {
1829     bool operator()(const Record *LHS, const Record *RHS) const {
1830       // Sort by name first.
1831       if (LHS->getName() < RHS->getName()) return true;
1832       // If both names are equal, sort by pointer.
1833       return LHS->getName() == RHS->getName() && LHS < RHS;
1834     }
1835   };
1836 }
1837
1838 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1839   std::string InstNS = Target.inst_begin()->second.Namespace;
1840   if (!InstNS.empty()) InstNS += "::";
1841   
1842   // Emit boilerplate.
1843   OS << "// The main instruction selector code.\n"
1844      << "SDOperand SelectCode(SDOperand N) {\n"
1845      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1846      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1847      << "INSTRUCTION_LIST_END))\n"
1848      << "    return N;   // Already selected.\n\n"
1849      << "  if (!N.Val->hasOneUse()) {\n"
1850   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1851      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1852      << "  }\n"
1853      << "  switch (N.getOpcode()) {\n"
1854      << "  default: break;\n"
1855      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1856      << "    return N;\n"
1857      << "  case ISD::AssertSext:\n"
1858      << "  case ISD::AssertZext: {\n"
1859      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
1860      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1861      << "    return Tmp0;\n"
1862      << "  }\n";
1863     
1864   // Group the patterns by their top-level opcodes.
1865   std::map<Record*, std::vector<PatternToMatch*>,
1866            CompareByRecordName> PatternsByOpcode;
1867   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1868     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1869       .push_back(&PatternsToMatch[i]);
1870   
1871   // Loop over all of the case statements.
1872   for (std::map<Record*, std::vector<PatternToMatch*>,
1873                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1874        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1875     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1876     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1877     
1878     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1879
1880     // We want to emit all of the matching code now.  However, we want to emit
1881     // the matches in order of minimal cost.  Sort the patterns so the least
1882     // cost one is at the start.
1883     std::stable_sort(Patterns.begin(), Patterns.end(),
1884                      PatternSortingPredicate());
1885     
1886     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1887       EmitCodeForPattern(*Patterns[i], OS);
1888     OS << "    break;\n\n";
1889   }
1890   
1891
1892   OS << "  } // end of big switch.\n\n"
1893      << "  std::cerr << \"Cannot yet select: \";\n"
1894      << "  N.Val->dump();\n"
1895      << "  std::cerr << '\\n';\n"
1896      << "  abort();\n"
1897      << "}\n";
1898 }
1899
1900 void DAGISelEmitter::run(std::ostream &OS) {
1901   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1902                        " target", OS);
1903   
1904   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1905      << "// *** instruction selector class.  These functions are really "
1906      << "methods.\n\n";
1907   
1908   OS << "// Instance var to keep track of multiply used nodes that have \n"
1909      << "// already been selected.\n"
1910      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1911   
1912   ParseNodeInfo();
1913   ParseNodeTransforms(OS);
1914   ParsePatternFragments(OS);
1915   ParseInstructions();
1916   ParsePatterns();
1917   
1918   // Generate variants.  For example, commutative patterns can match
1919   // multiple ways.  Add them to PatternsToMatch as well.
1920   GenerateVariants();
1921
1922   
1923   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1924         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1925           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
1926           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
1927           std::cerr << "\n";
1928         });
1929   
1930   // At this point, we have full information about the 'Patterns' we need to
1931   // parse, both implicitly from instructions as well as from explicit pattern
1932   // definitions.  Emit the resultant instruction selector.
1933   EmitInstructionSelector(OS);  
1934   
1935   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1936        E = PatternFragments.end(); I != E; ++I)
1937     delete I->second;
1938   PatternFragments.clear();
1939
1940   Instructions.clear();
1941 }