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