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