Asserting here is to violent
[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,
577                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
578    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
579      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
580 }
581
582 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
583                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
584   Trees.push_back(ParseTreePattern(Pat));
585 }
586
587 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, 
588                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
589   Trees.push_back(Pat);
590 }
591
592
593
594 void TreePattern::error(const std::string &Msg) const {
595   dump();
596   throw "In " + TheRecord->getName() + ": " + Msg;
597 }
598
599 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
600   Record *Operator = Dag->getNodeType();
601   
602   if (Operator->isSubClassOf("ValueType")) {
603     // If the operator is a ValueType, then this must be "type cast" of a leaf
604     // node.
605     if (Dag->getNumArgs() != 1)
606       error("Type cast only takes one operand!");
607     
608     Init *Arg = Dag->getArg(0);
609     TreePatternNode *New;
610     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
611       Record *R = DI->getDef();
612       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
613         Dag->setArg(0, new DagInit(R,
614                                 std::vector<std::pair<Init*, std::string> >()));
615         TreePatternNode *TPN = ParseTreePattern(Dag);
616         TPN->setName(Dag->getArgName(0));
617         return TPN;
618       }   
619       
620       New = new TreePatternNode(DI);
621     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
622       New = ParseTreePattern(DI);
623     } else {
624       Arg->dump();
625       error("Unknown leaf value for tree pattern!");
626       return 0;
627     }
628     
629     // Apply the type cast.
630     New->UpdateNodeType(getValueType(Operator), *this);
631     return New;
632   }
633   
634   // Verify that this is something that makes sense for an operator.
635   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
636       !Operator->isSubClassOf("Instruction") && 
637       !Operator->isSubClassOf("SDNodeXForm") &&
638       Operator->getName() != "set")
639     error("Unrecognized node '" + Operator->getName() + "'!");
640   
641   std::vector<TreePatternNode*> Children;
642   
643   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
644     Init *Arg = Dag->getArg(i);
645     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
646       Children.push_back(ParseTreePattern(DI));
647       Children.back()->setName(Dag->getArgName(i));
648     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
649       Record *R = DefI->getDef();
650       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
651       // TreePatternNode if its own.
652       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
653         Dag->setArg(i, new DagInit(R,
654                               std::vector<std::pair<Init*, std::string> >()));
655         --i;  // Revisit this node...
656       } else {
657         TreePatternNode *Node = new TreePatternNode(DefI);
658         Node->setName(Dag->getArgName(i));
659         Children.push_back(Node);
660         
661         // Input argument?
662         if (R->getName() == "node") {
663           if (Dag->getArgName(i).empty())
664             error("'node' argument requires a name to match with operand list");
665           Args.push_back(Dag->getArgName(i));
666         }
667       }
668     } else {
669       Arg->dump();
670       error("Unknown leaf value for tree pattern!");
671     }
672   }
673   
674   return new TreePatternNode(Operator, Children);
675 }
676
677 /// InferAllTypes - Infer/propagate as many types throughout the expression
678 /// patterns as possible.  Return true if all types are infered, false
679 /// otherwise.  Throw an exception if a type contradiction is found.
680 bool TreePattern::InferAllTypes() {
681   bool MadeChange = true;
682   while (MadeChange) {
683     MadeChange = false;
684     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
685       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
686   }
687   
688   bool HasUnresolvedTypes = false;
689   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
690     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
691   return !HasUnresolvedTypes;
692 }
693
694 void TreePattern::print(std::ostream &OS) const {
695   OS << getRecord()->getName();
696   if (!Args.empty()) {
697     OS << "(" << Args[0];
698     for (unsigned i = 1, e = Args.size(); i != e; ++i)
699       OS << ", " << Args[i];
700     OS << ")";
701   }
702   OS << ": ";
703   
704   if (Trees.size() > 1)
705     OS << "[\n";
706   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
707     OS << "\t";
708     Trees[i]->print(OS);
709     OS << "\n";
710   }
711
712   if (Trees.size() > 1)
713     OS << "]\n";
714 }
715
716 void TreePattern::dump() const { print(std::cerr); }
717
718
719
720 //===----------------------------------------------------------------------===//
721 // DAGISelEmitter implementation
722 //
723
724 // Parse all of the SDNode definitions for the target, populating SDNodes.
725 void DAGISelEmitter::ParseNodeInfo() {
726   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
727   while (!Nodes.empty()) {
728     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
729     Nodes.pop_back();
730   }
731 }
732
733 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
734 /// map, and emit them to the file as functions.
735 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
736   OS << "\n// Node transformations.\n";
737   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
738   while (!Xforms.empty()) {
739     Record *XFormNode = Xforms.back();
740     Record *SDNode = XFormNode->getValueAsDef("Opcode");
741     std::string Code = XFormNode->getValueAsCode("XFormFunction");
742     SDNodeXForms.insert(std::make_pair(XFormNode,
743                                        std::make_pair(SDNode, Code)));
744
745     if (!Code.empty()) {
746       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
747       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
748
749       OS << "inline SDOperand Transform_" << XFormNode->getName()
750          << "(SDNode *" << C2 << ") {\n";
751       if (ClassName != "SDNode")
752         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
753       OS << Code << "\n}\n";
754     }
755
756     Xforms.pop_back();
757   }
758 }
759
760
761
762 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
763 /// file, building up the PatternFragments map.  After we've collected them all,
764 /// inline fragments together as necessary, so that there are no references left
765 /// inside a pattern fragment to a pattern fragment.
766 ///
767 /// This also emits all of the predicate functions to the output file.
768 ///
769 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
770   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
771   
772   // First step, parse all of the fragments and emit predicate functions.
773   OS << "\n// Predicate functions.\n";
774   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
775     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
776     TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
777     PatternFragments[Fragments[i]] = P;
778     
779     // Validate the argument list, converting it to map, to discard duplicates.
780     std::vector<std::string> &Args = P->getArgList();
781     std::set<std::string> OperandsMap(Args.begin(), Args.end());
782     
783     if (OperandsMap.count(""))
784       P->error("Cannot have unnamed 'node' values in pattern fragment!");
785     
786     // Parse the operands list.
787     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
788     if (OpsList->getNodeType()->getName() != "ops")
789       P->error("Operands list should start with '(ops ... '!");
790     
791     // Copy over the arguments.       
792     Args.clear();
793     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
794       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
795           static_cast<DefInit*>(OpsList->getArg(j))->
796           getDef()->getName() != "node")
797         P->error("Operands list should all be 'node' values.");
798       if (OpsList->getArgName(j).empty())
799         P->error("Operands list should have names for each operand!");
800       if (!OperandsMap.count(OpsList->getArgName(j)))
801         P->error("'" + OpsList->getArgName(j) +
802                  "' does not occur in pattern or was multiply specified!");
803       OperandsMap.erase(OpsList->getArgName(j));
804       Args.push_back(OpsList->getArgName(j));
805     }
806     
807     if (!OperandsMap.empty())
808       P->error("Operands list does not contain an entry for operand '" +
809                *OperandsMap.begin() + "'!");
810
811     // If there is a code init for this fragment, emit the predicate code and
812     // keep track of the fact that this fragment uses it.
813     std::string Code = Fragments[i]->getValueAsCode("Predicate");
814     if (!Code.empty()) {
815       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
816       std::string ClassName =
817         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
818       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
819       
820       OS << "inline bool Predicate_" << Fragments[i]->getName()
821          << "(SDNode *" << C2 << ") {\n";
822       if (ClassName != "SDNode")
823         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
824       OS << Code << "\n}\n";
825       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
826     }
827     
828     // If there is a node transformation corresponding to this, keep track of
829     // it.
830     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
831     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
832       P->getOnlyTree()->setTransformFn(Transform);
833   }
834   
835   OS << "\n\n";
836
837   // Now that we've parsed all of the tree fragments, do a closure on them so
838   // that there are not references to PatFrags left inside of them.
839   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
840        E = PatternFragments.end(); I != E; ++I) {
841     TreePattern *ThePat = I->second;
842     ThePat->InlinePatternFragments();
843         
844     // Infer as many types as possible.  Don't worry about it if we don't infer
845     // all of them, some may depend on the inputs of the pattern.
846     try {
847       ThePat->InferAllTypes();
848     } catch (...) {
849       // If this pattern fragment is not supported by this target (no types can
850       // satisfy its constraints), just ignore it.  If the bogus pattern is
851       // actually used by instructions, the type consistency error will be
852       // reported there.
853     }
854     
855     // If debugging, print out the pattern fragment result.
856     DEBUG(ThePat->dump());
857   }
858 }
859
860 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
861 /// instruction input.  Return true if this is a real use.
862 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
863                       std::map<std::string, TreePatternNode*> &InstInputs) {
864   // No name -> not interesting.
865   if (Pat->getName().empty()) {
866     if (Pat->isLeaf()) {
867       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
868       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
869         I->error("Input " + DI->getDef()->getName() + " must be named!");
870
871     }
872     return false;
873   }
874
875   Record *Rec;
876   if (Pat->isLeaf()) {
877     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
878     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
879     Rec = DI->getDef();
880   } else {
881     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
882     Rec = Pat->getOperator();
883   }
884
885   TreePatternNode *&Slot = InstInputs[Pat->getName()];
886   if (!Slot) {
887     Slot = Pat;
888   } else {
889     Record *SlotRec;
890     if (Slot->isLeaf()) {
891       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
892     } else {
893       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
894       SlotRec = Slot->getOperator();
895     }
896     
897     // Ensure that the inputs agree if we've already seen this input.
898     if (Rec != SlotRec)
899       I->error("All $" + Pat->getName() + " inputs must agree with each other");
900     if (Slot->getExtType() != Pat->getExtType())
901       I->error("All $" + Pat->getName() + " inputs must agree with each other");
902   }
903   return true;
904 }
905
906 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
907 /// part of "I", the instruction), computing the set of inputs and outputs of
908 /// the pattern.  Report errors if we see anything naughty.
909 void DAGISelEmitter::
910 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
911                             std::map<std::string, TreePatternNode*> &InstInputs,
912                             std::map<std::string, Record*> &InstResults) {
913   if (Pat->isLeaf()) {
914     bool isUse = HandleUse(I, Pat, InstInputs);
915     if (!isUse && Pat->getTransformFn())
916       I->error("Cannot specify a transform function for a non-input value!");
917     return;
918   } else if (Pat->getOperator()->getName() != "set") {
919     // If this is not a set, verify that the children nodes are not void typed,
920     // and recurse.
921     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
922       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
923         I->error("Cannot have void nodes inside of patterns!");
924       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
925     }
926     
927     // If this is a non-leaf node with no children, treat it basically as if
928     // it were a leaf.  This handles nodes like (imm).
929     bool isUse = false;
930     if (Pat->getNumChildren() == 0)
931       isUse = HandleUse(I, Pat, InstInputs);
932     
933     if (!isUse && Pat->getTransformFn())
934       I->error("Cannot specify a transform function for a non-input value!");
935     return;
936   } 
937   
938   // Otherwise, this is a set, validate and collect instruction results.
939   if (Pat->getNumChildren() == 0)
940     I->error("set requires operands!");
941   else if (Pat->getNumChildren() & 1)
942     I->error("set requires an even number of operands");
943   
944   if (Pat->getTransformFn())
945     I->error("Cannot specify a transform function on a set node!");
946   
947   // Check the set destinations.
948   unsigned NumValues = Pat->getNumChildren()/2;
949   for (unsigned i = 0; i != NumValues; ++i) {
950     TreePatternNode *Dest = Pat->getChild(i);
951     if (!Dest->isLeaf())
952       I->error("set destination should be a virtual register!");
953     
954     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
955     if (!Val)
956       I->error("set destination should be a virtual register!");
957     
958     if (!Val->getDef()->isSubClassOf("RegisterClass"))
959       I->error("set destination should be a virtual register!");
960     if (Dest->getName().empty())
961       I->error("set destination must have a name!");
962     if (InstResults.count(Dest->getName()))
963       I->error("cannot set '" + Dest->getName() +"' multiple times");
964     InstResults[Dest->getName()] = Val->getDef();
965
966     // Verify and collect info from the computation.
967     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
968                                 InstInputs, InstResults);
969   }
970 }
971
972
973 /// ParseInstructions - Parse all of the instructions, inlining and resolving
974 /// any fragments involved.  This populates the Instructions list with fully
975 /// resolved instructions.
976 void DAGISelEmitter::ParseInstructions() {
977   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
978   
979   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
980     ListInit *LI = 0;
981     
982     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
983       LI = Instrs[i]->getValueAsListInit("Pattern");
984     
985     // If there is no pattern, only collect minimal information about the
986     // instruction for its operand list.  We have to assume that there is one
987     // result, as we have no detailed info.
988     if (!LI || LI->getSize() == 0) {
989       std::vector<MVT::ValueType> ResultTypes;
990       std::vector<MVT::ValueType> OperandTypes;
991       
992       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
993       
994       // Doesn't even define a result?
995       if (InstInfo.OperandList.size() == 0)
996         continue;
997       
998       // Assume the first operand is the result.
999       ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1000       
1001       // The rest are inputs.
1002       for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1003         OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1004       
1005       // Create and insert the instruction.
1006       Instructions.insert(std::make_pair(Instrs[i], 
1007                             DAGInstruction(0, ResultTypes, OperandTypes)));
1008       continue;  // no pattern.
1009     }
1010     
1011     // Parse the instruction.
1012     TreePattern *I = new TreePattern(Instrs[i], LI, *this);
1013     // Inline pattern fragments into it.
1014     I->InlinePatternFragments();
1015     
1016     // Infer as many types as possible.  If we cannot infer all of them, we can
1017     // never do anything with this instruction pattern: report it to the user.
1018     if (!I->InferAllTypes())
1019       I->error("Could not infer all types in pattern!");
1020     
1021     // InstInputs - Keep track of all of the inputs of the instruction, along 
1022     // with the record they are declared as.
1023     std::map<std::string, TreePatternNode*> InstInputs;
1024     
1025     // InstResults - Keep track of all the virtual registers that are 'set'
1026     // in the instruction, including what reg class they are.
1027     std::map<std::string, Record*> InstResults;
1028     
1029     // Verify that the top-level forms in the instruction are of void type, and
1030     // fill in the InstResults map.
1031     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1032       TreePatternNode *Pat = I->getTree(j);
1033       if (Pat->getExtType() != MVT::isVoid) {
1034         I->dump();
1035         I->error("Top-level forms in instruction pattern should have"
1036                  " void types");
1037       }
1038
1039       // Find inputs and outputs, and verify the structure of the uses/defs.
1040       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1041     }
1042
1043     // Now that we have inputs and outputs of the pattern, inspect the operands
1044     // list for the instruction.  This determines the order that operands are
1045     // added to the machine instruction the node corresponds to.
1046     unsigned NumResults = InstResults.size();
1047
1048     // Parse the operands list from the (ops) list, validating it.
1049     std::vector<std::string> &Args = I->getArgList();
1050     assert(Args.empty() && "Args list should still be empty here!");
1051     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1052
1053     // Check that all of the results occur first in the list.
1054     std::vector<MVT::ValueType> ResultTypes;
1055     for (unsigned i = 0; i != NumResults; ++i) {
1056       if (i == CGI.OperandList.size())
1057         I->error("'" + InstResults.begin()->first +
1058                  "' set but does not appear in operand list!");
1059       const std::string &OpName = CGI.OperandList[i].Name;
1060       
1061       // Check that it exists in InstResults.
1062       Record *R = InstResults[OpName];
1063       if (R == 0)
1064         I->error("Operand $" + OpName + " should be a set destination: all "
1065                  "outputs must occur before inputs in operand list!");
1066       
1067       if (CGI.OperandList[i].Rec != R)
1068         I->error("Operand $" + OpName + " class mismatch!");
1069       
1070       // Remember the return type.
1071       ResultTypes.push_back(CGI.OperandList[i].Ty);
1072       
1073       // Okay, this one checks out.
1074       InstResults.erase(OpName);
1075     }
1076
1077     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1078     // the copy while we're checking the inputs.
1079     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1080
1081     std::vector<TreePatternNode*> ResultNodeOperands;
1082     std::vector<MVT::ValueType> OperandTypes;
1083     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1084       const std::string &OpName = CGI.OperandList[i].Name;
1085       if (OpName.empty())
1086         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1087
1088       if (!InstInputsCheck.count(OpName))
1089         I->error("Operand $" + OpName +
1090                  " does not appear in the instruction pattern");
1091       TreePatternNode *InVal = InstInputsCheck[OpName];
1092       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1093       if (CGI.OperandList[i].Ty != InVal->getExtType())
1094         I->error("Operand $" + OpName +
1095                  "'s type disagrees between the operand and pattern");
1096       OperandTypes.push_back(InVal->getType());
1097       
1098       // Construct the result for the dest-pattern operand list.
1099       TreePatternNode *OpNode = InVal->clone();
1100       
1101       // No predicate is useful on the result.
1102       OpNode->setPredicateFn("");
1103       
1104       // Promote the xform function to be an explicit node if set.
1105       if (Record *Xform = OpNode->getTransformFn()) {
1106         OpNode->setTransformFn(0);
1107         std::vector<TreePatternNode*> Children;
1108         Children.push_back(OpNode);
1109         OpNode = new TreePatternNode(Xform, Children);
1110       }
1111       
1112       ResultNodeOperands.push_back(OpNode);
1113     }
1114     
1115     if (!InstInputsCheck.empty())
1116       I->error("Input operand $" + InstInputsCheck.begin()->first +
1117                " occurs in pattern but not in operands list!");
1118
1119     TreePatternNode *ResultPattern =
1120       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1121
1122     // Create and insert the instruction.
1123     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1124     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1125
1126     // Use a temporary tree pattern to infer all types and make sure that the
1127     // constructed result is correct.  This depends on the instruction already
1128     // being inserted into the Instructions map.
1129     TreePattern Temp(I->getRecord(), ResultPattern, *this);
1130     Temp.InferAllTypes();
1131
1132     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1133     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1134     
1135     DEBUG(I->dump());
1136   }
1137    
1138   // If we can, convert the instructions to be patterns that are matched!
1139   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1140        E = Instructions.end(); II != E; ++II) {
1141     TreePattern *I = II->second.getPattern();
1142     if (I == 0) continue;  // No pattern.
1143     
1144     if (I->getNumTrees() != 1) {
1145       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1146       continue;
1147     }
1148     TreePatternNode *Pattern = I->getTree(0);
1149     if (Pattern->getOperator()->getName() != "set")
1150       continue;  // Not a set (store or something?)
1151     
1152     if (Pattern->getNumChildren() != 2)
1153       continue;  // Not a set of a single value (not handled so far)
1154     
1155     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1156     
1157     std::string Reason;
1158     if (!SrcPattern->canPatternMatch(Reason, *this))
1159       I->error("Instruction can never match: " + Reason);
1160     
1161     TreePatternNode *DstPattern = II->second.getResultPattern();
1162     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1163   }
1164 }
1165
1166 void DAGISelEmitter::ParsePatterns() {
1167   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1168
1169   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1170     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1171     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
1172
1173     // Inline pattern fragments into it.
1174     Pattern->InlinePatternFragments();
1175     
1176     // Infer as many types as possible.  If we cannot infer all of them, we can
1177     // never do anything with this pattern: report it to the user.
1178     if (!Pattern->InferAllTypes())
1179       Pattern->error("Could not infer all types in pattern!");
1180     
1181     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1182     if (LI->getSize() == 0) continue;  // no pattern.
1183     
1184     // Parse the instruction.
1185     TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
1186     
1187     // Inline pattern fragments into it.
1188     Result->InlinePatternFragments();
1189     
1190     // Infer as many types as possible.  If we cannot infer all of them, we can
1191     // never do anything with this pattern: report it to the user.
1192     if (!Result->InferAllTypes())
1193       Result->error("Could not infer all types in pattern result!");
1194    
1195     if (Result->getNumTrees() != 1)
1196       Result->error("Cannot handle instructions producing instructions "
1197                     "with temporaries yet!");
1198
1199     std::string Reason;
1200     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1201       Pattern->error("Pattern can never match: " + Reason);
1202     
1203     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1204                                              Result->getOnlyTree()));
1205   }
1206 }
1207
1208 /// CombineChildVariants - Given a bunch of permutations of each child of the
1209 /// 'operator' node, put them together in all possible ways.
1210 static void CombineChildVariants(TreePatternNode *Orig, 
1211                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1212                                  std::vector<TreePatternNode*> &OutVariants,
1213                                  DAGISelEmitter &ISE) {
1214   // Make sure that each operand has at least one variant to choose from.
1215   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1216     if (ChildVariants[i].empty())
1217       return;
1218         
1219   // The end result is an all-pairs construction of the resultant pattern.
1220   std::vector<unsigned> Idxs;
1221   Idxs.resize(ChildVariants.size());
1222   bool NotDone = true;
1223   while (NotDone) {
1224     // Create the variant and add it to the output list.
1225     std::vector<TreePatternNode*> NewChildren;
1226     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1227       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1228     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1229     
1230     // Copy over properties.
1231     R->setName(Orig->getName());
1232     R->setPredicateFn(Orig->getPredicateFn());
1233     R->setTransformFn(Orig->getTransformFn());
1234     R->setType(Orig->getExtType());
1235     
1236     // If this pattern cannot every match, do not include it as a variant.
1237     std::string ErrString;
1238     if (!R->canPatternMatch(ErrString, ISE)) {
1239       delete R;
1240     } else {
1241       bool AlreadyExists = false;
1242       
1243       // Scan to see if this pattern has already been emitted.  We can get
1244       // duplication due to things like commuting:
1245       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1246       // which are the same pattern.  Ignore the dups.
1247       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1248         if (R->isIsomorphicTo(OutVariants[i])) {
1249           AlreadyExists = true;
1250           break;
1251         }
1252       
1253       if (AlreadyExists)
1254         delete R;
1255       else
1256         OutVariants.push_back(R);
1257     }
1258     
1259     // Increment indices to the next permutation.
1260     NotDone = false;
1261     // Look for something we can increment without causing a wrap-around.
1262     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1263       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1264         NotDone = true;   // Found something to increment.
1265         break;
1266       }
1267       Idxs[IdxsIdx] = 0;
1268     }
1269   }
1270 }
1271
1272 /// CombineChildVariants - A helper function for binary operators.
1273 ///
1274 static void CombineChildVariants(TreePatternNode *Orig, 
1275                                  const std::vector<TreePatternNode*> &LHS,
1276                                  const std::vector<TreePatternNode*> &RHS,
1277                                  std::vector<TreePatternNode*> &OutVariants,
1278                                  DAGISelEmitter &ISE) {
1279   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1280   ChildVariants.push_back(LHS);
1281   ChildVariants.push_back(RHS);
1282   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1283 }  
1284
1285
1286 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1287                                      std::vector<TreePatternNode *> &Children) {
1288   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1289   Record *Operator = N->getOperator();
1290   
1291   // Only permit raw nodes.
1292   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1293       N->getTransformFn()) {
1294     Children.push_back(N);
1295     return;
1296   }
1297
1298   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1299     Children.push_back(N->getChild(0));
1300   else
1301     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1302
1303   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1304     Children.push_back(N->getChild(1));
1305   else
1306     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1307 }
1308
1309 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1310 /// the (potentially recursive) pattern by using algebraic laws.
1311 ///
1312 static void GenerateVariantsOf(TreePatternNode *N,
1313                                std::vector<TreePatternNode*> &OutVariants,
1314                                DAGISelEmitter &ISE) {
1315   // We cannot permute leaves.
1316   if (N->isLeaf()) {
1317     OutVariants.push_back(N);
1318     return;
1319   }
1320
1321   // Look up interesting info about the node.
1322   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1323
1324   // If this node is associative, reassociate.
1325   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1326     // Reassociate by pulling together all of the linked operators 
1327     std::vector<TreePatternNode*> MaximalChildren;
1328     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1329
1330     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1331     // permutations.
1332     if (MaximalChildren.size() == 3) {
1333       // Find the variants of all of our maximal children.
1334       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1335       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1336       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1337       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1338       
1339       // There are only two ways we can permute the tree:
1340       //   (A op B) op C    and    A op (B op C)
1341       // Within these forms, we can also permute A/B/C.
1342       
1343       // Generate legal pair permutations of A/B/C.
1344       std::vector<TreePatternNode*> ABVariants;
1345       std::vector<TreePatternNode*> BAVariants;
1346       std::vector<TreePatternNode*> ACVariants;
1347       std::vector<TreePatternNode*> CAVariants;
1348       std::vector<TreePatternNode*> BCVariants;
1349       std::vector<TreePatternNode*> CBVariants;
1350       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1351       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1352       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1353       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1354       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1355       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1356
1357       // Combine those into the result: (x op x) op x
1358       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1359       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1360       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1361       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1362       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1363       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1364
1365       // Combine those into the result: x op (x op x)
1366       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1367       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1368       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1369       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1370       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1371       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1372       return;
1373     }
1374   }
1375   
1376   // Compute permutations of all children.
1377   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1378   ChildVariants.resize(N->getNumChildren());
1379   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1380     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1381
1382   // Build all permutations based on how the children were formed.
1383   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1384
1385   // If this node is commutative, consider the commuted order.
1386   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1387     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1388     // Consider the commuted order.
1389     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1390                          OutVariants, ISE);
1391   }
1392 }
1393
1394
1395 // GenerateVariants - Generate variants.  For example, commutative patterns can
1396 // match multiple ways.  Add them to PatternsToMatch as well.
1397 void DAGISelEmitter::GenerateVariants() {
1398   
1399   DEBUG(std::cerr << "Generating instruction variants.\n");
1400   
1401   // Loop over all of the patterns we've collected, checking to see if we can
1402   // generate variants of the instruction, through the exploitation of
1403   // identities.  This permits the target to provide agressive matching without
1404   // the .td file having to contain tons of variants of instructions.
1405   //
1406   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1407   // intentionally do not reconsider these.  Any variants of added patterns have
1408   // already been added.
1409   //
1410   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1411     std::vector<TreePatternNode*> Variants;
1412     GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1413
1414     assert(!Variants.empty() && "Must create at least original variant!");
1415     Variants.erase(Variants.begin());  // Remove the original pattern.
1416
1417     if (Variants.empty())  // No variants for this pattern.
1418       continue;
1419
1420     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1421           PatternsToMatch[i].first->dump();
1422           std::cerr << "\n");
1423
1424     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1425       TreePatternNode *Variant = Variants[v];
1426
1427       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1428             Variant->dump();
1429             std::cerr << "\n");
1430       
1431       // Scan to see if an instruction or explicit pattern already matches this.
1432       bool AlreadyExists = false;
1433       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1434         // Check to see if this variant already exists.
1435         if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1436           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1437           AlreadyExists = true;
1438           break;
1439         }
1440       }
1441       // If we already have it, ignore the variant.
1442       if (AlreadyExists) continue;
1443
1444       // Otherwise, add it to the list of patterns we have.
1445       PatternsToMatch.push_back(std::make_pair(Variant, 
1446                                                PatternsToMatch[i].second));
1447     }
1448
1449     DEBUG(std::cerr << "\n");
1450   }
1451 }
1452
1453
1454 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1455 /// patterns before small ones.  This is used to determine the size of a
1456 /// pattern.
1457 static unsigned getPatternSize(TreePatternNode *P) {
1458   assert(isExtIntegerVT(P->getExtType()) || 
1459          isExtFloatingPointVT(P->getExtType()) &&
1460          "Not a valid pattern node to size!");
1461   unsigned Size = 1;  // The node itself.
1462   
1463   // Count children in the count if they are also nodes.
1464   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1465     TreePatternNode *Child = P->getChild(i);
1466     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1467       Size += getPatternSize(Child);
1468   }
1469   
1470   return Size;
1471 }
1472
1473 /// getResultPatternCost - Compute the number of instructions for this pattern.
1474 /// This is a temporary hack.  We should really include the instruction
1475 /// latencies in this calculation.
1476 static unsigned getResultPatternCost(TreePatternNode *P) {
1477   if (P->isLeaf()) return 0;
1478   
1479   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1480   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1481     Cost += getResultPatternCost(P->getChild(i));
1482   return Cost;
1483 }
1484
1485 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1486 // In particular, we want to match maximal patterns first and lowest cost within
1487 // a particular complexity first.
1488 struct PatternSortingPredicate {
1489   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1490                   DAGISelEmitter::PatternToMatch *RHS) {
1491     unsigned LHSSize = getPatternSize(LHS->first);
1492     unsigned RHSSize = getPatternSize(RHS->first);
1493     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1494     if (LHSSize < RHSSize) return false;
1495     
1496     // If the patterns have equal complexity, compare generated instruction cost
1497     return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1498   }
1499 };
1500
1501 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1502 /// if the match fails.  At this point, we already know that the opcode for N
1503 /// matches, and the SDNode for the result has the RootName specified name.
1504 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1505                                          const std::string &RootName,
1506                                      std::map<std::string,std::string> &VarMap,
1507                                          unsigned PatternNo, std::ostream &OS) {
1508   assert(!N->isLeaf() && "Cannot match against a leaf!");
1509   
1510   // If this node has a name associated with it, capture it in VarMap.  If
1511   // we already saw this in the pattern, emit code to verify dagness.
1512   if (!N->getName().empty()) {
1513     std::string &VarMapEntry = VarMap[N->getName()];
1514     if (VarMapEntry.empty()) {
1515       VarMapEntry = RootName;
1516     } else {
1517       // If we get here, this is a second reference to a specific name.  Since
1518       // we already have checked that the first reference is valid, we don't
1519       // have to recursively match it, just check that it's the same as the
1520       // previously named thing.
1521       OS << "      if (" << VarMapEntry << " != " << RootName
1522          << ") goto P" << PatternNo << "Fail;\n";
1523       return;
1524     }
1525   }
1526   
1527   // Emit code to load the child nodes and match their contents recursively.
1528   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1529     OS << "      SDOperand " << RootName << i <<" = " << RootName
1530        << ".getOperand(" << i << ");\n";
1531     TreePatternNode *Child = N->getChild(i);
1532     
1533     if (!Child->isLeaf()) {
1534       // If it's not a leaf, recursively match.
1535       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1536       OS << "      if (" << RootName << i << ".getOpcode() != "
1537          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1538       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1539     } else {
1540       // If this child has a name associated with it, capture it in VarMap.  If
1541       // we already saw this in the pattern, emit code to verify dagness.
1542       if (!Child->getName().empty()) {
1543         std::string &VarMapEntry = VarMap[Child->getName()];
1544         if (VarMapEntry.empty()) {
1545           VarMapEntry = RootName + utostr(i);
1546         } else {
1547           // If we get here, this is a second reference to a specific name.  Since
1548           // we already have checked that the first reference is valid, we don't
1549           // have to recursively match it, just check that it's the same as the
1550           // previously named thing.
1551           OS << "      if (" << VarMapEntry << " != " << RootName << i
1552           << ") goto P" << PatternNo << "Fail;\n";
1553           continue;
1554         }
1555       }
1556       
1557       // Handle leaves of various types.
1558       Init *LeafVal = Child->getLeafValue();
1559       Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1560       if (LeafRec->isSubClassOf("RegisterClass")) {
1561         // Handle register references.  Nothing to do here.
1562       } else if (LeafRec->isSubClassOf("ValueType")) {
1563         // Make sure this is the specified value type.
1564         OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1565            << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1566            << "Fail;\n";
1567       } else {
1568         Child->dump();
1569         assert(0 && "Unknown leaf type!");
1570       }
1571     }
1572   }
1573   
1574   // If there is a node predicate for this, emit the call.
1575   if (!N->getPredicateFn().empty())
1576     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1577        << ".Val)) goto P" << PatternNo << "Fail;\n";
1578 }
1579
1580 /// CodeGenPatternResult - Emit the action for a pattern.  Now that it has
1581 /// matched, we actually have to build a DAG!
1582 unsigned DAGISelEmitter::
1583 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1584                      std::map<std::string,std::string> &VariableMap, 
1585                      std::ostream &OS, bool isRoot) {
1586   // This is something selected from the pattern we matched.
1587   if (!N->getName().empty()) {
1588     assert(!isRoot && "Root of pattern cannot be a leaf!");
1589     std::string &Val = VariableMap[N->getName()];
1590     assert(!Val.empty() &&
1591            "Variable referenced but not defined and not caught earlier!");
1592     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1593       // Already selected this operand, just return the tmpval.
1594       return atoi(Val.c_str()+3);
1595     }
1596     
1597     unsigned ResNo = Ctr++;
1598     if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1599       switch (N->getType()) {
1600       default: assert(0 && "Unknown type for constant node!");
1601       case MVT::i1:  OS << "      bool Tmp"; break;
1602       case MVT::i8:  OS << "      unsigned char Tmp"; break;
1603       case MVT::i16: OS << "      unsigned short Tmp"; break;
1604       case MVT::i32: OS << "      unsigned Tmp"; break;
1605       case MVT::i64: OS << "      uint64_t Tmp"; break;
1606       }
1607       OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1608       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1609          << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1610     } else {
1611       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1612     }
1613     // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1614     // value if used multiple times by this pattern result.
1615     Val = "Tmp"+utostr(ResNo);
1616     return ResNo;
1617   }
1618   
1619   if (N->isLeaf()) {
1620     N->dump();
1621     assert(0 && "Unknown leaf type!");
1622     return ~0U;
1623   }
1624
1625   Record *Op = N->getOperator();
1626   if (Op->isSubClassOf("Instruction")) {
1627     // Emit all of the operands.
1628     std::vector<unsigned> Ops;
1629     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1630       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1631
1632     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1633     unsigned ResNo = Ctr++;
1634     
1635     if (!isRoot) {
1636       OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1637          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1638          << getEnumName(N->getType());
1639       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1640         OS << ", Tmp" << Ops[i];
1641       OS << ");\n";
1642     } else {
1643       // If this instruction is the root, and if there is only one use of it,
1644       // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1645       OS << "      if (N.Val->hasOneUse()) {\n";
1646       OS << "        CurDAG->SelectNodeTo(N.Val, "
1647          << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1648          << getEnumName(N->getType());
1649       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1650         OS << ", Tmp" << Ops[i];
1651       OS << ");\n";
1652       OS << "        return N;\n";
1653       OS << "      } else {\n";
1654       OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
1655       << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1656       << getEnumName(N->getType());
1657       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1658         OS << ", Tmp" << Ops[i];
1659       OS << ");\n";
1660       OS << "      }\n";
1661     }
1662     return ResNo;
1663   } else if (Op->isSubClassOf("SDNodeXForm")) {
1664     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1665     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1666     
1667     unsigned ResNo = Ctr++;
1668     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1669        << "(Tmp" << OpVal << ".Val);\n";
1670     if (isRoot) {
1671       OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
1672       OS << "      return Tmp" << ResNo << ";\n";
1673     }
1674     return ResNo;
1675   } else {
1676     N->dump();
1677     assert(0 && "Unknown node in result pattern!");
1678     return ~0U;
1679   }
1680 }
1681
1682 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1683 /// type information from it.
1684 static void RemoveAllTypes(TreePatternNode *N) {
1685   N->setType(MVT::isUnknown);
1686   if (!N->isLeaf())
1687     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1688       RemoveAllTypes(N->getChild(i));
1689 }
1690
1691 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1692 /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
1693 /// 'Pat' may be missing types.  If we find an unresolved type to add a check
1694 /// for, this returns true otherwise false if Pat has all types.
1695 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1696                                const std::string &Prefix, unsigned PatternNo,
1697                                std::ostream &OS) {
1698   // Did we find one?
1699   if (!Pat->hasTypeSet()) {
1700     // Move a type over from 'other' to 'pat'.
1701     Pat->setType(Other->getType());
1702     OS << "      if (" << Prefix << ".getValueType() != MVT::"
1703        << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1704     return true;
1705   } else if (Pat->isLeaf()) {
1706     return false;
1707   }
1708   
1709   for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1710     if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1711                            Prefix + utostr(i), PatternNo, OS))
1712       return true;
1713   return false;
1714 }
1715
1716 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1717 /// stream to match the pattern, and generate the code for the match if it
1718 /// succeeds.
1719 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1720                                         std::ostream &OS) {
1721   static unsigned PatternCount = 0;
1722   unsigned PatternNo = PatternCount++;
1723   OS << "    { // Pattern #" << PatternNo << ": ";
1724   Pattern.first->print(OS);
1725   OS << "\n      // Emits: ";
1726   Pattern.second->print(OS);
1727   OS << "\n";
1728   OS << "      // Pattern complexity = " << getPatternSize(Pattern.first)
1729      << "  cost = " << getResultPatternCost(Pattern.second) << "\n";
1730
1731   // Emit the matcher, capturing named arguments in VariableMap.
1732   std::map<std::string,std::string> VariableMap;
1733   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1734   
1735   // TP - Get *SOME* tree pattern, we don't care which.
1736   TreePattern &TP = *PatternFragments.begin()->second;
1737   
1738   // At this point, we know that we structurally match the pattern, but the
1739   // types of the nodes may not match.  Figure out the fewest number of type 
1740   // comparisons we need to emit.  For example, if there is only one integer
1741   // type supported by a target, there should be no type comparisons at all for
1742   // integer patterns!
1743   //
1744   // To figure out the fewest number of type checks needed, clone the pattern,
1745   // remove the types, then perform type inference on the pattern as a whole.
1746   // If there are unresolved types, emit an explicit check for those types,
1747   // apply the type to the tree, then rerun type inference.  Iterate until all
1748   // types are resolved.
1749   //
1750   TreePatternNode *Pat = Pattern.first->clone();
1751   RemoveAllTypes(Pat);
1752   
1753   do {
1754     // Resolve/propagate as many types as possible.
1755     try {
1756       bool MadeChange = true;
1757       while (MadeChange)
1758         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1759     } catch (...) {
1760       assert(0 && "Error: could not find consistent types for something we"
1761              " already decided was ok!");
1762       abort();
1763     }
1764
1765     // Insert a check for an unresolved type and add it to the tree.  If we find
1766     // an unresolved type to add a check for, this returns true and we iterate,
1767     // otherwise we are done.
1768   } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1769   
1770   unsigned TmpNo = 0;
1771   CodeGenPatternResult(Pattern.second, TmpNo,
1772                        VariableMap, OS, true /*the root*/);
1773   delete Pat;
1774   
1775   OS << "    }\n  P" << PatternNo << "Fail:\n";
1776 }
1777
1778
1779 namespace {
1780   /// CompareByRecordName - An ordering predicate that implements less-than by
1781   /// comparing the names records.
1782   struct CompareByRecordName {
1783     bool operator()(const Record *LHS, const Record *RHS) const {
1784       // Sort by name first.
1785       if (LHS->getName() < RHS->getName()) return true;
1786       // If both names are equal, sort by pointer.
1787       return LHS->getName() == RHS->getName() && LHS < RHS;
1788     }
1789   };
1790 }
1791
1792 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1793   std::string InstNS = Target.inst_begin()->second.Namespace;
1794   if (!InstNS.empty()) InstNS += "::";
1795   
1796   // Emit boilerplate.
1797   OS << "// The main instruction selector code.\n"
1798      << "SDOperand SelectCode(SDOperand N) {\n"
1799      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1800      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1801      << "INSTRUCTION_LIST_END))\n"
1802      << "    return N;   // Already selected.\n\n"
1803      << "  if (!N.Val->hasOneUse()) {\n"
1804   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1805      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1806      << "  }\n"
1807      << "  switch (N.getOpcode()) {\n"
1808      << "  default: break;\n"
1809      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1810      << "    return N;\n"
1811      << "  case ISD::AssertSext:\n"
1812      << "  case ISD::AssertZext: {\n"
1813      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
1814      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1815      << "    return Tmp0;\n"
1816      << "  }\n";
1817     
1818   // Group the patterns by their top-level opcodes.
1819   std::map<Record*, std::vector<PatternToMatch*>,
1820            CompareByRecordName> PatternsByOpcode;
1821   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1822     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1823       .push_back(&PatternsToMatch[i]);
1824   
1825   // Loop over all of the case statements.
1826   for (std::map<Record*, std::vector<PatternToMatch*>,
1827                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1828        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1829     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1830     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1831     
1832     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1833
1834     // We want to emit all of the matching code now.  However, we want to emit
1835     // the matches in order of minimal cost.  Sort the patterns so the least
1836     // cost one is at the start.
1837     std::stable_sort(Patterns.begin(), Patterns.end(),
1838                      PatternSortingPredicate());
1839     
1840     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1841       EmitCodeForPattern(*Patterns[i], OS);
1842     OS << "    break;\n\n";
1843   }
1844   
1845
1846   OS << "  } // end of big switch.\n\n"
1847      << "  std::cerr << \"Cannot yet select: \";\n"
1848      << "  N.Val->dump();\n"
1849      << "  std::cerr << '\\n';\n"
1850      << "  abort();\n"
1851      << "}\n";
1852 }
1853
1854 void DAGISelEmitter::run(std::ostream &OS) {
1855   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1856                        " target", OS);
1857   
1858   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1859      << "// *** instruction selector class.  These functions are really "
1860      << "methods.\n\n";
1861   
1862   OS << "// Instance var to keep track of multiply used nodes that have \n"
1863      << "// already been selected.\n"
1864      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1865   
1866   ParseNodeInfo();
1867   ParseNodeTransforms(OS);
1868   ParsePatternFragments(OS);
1869   ParseInstructions();
1870   ParsePatterns();
1871   
1872   // Generate variants.  For example, commutative patterns can match
1873   // multiple ways.  Add them to PatternsToMatch as well.
1874   GenerateVariants();
1875
1876   
1877   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1878         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1879           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
1880           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
1881           std::cerr << "\n";
1882         });
1883   
1884   // At this point, we have full information about the 'Patterns' we need to
1885   // parse, both implicitly from instructions as well as from explicit pattern
1886   // definitions.  Emit the resultant instruction selector.
1887   EmitInstructionSelector(OS);  
1888   
1889   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1890        E = PatternFragments.end(); I != E; ++I)
1891     delete I->second;
1892   PatternFragments.clear();
1893
1894   Instructions.clear();
1895 }