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