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