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