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