Use the 'MadeChange' variable instead of returning 'false' all of the time.
[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 /// SubstituteFormalArguments - Replace the formal arguments in this tree
678 /// with actual values specified by ArgMap.
679 void TreePatternNode::
680 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
681   if (isLeaf()) return;
682   
683   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
684     TreePatternNode *Child = getChild(i);
685     if (Child->isLeaf()) {
686       Init *Val = Child->getLeafValue();
687       if (dynamic_cast<DefInit*>(Val) &&
688           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
689         // We found a use of a formal argument, replace it with its value.
690         TreePatternNode *NewChild = ArgMap[Child->getName()];
691         assert(NewChild && "Couldn't find formal argument!");
692         assert((Child->getPredicateFns().empty() ||
693                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
694                "Non-empty child predicate clobbered!");
695         setChild(i, NewChild);
696       }
697     } else {
698       getChild(i)->SubstituteFormalArguments(ArgMap);
699     }
700   }
701 }
702
703
704 /// InlinePatternFragments - If this pattern refers to any pattern
705 /// fragments, inline them into place, giving us a pattern without any
706 /// PatFrag references.
707 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
708   if (isLeaf()) return this;  // nothing to do.
709   Record *Op = getOperator();
710   
711   if (!Op->isSubClassOf("PatFrag")) {
712     // Just recursively inline children nodes.
713     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
714       TreePatternNode *Child = getChild(i);
715       TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
716
717       assert((Child->getPredicateFns().empty() ||
718               NewChild->getPredicateFns() == Child->getPredicateFns()) &&
719              "Non-empty child predicate clobbered!");
720
721       setChild(i, NewChild);
722     }
723     return this;
724   }
725
726   // Otherwise, we found a reference to a fragment.  First, look up its
727   // TreePattern record.
728   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
729   
730   // Verify that we are passing the right number of operands.
731   if (Frag->getNumArgs() != Children.size())
732     TP.error("'" + Op->getName() + "' fragment requires " +
733              utostr(Frag->getNumArgs()) + " operands!");
734
735   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
736
737   std::string Code = Op->getValueAsCode("Predicate");
738   if (!Code.empty())
739     FragTree->addPredicateFn("Predicate_"+Op->getName());
740
741   // Resolve formal arguments to their actual value.
742   if (Frag->getNumArgs()) {
743     // Compute the map of formal to actual arguments.
744     std::map<std::string, TreePatternNode*> ArgMap;
745     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
746       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
747   
748     FragTree->SubstituteFormalArguments(ArgMap);
749   }
750   
751   FragTree->setName(getName());
752   FragTree->UpdateNodeType(getExtTypes(), TP);
753
754   // Transfer in the old predicates.
755   for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
756     FragTree->addPredicateFn(getPredicateFns()[i]);
757
758   // Get a new copy of this fragment to stitch into here.
759   //delete this;    // FIXME: implement refcounting!
760   
761   // The fragment we inlined could have recursive inlining that is needed.  See
762   // if there are any pattern fragments in it and inline them as needed.
763   return FragTree->InlinePatternFragments(TP);
764 }
765
766 /// getImplicitType - Check to see if the specified record has an implicit
767 /// type which should be applied to it.  This will infer the type of register
768 /// references from the register file information, for example.
769 ///
770 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
771                                       TreePattern &TP) {
772   // Some common return values
773   std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
774   std::vector<unsigned char> Other(1, MVT::Other);
775
776   // Check to see if this is a register or a register class...
777   if (R->isSubClassOf("RegisterClass")) {
778     if (NotRegisters) 
779       return Unknown;
780     const CodeGenRegisterClass &RC = 
781       TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
782     return ConvertVTs(RC.getValueTypes());
783   } else if (R->isSubClassOf("PatFrag")) {
784     // Pattern fragment types will be resolved when they are inlined.
785     return Unknown;
786   } else if (R->isSubClassOf("Register")) {
787     if (NotRegisters) 
788       return Unknown;
789     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
790     return T.getRegisterVTs(R);
791   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
792     // Using a VTSDNode or CondCodeSDNode.
793     return Other;
794   } else if (R->isSubClassOf("ComplexPattern")) {
795     if (NotRegisters) 
796       return Unknown;
797     std::vector<unsigned char>
798     ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
799     return ComplexPat;
800   } else if (R->isSubClassOf("PointerLikeRegClass")) {
801     Other[0] = MVT::iPTR;
802     return Other;
803   } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
804              R->getName() == "zero_reg") {
805     // Placeholder.
806     return Unknown;
807   }
808   
809   TP.error("Unknown node flavor used in pattern: " + R->getName());
810   return Other;
811 }
812
813
814 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
815 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
816 const CodeGenIntrinsic *TreePatternNode::
817 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
818   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
819       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
820       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
821     return 0;
822     
823   unsigned IID = 
824     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
825   return &CDP.getIntrinsicInfo(IID);
826 }
827
828 /// isCommutativeIntrinsic - Return true if the node corresponds to a
829 /// commutative intrinsic.
830 bool
831 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
832   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
833     return Int->isCommutative;
834   return false;
835 }
836
837
838 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
839 /// this node and its children in the tree.  This returns true if it makes a
840 /// change, false otherwise.  If a type contradiction is found, throw an
841 /// exception.
842 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
843   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
844   if (isLeaf()) {
845     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
846       // If it's a regclass or something else known, include the type.
847       return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
848     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
849       // Int inits are always integers. :)
850       bool MadeChange = UpdateNodeType(MVT::iAny, TP);
851       
852       if (hasTypeSet()) {
853         // At some point, it may make sense for this tree pattern to have
854         // multiple types.  Assert here that it does not, so we revisit this
855         // code when appropriate.
856         assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
857         MVT::SimpleValueType VT = getTypeNum(0);
858         for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
859           assert(getTypeNum(i) == VT && "TreePattern has too many types!");
860         
861         VT = getTypeNum(0);
862         if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
863           unsigned Size = EVT(VT).getSizeInBits();
864           // Make sure that the value is representable for this type.
865           if (Size < 32) {
866             int Val = (II->getValue() << (32-Size)) >> (32-Size);
867             if (Val != II->getValue()) {
868               // If sign-extended doesn't fit, does it fit as unsigned?
869               unsigned ValueMask;
870               unsigned UnsignedVal;
871               ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
872               UnsignedVal = unsigned(II->getValue());
873
874               if ((ValueMask & UnsignedVal) != UnsignedVal) {
875                 TP.error("Integer value '" + itostr(II->getValue())+
876                          "' is out of range for type '" + 
877                          getEnumName(getTypeNum(0)) + "'!");
878               }
879             }
880           }
881         }
882       }
883       
884       return MadeChange;
885     }
886     return false;
887   }
888   
889   // special handling for set, which isn't really an SDNode.
890   if (getOperator()->getName() == "set") {
891     assert (getNumChildren() >= 2 && "Missing RHS of a set?");
892     unsigned NC = getNumChildren();
893     bool MadeChange = false;
894     for (unsigned i = 0; i < NC-1; ++i) {
895       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
896       MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
897     
898       // Types of operands must match.
899       MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
900                                                 TP);
901       MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
902                                                    TP);
903       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
904     }
905     return MadeChange;
906   } else if (getOperator()->getName() == "implicit" ||
907              getOperator()->getName() == "parallel") {
908     bool MadeChange = false;
909     for (unsigned i = 0; i < getNumChildren(); ++i)
910       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
911     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
912     return MadeChange;
913   } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
914     bool MadeChange = false;
915     MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
916     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
917     return MadeChange;
918   } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
919     bool MadeChange = false;
920
921     // Apply the result type to the node.
922     unsigned NumRetVTs = Int->IS.RetVTs.size();
923     unsigned NumParamVTs = Int->IS.ParamVTs.size();
924
925     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
926       MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
927
928     if (getNumChildren() != NumParamVTs + NumRetVTs)
929       TP.error("Intrinsic '" + Int->Name + "' expects " +
930                utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
931                utostr(getNumChildren() - 1) + " operands!");
932
933     // Apply type info to the intrinsic ID.
934     MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
935     
936     for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
937       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
938       MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
939       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
940     }
941     return MadeChange;
942   } else if (getOperator()->isSubClassOf("SDNode")) {
943     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
944     
945     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
946     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
947       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
948     // Branch, etc. do not produce results and top-level forms in instr pattern
949     // must have void types.
950     if (NI.getNumResults() == 0)
951       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
952     
953     return MadeChange;  
954   } else if (getOperator()->isSubClassOf("Instruction")) {
955     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
956     bool MadeChange = false;
957     unsigned NumResults = Inst.getNumResults();
958     
959     assert(NumResults <= 1 &&
960            "Only supports zero or one result instrs!");
961
962     CodeGenInstruction &InstInfo =
963       CDP.getTargetInfo().getInstruction(getOperator()->getName());
964     // Apply the result type to the node
965     if (NumResults == 0 || InstInfo.NumDefs == 0) {
966       MadeChange = UpdateNodeType(MVT::isVoid, TP);
967     } else {
968       Record *ResultNode = Inst.getResult(0);
969       
970       if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
971         std::vector<unsigned char> VT;
972         VT.push_back(MVT::iPTR);
973         MadeChange = UpdateNodeType(VT, TP);
974       } else if (ResultNode->getName() == "unknown") {
975         std::vector<unsigned char> VT;
976         VT.push_back(EEVT::isUnknown);
977         MadeChange = UpdateNodeType(VT, TP);
978       } else {
979         assert(ResultNode->isSubClassOf("RegisterClass") &&
980                "Operands should be register classes!");
981
982         const CodeGenRegisterClass &RC = 
983           CDP.getTargetInfo().getRegisterClass(ResultNode);
984         MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
985       }
986     }
987
988     unsigned ChildNo = 0;
989     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
990       Record *OperandNode = Inst.getOperand(i);
991       
992       // If the instruction expects a predicate or optional def operand, we
993       // codegen this by setting the operand to it's default value if it has a
994       // non-empty DefaultOps field.
995       if ((OperandNode->isSubClassOf("PredicateOperand") ||
996            OperandNode->isSubClassOf("OptionalDefOperand")) &&
997           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
998         continue;
999        
1000       // Verify that we didn't run out of provided operands.
1001       if (ChildNo >= getNumChildren())
1002         TP.error("Instruction '" + getOperator()->getName() +
1003                  "' expects more operands than were provided.");
1004       
1005       MVT::SimpleValueType VT;
1006       TreePatternNode *Child = getChild(ChildNo++);
1007       if (OperandNode->isSubClassOf("RegisterClass")) {
1008         const CodeGenRegisterClass &RC = 
1009           CDP.getTargetInfo().getRegisterClass(OperandNode);
1010         MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1011       } else if (OperandNode->isSubClassOf("Operand")) {
1012         VT = getValueType(OperandNode->getValueAsDef("Type"));
1013         MadeChange |= Child->UpdateNodeType(VT, TP);
1014       } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1015         MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1016       } else if (OperandNode->getName() == "unknown") {
1017         MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
1018       } else {
1019         assert(0 && "Unknown operand type!");
1020         abort();
1021       }
1022       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1023     }
1024
1025     if (ChildNo != getNumChildren())
1026       TP.error("Instruction '" + getOperator()->getName() +
1027                "' was provided too many operands!");
1028     
1029     return MadeChange;
1030   } else {
1031     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1032     
1033     // Node transforms always take one operand.
1034     if (getNumChildren() != 1)
1035       TP.error("Node transform '" + getOperator()->getName() +
1036                "' requires one operand!");
1037
1038     // If either the output or input of the xform does not have exact
1039     // type info. We assume they must be the same. Otherwise, it is perfectly
1040     // legal to transform from one type to a completely different type.
1041     if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1042       bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1043       MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1044       return MadeChange;
1045     }
1046     return false;
1047   }
1048 }
1049
1050 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1051 /// RHS of a commutative operation, not the on LHS.
1052 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1053   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1054     return true;
1055   if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1056     return true;
1057   return false;
1058 }
1059
1060
1061 /// canPatternMatch - If it is impossible for this pattern to match on this
1062 /// target, fill in Reason and return false.  Otherwise, return true.  This is
1063 /// used as a sanity check for .td files (to prevent people from writing stuff
1064 /// that can never possibly work), and to prevent the pattern permuter from
1065 /// generating stuff that is useless.
1066 bool TreePatternNode::canPatternMatch(std::string &Reason, 
1067                                       const CodeGenDAGPatterns &CDP) {
1068   if (isLeaf()) return true;
1069
1070   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1071     if (!getChild(i)->canPatternMatch(Reason, CDP))
1072       return false;
1073
1074   // If this is an intrinsic, handle cases that would make it not match.  For
1075   // example, if an operand is required to be an immediate.
1076   if (getOperator()->isSubClassOf("Intrinsic")) {
1077     // TODO:
1078     return true;
1079   }
1080   
1081   // If this node is a commutative operator, check that the LHS isn't an
1082   // immediate.
1083   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1084   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1085   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1086     // Scan all of the operands of the node and make sure that only the last one
1087     // is a constant node, unless the RHS also is.
1088     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1089       bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1090       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1091         if (OnlyOnRHSOfCommutative(getChild(i))) {
1092           Reason="Immediate value must be on the RHS of commutative operators!";
1093           return false;
1094         }
1095     }
1096   }
1097   
1098   return true;
1099 }
1100
1101 //===----------------------------------------------------------------------===//
1102 // TreePattern implementation
1103 //
1104
1105 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1106                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1107    isInputPattern = isInput;
1108    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1109      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1110 }
1111
1112 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1113                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1114   isInputPattern = isInput;
1115   Trees.push_back(ParseTreePattern(Pat));
1116 }
1117
1118 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1119                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1120   isInputPattern = isInput;
1121   Trees.push_back(Pat);
1122 }
1123
1124
1125
1126 void TreePattern::error(const std::string &Msg) const {
1127   dump();
1128   throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1129 }
1130
1131 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1132   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1133   if (!OpDef) error("Pattern has unexpected operator type!");
1134   Record *Operator = OpDef->getDef();
1135   
1136   if (Operator->isSubClassOf("ValueType")) {
1137     // If the operator is a ValueType, then this must be "type cast" of a leaf
1138     // node.
1139     if (Dag->getNumArgs() != 1)
1140       error("Type cast only takes one operand!");
1141     
1142     Init *Arg = Dag->getArg(0);
1143     TreePatternNode *New;
1144     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1145       Record *R = DI->getDef();
1146       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1147         Dag->setArg(0, new DagInit(DI, "",
1148                                 std::vector<std::pair<Init*, std::string> >()));
1149         return ParseTreePattern(Dag);
1150       }
1151       New = new TreePatternNode(DI);
1152     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1153       New = ParseTreePattern(DI);
1154     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1155       New = new TreePatternNode(II);
1156       if (!Dag->getArgName(0).empty())
1157         error("Constant int argument should not have a name!");
1158     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1159       // Turn this into an IntInit.
1160       Init *II = BI->convertInitializerTo(new IntRecTy());
1161       if (II == 0 || !dynamic_cast<IntInit*>(II))
1162         error("Bits value must be constants!");
1163       
1164       New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1165       if (!Dag->getArgName(0).empty())
1166         error("Constant int argument should not have a name!");
1167     } else {
1168       Arg->dump();
1169       error("Unknown leaf value for tree pattern!");
1170       return 0;
1171     }
1172     
1173     // Apply the type cast.
1174     New->UpdateNodeType(getValueType(Operator), *this);
1175     if (New->getNumChildren() == 0)
1176       New->setName(Dag->getArgName(0));
1177     return New;
1178   }
1179   
1180   // Verify that this is something that makes sense for an operator.
1181   if (!Operator->isSubClassOf("PatFrag") && 
1182       !Operator->isSubClassOf("SDNode") &&
1183       !Operator->isSubClassOf("Instruction") && 
1184       !Operator->isSubClassOf("SDNodeXForm") &&
1185       !Operator->isSubClassOf("Intrinsic") &&
1186       Operator->getName() != "set" &&
1187       Operator->getName() != "implicit" &&
1188       Operator->getName() != "parallel")
1189     error("Unrecognized node '" + Operator->getName() + "'!");
1190   
1191   //  Check to see if this is something that is illegal in an input pattern.
1192   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1193                          Operator->isSubClassOf("SDNodeXForm")))
1194     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1195   
1196   std::vector<TreePatternNode*> Children;
1197   
1198   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1199     Init *Arg = Dag->getArg(i);
1200     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1201       Children.push_back(ParseTreePattern(DI));
1202       if (Children.back()->getName().empty())
1203         Children.back()->setName(Dag->getArgName(i));
1204     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1205       Record *R = DefI->getDef();
1206       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
1207       // TreePatternNode if its own.
1208       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1209         Dag->setArg(i, new DagInit(DefI, "",
1210                               std::vector<std::pair<Init*, std::string> >()));
1211         --i;  // Revisit this node...
1212       } else {
1213         TreePatternNode *Node = new TreePatternNode(DefI);
1214         Node->setName(Dag->getArgName(i));
1215         Children.push_back(Node);
1216         
1217         // Input argument?
1218         if (R->getName() == "node") {
1219           if (Dag->getArgName(i).empty())
1220             error("'node' argument requires a name to match with operand list");
1221           Args.push_back(Dag->getArgName(i));
1222         }
1223       }
1224     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1225       TreePatternNode *Node = new TreePatternNode(II);
1226       if (!Dag->getArgName(i).empty())
1227         error("Constant int argument should not have a name!");
1228       Children.push_back(Node);
1229     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1230       // Turn this into an IntInit.
1231       Init *II = BI->convertInitializerTo(new IntRecTy());
1232       if (II == 0 || !dynamic_cast<IntInit*>(II))
1233         error("Bits value must be constants!");
1234       
1235       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1236       if (!Dag->getArgName(i).empty())
1237         error("Constant int argument should not have a name!");
1238       Children.push_back(Node);
1239     } else {
1240       errs() << '"';
1241       Arg->dump();
1242       errs() << "\": ";
1243       error("Unknown leaf value for tree pattern!");
1244     }
1245   }
1246   
1247   // If the operator is an intrinsic, then this is just syntactic sugar for for
1248   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
1249   // convert the intrinsic name to a number.
1250   if (Operator->isSubClassOf("Intrinsic")) {
1251     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1252     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1253
1254     // If this intrinsic returns void, it must have side-effects and thus a
1255     // chain.
1256     if (Int.IS.RetVTs[0] == MVT::isVoid) {
1257       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1258     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1259       // Has side-effects, requires chain.
1260       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1261     } else {
1262       // Otherwise, no chain.
1263       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1264     }
1265     
1266     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1267     Children.insert(Children.begin(), IIDNode);
1268   }
1269   
1270   TreePatternNode *Result = new TreePatternNode(Operator, Children);
1271   Result->setName(Dag->getName());
1272   return Result;
1273 }
1274
1275 /// InferAllTypes - Infer/propagate as many types throughout the expression
1276 /// patterns as possible.  Return true if all types are inferred, false
1277 /// otherwise.  Throw an exception if a type contradiction is found.
1278 bool TreePattern::InferAllTypes() {
1279   bool MadeChange = true;
1280   while (MadeChange) {
1281     MadeChange = false;
1282     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1283       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1284   }
1285   
1286   bool HasUnresolvedTypes = false;
1287   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1288     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1289   return !HasUnresolvedTypes;
1290 }
1291
1292 void TreePattern::print(raw_ostream &OS) const {
1293   OS << getRecord()->getName();
1294   if (!Args.empty()) {
1295     OS << "(" << Args[0];
1296     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1297       OS << ", " << Args[i];
1298     OS << ")";
1299   }
1300   OS << ": ";
1301   
1302   if (Trees.size() > 1)
1303     OS << "[\n";
1304   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1305     OS << "\t";
1306     Trees[i]->print(OS);
1307     OS << "\n";
1308   }
1309
1310   if (Trees.size() > 1)
1311     OS << "]\n";
1312 }
1313
1314 void TreePattern::dump() const { print(errs()); }
1315
1316 //===----------------------------------------------------------------------===//
1317 // CodeGenDAGPatterns implementation
1318 //
1319
1320 // FIXME: REMOVE OSTREAM ARGUMENT
1321 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1322   Intrinsics = LoadIntrinsics(Records, false);
1323   TgtIntrinsics = LoadIntrinsics(Records, true);
1324   ParseNodeInfo();
1325   ParseNodeTransforms();
1326   ParseComplexPatterns();
1327   ParsePatternFragments();
1328   ParseDefaultOperands();
1329   ParseInstructions();
1330   ParsePatterns();
1331   
1332   // Generate variants.  For example, commutative patterns can match
1333   // multiple ways.  Add them to PatternsToMatch as well.
1334   GenerateVariants();
1335
1336   // Infer instruction flags.  For example, we can detect loads,
1337   // stores, and side effects in many cases by examining an
1338   // instruction's pattern.
1339   InferInstructionFlags();
1340 }
1341
1342 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1343   for (pf_iterator I = PatternFragments.begin(),
1344        E = PatternFragments.end(); I != E; ++I)
1345     delete I->second;
1346 }
1347
1348
1349 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1350   Record *N = Records.getDef(Name);
1351   if (!N || !N->isSubClassOf("SDNode")) {
1352     errs() << "Error getting SDNode '" << Name << "'!\n";
1353     exit(1);
1354   }
1355   return N;
1356 }
1357
1358 // Parse all of the SDNode definitions for the target, populating SDNodes.
1359 void CodeGenDAGPatterns::ParseNodeInfo() {
1360   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1361   while (!Nodes.empty()) {
1362     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1363     Nodes.pop_back();
1364   }
1365
1366   // Get the builtin intrinsic nodes.
1367   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1368   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1369   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1370 }
1371
1372 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1373 /// map, and emit them to the file as functions.
1374 void CodeGenDAGPatterns::ParseNodeTransforms() {
1375   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1376   while (!Xforms.empty()) {
1377     Record *XFormNode = Xforms.back();
1378     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1379     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1380     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1381
1382     Xforms.pop_back();
1383   }
1384 }
1385
1386 void CodeGenDAGPatterns::ParseComplexPatterns() {
1387   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1388   while (!AMs.empty()) {
1389     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1390     AMs.pop_back();
1391   }
1392 }
1393
1394
1395 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1396 /// file, building up the PatternFragments map.  After we've collected them all,
1397 /// inline fragments together as necessary, so that there are no references left
1398 /// inside a pattern fragment to a pattern fragment.
1399 ///
1400 void CodeGenDAGPatterns::ParsePatternFragments() {
1401   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1402   
1403   // First step, parse all of the fragments.
1404   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1405     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1406     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1407     PatternFragments[Fragments[i]] = P;
1408     
1409     // Validate the argument list, converting it to set, to discard duplicates.
1410     std::vector<std::string> &Args = P->getArgList();
1411     std::set<std::string> OperandsSet(Args.begin(), Args.end());
1412     
1413     if (OperandsSet.count(""))
1414       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1415     
1416     // Parse the operands list.
1417     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1418     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1419     // Special cases: ops == outs == ins. Different names are used to
1420     // improve readability.
1421     if (!OpsOp ||
1422         (OpsOp->getDef()->getName() != "ops" &&
1423          OpsOp->getDef()->getName() != "outs" &&
1424          OpsOp->getDef()->getName() != "ins"))
1425       P->error("Operands list should start with '(ops ... '!");
1426     
1427     // Copy over the arguments.       
1428     Args.clear();
1429     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1430       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1431           static_cast<DefInit*>(OpsList->getArg(j))->
1432           getDef()->getName() != "node")
1433         P->error("Operands list should all be 'node' values.");
1434       if (OpsList->getArgName(j).empty())
1435         P->error("Operands list should have names for each operand!");
1436       if (!OperandsSet.count(OpsList->getArgName(j)))
1437         P->error("'" + OpsList->getArgName(j) +
1438                  "' does not occur in pattern or was multiply specified!");
1439       OperandsSet.erase(OpsList->getArgName(j));
1440       Args.push_back(OpsList->getArgName(j));
1441     }
1442     
1443     if (!OperandsSet.empty())
1444       P->error("Operands list does not contain an entry for operand '" +
1445                *OperandsSet.begin() + "'!");
1446
1447     // If there is a code init for this fragment, keep track of the fact that
1448     // this fragment uses it.
1449     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1450     if (!Code.empty())
1451       P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1452     
1453     // If there is a node transformation corresponding to this, keep track of
1454     // it.
1455     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1456     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1457       P->getOnlyTree()->setTransformFn(Transform);
1458   }
1459   
1460   // Now that we've parsed all of the tree fragments, do a closure on them so
1461   // that there are not references to PatFrags left inside of them.
1462   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1463     TreePattern *ThePat = PatternFragments[Fragments[i]];
1464     ThePat->InlinePatternFragments();
1465         
1466     // Infer as many types as possible.  Don't worry about it if we don't infer
1467     // all of them, some may depend on the inputs of the pattern.
1468     try {
1469       ThePat->InferAllTypes();
1470     } catch (...) {
1471       // If this pattern fragment is not supported by this target (no types can
1472       // satisfy its constraints), just ignore it.  If the bogus pattern is
1473       // actually used by instructions, the type consistency error will be
1474       // reported there.
1475     }
1476     
1477     // If debugging, print out the pattern fragment result.
1478     DEBUG(ThePat->dump());
1479   }
1480 }
1481
1482 void CodeGenDAGPatterns::ParseDefaultOperands() {
1483   std::vector<Record*> DefaultOps[2];
1484   DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1485   DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1486
1487   // Find some SDNode.
1488   assert(!SDNodes.empty() && "No SDNodes parsed?");
1489   Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1490   
1491   for (unsigned iter = 0; iter != 2; ++iter) {
1492     for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1493       DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1494     
1495       // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1496       // SomeSDnode so that we can parse this.
1497       std::vector<std::pair<Init*, std::string> > Ops;
1498       for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1499         Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1500                                      DefaultInfo->getArgName(op)));
1501       DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1502     
1503       // Create a TreePattern to parse this.
1504       TreePattern P(DefaultOps[iter][i], DI, false, *this);
1505       assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1506
1507       // Copy the operands over into a DAGDefaultOperand.
1508       DAGDefaultOperand DefaultOpInfo;
1509     
1510       TreePatternNode *T = P.getTree(0);
1511       for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1512         TreePatternNode *TPN = T->getChild(op);
1513         while (TPN->ApplyTypeConstraints(P, false))
1514           /* Resolve all types */;
1515       
1516         if (TPN->ContainsUnresolvedType()) {
1517           if (iter == 0)
1518             throw "Value #" + utostr(i) + " of PredicateOperand '" +
1519               DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1520           else
1521             throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1522               DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1523         }
1524         DefaultOpInfo.DefaultOps.push_back(TPN);
1525       }
1526
1527       // Insert it into the DefaultOperands map so we can find it later.
1528       DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1529     }
1530   }
1531 }
1532
1533 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1534 /// instruction input.  Return true if this is a real use.
1535 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1536                       std::map<std::string, TreePatternNode*> &InstInputs,
1537                       std::vector<Record*> &InstImpInputs) {
1538   // No name -> not interesting.
1539   if (Pat->getName().empty()) {
1540     if (Pat->isLeaf()) {
1541       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1542       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1543         I->error("Input " + DI->getDef()->getName() + " must be named!");
1544       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1545         InstImpInputs.push_back(DI->getDef());
1546     }
1547     return false;
1548   }
1549
1550   Record *Rec;
1551   if (Pat->isLeaf()) {
1552     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1553     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1554     Rec = DI->getDef();
1555   } else {
1556     Rec = Pat->getOperator();
1557   }
1558
1559   // SRCVALUE nodes are ignored.
1560   if (Rec->getName() == "srcvalue")
1561     return false;
1562
1563   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1564   if (!Slot) {
1565     Slot = Pat;
1566   } else {
1567     Record *SlotRec;
1568     if (Slot->isLeaf()) {
1569       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1570     } else {
1571       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1572       SlotRec = Slot->getOperator();
1573     }
1574     
1575     // Ensure that the inputs agree if we've already seen this input.
1576     if (Rec != SlotRec)
1577       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1578     if (Slot->getExtTypes() != Pat->getExtTypes())
1579       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1580   }
1581   return true;
1582 }
1583
1584 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1585 /// part of "I", the instruction), computing the set of inputs and outputs of
1586 /// the pattern.  Report errors if we see anything naughty.
1587 void CodeGenDAGPatterns::
1588 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1589                             std::map<std::string, TreePatternNode*> &InstInputs,
1590                             std::map<std::string, TreePatternNode*>&InstResults,
1591                             std::vector<Record*> &InstImpInputs,
1592                             std::vector<Record*> &InstImpResults) {
1593   if (Pat->isLeaf()) {
1594     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1595     if (!isUse && Pat->getTransformFn())
1596       I->error("Cannot specify a transform function for a non-input value!");
1597     return;
1598   } else if (Pat->getOperator()->getName() == "implicit") {
1599     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1600       TreePatternNode *Dest = Pat->getChild(i);
1601       if (!Dest->isLeaf())
1602         I->error("implicitly defined value should be a register!");
1603     
1604       DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1605       if (!Val || !Val->getDef()->isSubClassOf("Register"))
1606         I->error("implicitly defined value should be a register!");
1607       InstImpResults.push_back(Val->getDef());
1608     }
1609     return;
1610   } else if (Pat->getOperator()->getName() != "set") {
1611     // If this is not a set, verify that the children nodes are not void typed,
1612     // and recurse.
1613     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1614       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1615         I->error("Cannot have void nodes inside of patterns!");
1616       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1617                                   InstImpInputs, InstImpResults);
1618     }
1619     
1620     // If this is a non-leaf node with no children, treat it basically as if
1621     // it were a leaf.  This handles nodes like (imm).
1622     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1623     
1624     if (!isUse && Pat->getTransformFn())
1625       I->error("Cannot specify a transform function for a non-input value!");
1626     return;
1627   } 
1628   
1629   // Otherwise, this is a set, validate and collect instruction results.
1630   if (Pat->getNumChildren() == 0)
1631     I->error("set requires operands!");
1632   
1633   if (Pat->getTransformFn())
1634     I->error("Cannot specify a transform function on a set node!");
1635   
1636   // Check the set destinations.
1637   unsigned NumDests = Pat->getNumChildren()-1;
1638   for (unsigned i = 0; i != NumDests; ++i) {
1639     TreePatternNode *Dest = Pat->getChild(i);
1640     if (!Dest->isLeaf())
1641       I->error("set destination should be a register!");
1642     
1643     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1644     if (!Val)
1645       I->error("set destination should be a register!");
1646
1647     if (Val->getDef()->isSubClassOf("RegisterClass") ||
1648         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1649       if (Dest->getName().empty())
1650         I->error("set destination must have a name!");
1651       if (InstResults.count(Dest->getName()))
1652         I->error("cannot set '" + Dest->getName() +"' multiple times");
1653       InstResults[Dest->getName()] = Dest;
1654     } else if (Val->getDef()->isSubClassOf("Register")) {
1655       InstImpResults.push_back(Val->getDef());
1656     } else {
1657       I->error("set destination should be a register!");
1658     }
1659   }
1660     
1661   // Verify and collect info from the computation.
1662   FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1663                               InstInputs, InstResults,
1664                               InstImpInputs, InstImpResults);
1665 }
1666
1667 //===----------------------------------------------------------------------===//
1668 // Instruction Analysis
1669 //===----------------------------------------------------------------------===//
1670
1671 class InstAnalyzer {
1672   const CodeGenDAGPatterns &CDP;
1673   bool &mayStore;
1674   bool &mayLoad;
1675   bool &HasSideEffects;
1676 public:
1677   InstAnalyzer(const CodeGenDAGPatterns &cdp,
1678                bool &maystore, bool &mayload, bool &hse)
1679     : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1680   }
1681
1682   /// Analyze - Analyze the specified instruction, returning true if the
1683   /// instruction had a pattern.
1684   bool Analyze(Record *InstRecord) {
1685     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1686     if (Pattern == 0) {
1687       HasSideEffects = 1;
1688       return false;  // No pattern.
1689     }
1690
1691     // FIXME: Assume only the first tree is the pattern. The others are clobber
1692     // nodes.
1693     AnalyzeNode(Pattern->getTree(0));
1694     return true;
1695   }
1696
1697 private:
1698   void AnalyzeNode(const TreePatternNode *N) {
1699     if (N->isLeaf()) {
1700       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1701         Record *LeafRec = DI->getDef();
1702         // Handle ComplexPattern leaves.
1703         if (LeafRec->isSubClassOf("ComplexPattern")) {
1704           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1705           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1706           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1707           if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1708         }
1709       }
1710       return;
1711     }
1712
1713     // Analyze children.
1714     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1715       AnalyzeNode(N->getChild(i));
1716
1717     // Ignore set nodes, which are not SDNodes.
1718     if (N->getOperator()->getName() == "set")
1719       return;
1720
1721     // Get information about the SDNode for the operator.
1722     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1723
1724     // Notice properties of the node.
1725     if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1726     if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1727     if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1728
1729     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1730       // If this is an intrinsic, analyze it.
1731       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1732         mayLoad = true;// These may load memory.
1733
1734       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1735         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1736
1737       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1738         // WriteMem intrinsics can have other strange effects.
1739         HasSideEffects = true;
1740     }
1741   }
1742
1743 };
1744
1745 static void InferFromPattern(const CodeGenInstruction &Inst,
1746                              bool &MayStore, bool &MayLoad,
1747                              bool &HasSideEffects,
1748                              const CodeGenDAGPatterns &CDP) {
1749   MayStore = MayLoad = HasSideEffects = false;
1750
1751   bool HadPattern =
1752     InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1753
1754   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1755   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
1756     // If we decided that this is a store from the pattern, then the .td file
1757     // entry is redundant.
1758     if (MayStore)
1759       fprintf(stderr,
1760               "Warning: mayStore flag explicitly set on instruction '%s'"
1761               " but flag already inferred from pattern.\n",
1762               Inst.TheDef->getName().c_str());
1763     MayStore = true;
1764   }
1765
1766   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
1767     // If we decided that this is a load from the pattern, then the .td file
1768     // entry is redundant.
1769     if (MayLoad)
1770       fprintf(stderr,
1771               "Warning: mayLoad flag explicitly set on instruction '%s'"
1772               " but flag already inferred from pattern.\n",
1773               Inst.TheDef->getName().c_str());
1774     MayLoad = true;
1775   }
1776
1777   if (Inst.neverHasSideEffects) {
1778     if (HadPattern)
1779       fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1780               "which already has a pattern\n", Inst.TheDef->getName().c_str());
1781     HasSideEffects = false;
1782   }
1783
1784   if (Inst.hasSideEffects) {
1785     if (HasSideEffects)
1786       fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1787               "which already inferred this.\n", Inst.TheDef->getName().c_str());
1788     HasSideEffects = true;
1789   }
1790 }
1791
1792 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1793 /// any fragments involved.  This populates the Instructions list with fully
1794 /// resolved instructions.
1795 void CodeGenDAGPatterns::ParseInstructions() {
1796   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1797   
1798   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1799     ListInit *LI = 0;
1800     
1801     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1802       LI = Instrs[i]->getValueAsListInit("Pattern");
1803     
1804     // If there is no pattern, only collect minimal information about the
1805     // instruction for its operand list.  We have to assume that there is one
1806     // result, as we have no detailed info.
1807     if (!LI || LI->getSize() == 0) {
1808       std::vector<Record*> Results;
1809       std::vector<Record*> Operands;
1810       
1811       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1812
1813       if (InstInfo.OperandList.size() != 0) {
1814         if (InstInfo.NumDefs == 0) {
1815           // These produce no results
1816           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1817             Operands.push_back(InstInfo.OperandList[j].Rec);
1818         } else {
1819           // Assume the first operand is the result.
1820           Results.push_back(InstInfo.OperandList[0].Rec);
1821       
1822           // The rest are inputs.
1823           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1824             Operands.push_back(InstInfo.OperandList[j].Rec);
1825         }
1826       }
1827       
1828       // Create and insert the instruction.
1829       std::vector<Record*> ImpResults;
1830       std::vector<Record*> ImpOperands;
1831       Instructions.insert(std::make_pair(Instrs[i], 
1832                           DAGInstruction(0, Results, Operands, ImpResults,
1833                                          ImpOperands)));
1834       continue;  // no pattern.
1835     }
1836     
1837     // Parse the instruction.
1838     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1839     // Inline pattern fragments into it.
1840     I->InlinePatternFragments();
1841     
1842     // Infer as many types as possible.  If we cannot infer all of them, we can
1843     // never do anything with this instruction pattern: report it to the user.
1844     if (!I->InferAllTypes())
1845       I->error("Could not infer all types in pattern!");
1846     
1847     // InstInputs - Keep track of all of the inputs of the instruction, along 
1848     // with the record they are declared as.
1849     std::map<std::string, TreePatternNode*> InstInputs;
1850     
1851     // InstResults - Keep track of all the virtual registers that are 'set'
1852     // in the instruction, including what reg class they are.
1853     std::map<std::string, TreePatternNode*> InstResults;
1854
1855     std::vector<Record*> InstImpInputs;
1856     std::vector<Record*> InstImpResults;
1857     
1858     // Verify that the top-level forms in the instruction are of void type, and
1859     // fill in the InstResults map.
1860     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1861       TreePatternNode *Pat = I->getTree(j);
1862       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1863         I->error("Top-level forms in instruction pattern should have"
1864                  " void types");
1865
1866       // Find inputs and outputs, and verify the structure of the uses/defs.
1867       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1868                                   InstImpInputs, InstImpResults);
1869     }
1870
1871     // Now that we have inputs and outputs of the pattern, inspect the operands
1872     // list for the instruction.  This determines the order that operands are
1873     // added to the machine instruction the node corresponds to.
1874     unsigned NumResults = InstResults.size();
1875
1876     // Parse the operands list from the (ops) list, validating it.
1877     assert(I->getArgList().empty() && "Args list should still be empty here!");
1878     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1879
1880     // Check that all of the results occur first in the list.
1881     std::vector<Record*> Results;
1882     TreePatternNode *Res0Node = NULL;
1883     for (unsigned i = 0; i != NumResults; ++i) {
1884       if (i == CGI.OperandList.size())
1885         I->error("'" + InstResults.begin()->first +
1886                  "' set but does not appear in operand list!");
1887       const std::string &OpName = CGI.OperandList[i].Name;
1888       
1889       // Check that it exists in InstResults.
1890       TreePatternNode *RNode = InstResults[OpName];
1891       if (RNode == 0)
1892         I->error("Operand $" + OpName + " does not exist in operand list!");
1893         
1894       if (i == 0)
1895         Res0Node = RNode;
1896       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1897       if (R == 0)
1898         I->error("Operand $" + OpName + " should be a set destination: all "
1899                  "outputs must occur before inputs in operand list!");
1900       
1901       if (CGI.OperandList[i].Rec != R)
1902         I->error("Operand $" + OpName + " class mismatch!");
1903       
1904       // Remember the return type.
1905       Results.push_back(CGI.OperandList[i].Rec);
1906       
1907       // Okay, this one checks out.
1908       InstResults.erase(OpName);
1909     }
1910
1911     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1912     // the copy while we're checking the inputs.
1913     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1914
1915     std::vector<TreePatternNode*> ResultNodeOperands;
1916     std::vector<Record*> Operands;
1917     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1918       CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1919       const std::string &OpName = Op.Name;
1920       if (OpName.empty())
1921         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1922
1923       if (!InstInputsCheck.count(OpName)) {
1924         // If this is an predicate operand or optional def operand with an
1925         // DefaultOps set filled in, we can ignore this.  When we codegen it,
1926         // we will do so as always executed.
1927         if (Op.Rec->isSubClassOf("PredicateOperand") ||
1928             Op.Rec->isSubClassOf("OptionalDefOperand")) {
1929           // Does it have a non-empty DefaultOps field?  If so, ignore this
1930           // operand.
1931           if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1932             continue;
1933         }
1934         I->error("Operand $" + OpName +
1935                  " does not appear in the instruction pattern");
1936       }
1937       TreePatternNode *InVal = InstInputsCheck[OpName];
1938       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1939       
1940       if (InVal->isLeaf() &&
1941           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1942         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1943         if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1944           I->error("Operand $" + OpName + "'s register class disagrees"
1945                    " between the operand and pattern");
1946       }
1947       Operands.push_back(Op.Rec);
1948       
1949       // Construct the result for the dest-pattern operand list.
1950       TreePatternNode *OpNode = InVal->clone();
1951       
1952       // No predicate is useful on the result.
1953       OpNode->clearPredicateFns();
1954       
1955       // Promote the xform function to be an explicit node if set.
1956       if (Record *Xform = OpNode->getTransformFn()) {
1957         OpNode->setTransformFn(0);
1958         std::vector<TreePatternNode*> Children;
1959         Children.push_back(OpNode);
1960         OpNode = new TreePatternNode(Xform, Children);
1961       }
1962       
1963       ResultNodeOperands.push_back(OpNode);
1964     }
1965     
1966     if (!InstInputsCheck.empty())
1967       I->error("Input operand $" + InstInputsCheck.begin()->first +
1968                " occurs in pattern but not in operands list!");
1969
1970     TreePatternNode *ResultPattern =
1971       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1972     // Copy fully inferred output node type to instruction result pattern.
1973     if (NumResults > 0)
1974       ResultPattern->setTypes(Res0Node->getExtTypes());
1975
1976     // Create and insert the instruction.
1977     // FIXME: InstImpResults and InstImpInputs should not be part of
1978     // DAGInstruction.
1979     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1980     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1981
1982     // Use a temporary tree pattern to infer all types and make sure that the
1983     // constructed result is correct.  This depends on the instruction already
1984     // being inserted into the Instructions map.
1985     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1986     Temp.InferAllTypes();
1987
1988     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1989     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1990     
1991     DEBUG(I->dump());
1992   }
1993    
1994   // If we can, convert the instructions to be patterns that are matched!
1995   for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
1996         Instructions.begin(),
1997        E = Instructions.end(); II != E; ++II) {
1998     DAGInstruction &TheInst = II->second;
1999     const TreePattern *I = TheInst.getPattern();
2000     if (I == 0) continue;  // No pattern.
2001
2002     // FIXME: Assume only the first tree is the pattern. The others are clobber
2003     // nodes.
2004     TreePatternNode *Pattern = I->getTree(0);
2005     TreePatternNode *SrcPattern;
2006     if (Pattern->getOperator()->getName() == "set") {
2007       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2008     } else{
2009       // Not a set (store or something?)
2010       SrcPattern = Pattern;
2011     }
2012     
2013     std::string Reason;
2014     if (!SrcPattern->canPatternMatch(Reason, *this))
2015       I->error("Instruction can never match: " + Reason);
2016     
2017     Record *Instr = II->first;
2018     TreePatternNode *DstPattern = TheInst.getResultPattern();
2019     PatternsToMatch.
2020       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2021                                SrcPattern, DstPattern, TheInst.getImpResults(),
2022                                Instr->getValueAsInt("AddedComplexity")));
2023   }
2024 }
2025
2026
2027 void CodeGenDAGPatterns::InferInstructionFlags() {
2028   std::map<std::string, CodeGenInstruction> &InstrDescs =
2029     Target.getInstructions();
2030   for (std::map<std::string, CodeGenInstruction>::iterator
2031          II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2032     CodeGenInstruction &InstInfo = II->second;
2033     // Determine properties of the instruction from its pattern.
2034     bool MayStore, MayLoad, HasSideEffects;
2035     InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2036     InstInfo.mayStore = MayStore;
2037     InstInfo.mayLoad = MayLoad;
2038     InstInfo.hasSideEffects = HasSideEffects;
2039   }
2040 }
2041
2042 void CodeGenDAGPatterns::ParsePatterns() {
2043   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2044
2045   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2046     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2047     DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2048     Record *Operator = OpDef->getDef();
2049     TreePattern *Pattern;
2050     if (Operator->getName() != "parallel")
2051       Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2052     else {
2053       std::vector<Init*> Values;
2054       RecTy *ListTy = 0;
2055       for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2056         Values.push_back(Tree->getArg(j));
2057         TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2058         if (TArg == 0) {
2059           errs() << "In dag: " << Tree->getAsString();
2060           errs() << " --  Untyped argument in pattern\n";
2061           assert(0 && "Untyped argument in pattern");
2062         }
2063         if (ListTy != 0) {
2064           ListTy = resolveTypes(ListTy, TArg->getType());
2065           if (ListTy == 0) {
2066             errs() << "In dag: " << Tree->getAsString();
2067             errs() << " --  Incompatible types in pattern arguments\n";
2068             assert(0 && "Incompatible types in pattern arguments");
2069           }
2070         }
2071         else {
2072           ListTy = TArg->getType();
2073         }
2074       }
2075       ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2076       Pattern = new TreePattern(Patterns[i], LI, true, *this);
2077     }
2078
2079     // Inline pattern fragments into it.
2080     Pattern->InlinePatternFragments();
2081     
2082     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2083     if (LI->getSize() == 0) continue;  // no pattern.
2084     
2085     // Parse the instruction.
2086     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2087     
2088     // Inline pattern fragments into it.
2089     Result->InlinePatternFragments();
2090
2091     if (Result->getNumTrees() != 1)
2092       Result->error("Cannot handle instructions producing instructions "
2093                     "with temporaries yet!");
2094     
2095     bool IterateInference;
2096     bool InferredAllPatternTypes, InferredAllResultTypes;
2097     do {
2098       // Infer as many types as possible.  If we cannot infer all of them, we
2099       // can never do anything with this pattern: report it to the user.
2100       InferredAllPatternTypes = Pattern->InferAllTypes();
2101       
2102       // Infer as many types as possible.  If we cannot infer all of them, we
2103       // can never do anything with this pattern: report it to the user.
2104       InferredAllResultTypes = Result->InferAllTypes();
2105
2106       // Apply the type of the result to the source pattern.  This helps us
2107       // resolve cases where the input type is known to be a pointer type (which
2108       // is considered resolved), but the result knows it needs to be 32- or
2109       // 64-bits.  Infer the other way for good measure.
2110       IterateInference = Pattern->getTree(0)->
2111         UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2112       IterateInference |= Result->getTree(0)->
2113         UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2114     } while (IterateInference);
2115     
2116     // Verify that we inferred enough types that we can do something with the
2117     // pattern and result.  If these fire the user has to add type casts.
2118     if (!InferredAllPatternTypes)
2119       Pattern->error("Could not infer all types in pattern!");
2120     if (!InferredAllResultTypes)
2121       Result->error("Could not infer all types in pattern result!");
2122     
2123     // Validate that the input pattern is correct.
2124     std::map<std::string, TreePatternNode*> InstInputs;
2125     std::map<std::string, TreePatternNode*> InstResults;
2126     std::vector<Record*> InstImpInputs;
2127     std::vector<Record*> InstImpResults;
2128     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2129       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2130                                   InstInputs, InstResults,
2131                                   InstImpInputs, InstImpResults);
2132
2133     // Promote the xform function to be an explicit node if set.
2134     TreePatternNode *DstPattern = Result->getOnlyTree();
2135     std::vector<TreePatternNode*> ResultNodeOperands;
2136     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2137       TreePatternNode *OpNode = DstPattern->getChild(ii);
2138       if (Record *Xform = OpNode->getTransformFn()) {
2139         OpNode->setTransformFn(0);
2140         std::vector<TreePatternNode*> Children;
2141         Children.push_back(OpNode);
2142         OpNode = new TreePatternNode(Xform, Children);
2143       }
2144       ResultNodeOperands.push_back(OpNode);
2145     }
2146     DstPattern = Result->getOnlyTree();
2147     if (!DstPattern->isLeaf())
2148       DstPattern = new TreePatternNode(DstPattern->getOperator(),
2149                                        ResultNodeOperands);
2150     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2151     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2152     Temp.InferAllTypes();
2153
2154     std::string Reason;
2155     if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2156       Pattern->error("Pattern can never match: " + Reason);
2157     
2158     PatternsToMatch.
2159       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2160                                Pattern->getTree(0),
2161                                Temp.getOnlyTree(), InstImpResults,
2162                                Patterns[i]->getValueAsInt("AddedComplexity")));
2163   }
2164 }
2165
2166 /// CombineChildVariants - Given a bunch of permutations of each child of the
2167 /// 'operator' node, put them together in all possible ways.
2168 static void CombineChildVariants(TreePatternNode *Orig, 
2169                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2170                                  std::vector<TreePatternNode*> &OutVariants,
2171                                  CodeGenDAGPatterns &CDP,
2172                                  const MultipleUseVarSet &DepVars) {
2173   // Make sure that each operand has at least one variant to choose from.
2174   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2175     if (ChildVariants[i].empty())
2176       return;
2177         
2178   // The end result is an all-pairs construction of the resultant pattern.
2179   std::vector<unsigned> Idxs;
2180   Idxs.resize(ChildVariants.size());
2181   bool NotDone;
2182   do {
2183 #ifndef NDEBUG
2184     if (DebugFlag && !Idxs.empty()) {
2185       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2186         for (unsigned i = 0; i < Idxs.size(); ++i) {
2187           errs() << Idxs[i] << " ";
2188       }
2189       errs() << "]\n";
2190     }
2191 #endif
2192     // Create the variant and add it to the output list.
2193     std::vector<TreePatternNode*> NewChildren;
2194     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2195       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2196     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2197     
2198     // Copy over properties.
2199     R->setName(Orig->getName());
2200     R->setPredicateFns(Orig->getPredicateFns());
2201     R->setTransformFn(Orig->getTransformFn());
2202     R->setTypes(Orig->getExtTypes());
2203     
2204     // If this pattern cannot match, do not include it as a variant.
2205     std::string ErrString;
2206     if (!R->canPatternMatch(ErrString, CDP)) {
2207       delete R;
2208     } else {
2209       bool AlreadyExists = false;
2210       
2211       // Scan to see if this pattern has already been emitted.  We can get
2212       // duplication due to things like commuting:
2213       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2214       // which are the same pattern.  Ignore the dups.
2215       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2216         if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2217           AlreadyExists = true;
2218           break;
2219         }
2220       
2221       if (AlreadyExists)
2222         delete R;
2223       else
2224         OutVariants.push_back(R);
2225     }
2226     
2227     // Increment indices to the next permutation by incrementing the
2228     // indicies from last index backward, e.g., generate the sequence
2229     // [0, 0], [0, 1], [1, 0], [1, 1].
2230     int IdxsIdx;
2231     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2232       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2233         Idxs[IdxsIdx] = 0;
2234       else
2235         break;
2236     }
2237     NotDone = (IdxsIdx >= 0);
2238   } while (NotDone);
2239 }
2240
2241 /// CombineChildVariants - A helper function for binary operators.
2242 ///
2243 static void CombineChildVariants(TreePatternNode *Orig, 
2244                                  const std::vector<TreePatternNode*> &LHS,
2245                                  const std::vector<TreePatternNode*> &RHS,
2246                                  std::vector<TreePatternNode*> &OutVariants,
2247                                  CodeGenDAGPatterns &CDP,
2248                                  const MultipleUseVarSet &DepVars) {
2249   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2250   ChildVariants.push_back(LHS);
2251   ChildVariants.push_back(RHS);
2252   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2253 }  
2254
2255
2256 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2257                                      std::vector<TreePatternNode *> &Children) {
2258   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2259   Record *Operator = N->getOperator();
2260   
2261   // Only permit raw nodes.
2262   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2263       N->getTransformFn()) {
2264     Children.push_back(N);
2265     return;
2266   }
2267
2268   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2269     Children.push_back(N->getChild(0));
2270   else
2271     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2272
2273   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2274     Children.push_back(N->getChild(1));
2275   else
2276     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2277 }
2278
2279 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2280 /// the (potentially recursive) pattern by using algebraic laws.
2281 ///
2282 static void GenerateVariantsOf(TreePatternNode *N,
2283                                std::vector<TreePatternNode*> &OutVariants,
2284                                CodeGenDAGPatterns &CDP,
2285                                const MultipleUseVarSet &DepVars) {
2286   // We cannot permute leaves.
2287   if (N->isLeaf()) {
2288     OutVariants.push_back(N);
2289     return;
2290   }
2291
2292   // Look up interesting info about the node.
2293   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2294
2295   // If this node is associative, re-associate.
2296   if (NodeInfo.hasProperty(SDNPAssociative)) {
2297     // Re-associate by pulling together all of the linked operators 
2298     std::vector<TreePatternNode*> MaximalChildren;
2299     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2300
2301     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
2302     // permutations.
2303     if (MaximalChildren.size() == 3) {
2304       // Find the variants of all of our maximal children.
2305       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2306       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2307       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2308       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2309       
2310       // There are only two ways we can permute the tree:
2311       //   (A op B) op C    and    A op (B op C)
2312       // Within these forms, we can also permute A/B/C.
2313       
2314       // Generate legal pair permutations of A/B/C.
2315       std::vector<TreePatternNode*> ABVariants;
2316       std::vector<TreePatternNode*> BAVariants;
2317       std::vector<TreePatternNode*> ACVariants;
2318       std::vector<TreePatternNode*> CAVariants;
2319       std::vector<TreePatternNode*> BCVariants;
2320       std::vector<TreePatternNode*> CBVariants;
2321       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2322       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2323       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2324       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2325       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2326       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2327
2328       // Combine those into the result: (x op x) op x
2329       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2330       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2331       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2332       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2333       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2334       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2335
2336       // Combine those into the result: x op (x op x)
2337       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2338       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2339       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2340       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2341       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2342       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2343       return;
2344     }
2345   }
2346   
2347   // Compute permutations of all children.
2348   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2349   ChildVariants.resize(N->getNumChildren());
2350   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2351     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2352
2353   // Build all permutations based on how the children were formed.
2354   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2355
2356   // If this node is commutative, consider the commuted order.
2357   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2358   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2359     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2360            "Commutative but doesn't have 2 children!");
2361     // Don't count children which are actually register references.
2362     unsigned NC = 0;
2363     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2364       TreePatternNode *Child = N->getChild(i);
2365       if (Child->isLeaf())
2366         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2367           Record *RR = DI->getDef();
2368           if (RR->isSubClassOf("Register"))
2369             continue;
2370         }
2371       NC++;
2372     }
2373     // Consider the commuted order.
2374     if (isCommIntrinsic) {
2375       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2376       // operands are the commutative operands, and there might be more operands
2377       // after those.
2378       assert(NC >= 3 &&
2379              "Commutative intrinsic should have at least 3 childrean!");
2380       std::vector<std::vector<TreePatternNode*> > Variants;
2381       Variants.push_back(ChildVariants[0]); // Intrinsic id.
2382       Variants.push_back(ChildVariants[2]);
2383       Variants.push_back(ChildVariants[1]);
2384       for (unsigned i = 3; i != NC; ++i)
2385         Variants.push_back(ChildVariants[i]);
2386       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2387     } else if (NC == 2)
2388       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2389                            OutVariants, CDP, DepVars);
2390   }
2391 }
2392
2393
2394 // GenerateVariants - Generate variants.  For example, commutative patterns can
2395 // match multiple ways.  Add them to PatternsToMatch as well.
2396 void CodeGenDAGPatterns::GenerateVariants() {
2397   DEBUG(errs() << "Generating instruction variants.\n");
2398   
2399   // Loop over all of the patterns we've collected, checking to see if we can
2400   // generate variants of the instruction, through the exploitation of
2401   // identities.  This permits the target to provide aggressive matching without
2402   // the .td file having to contain tons of variants of instructions.
2403   //
2404   // Note that this loop adds new patterns to the PatternsToMatch list, but we
2405   // intentionally do not reconsider these.  Any variants of added patterns have
2406   // already been added.
2407   //
2408   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2409     MultipleUseVarSet             DepVars;
2410     std::vector<TreePatternNode*> Variants;
2411     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2412     DEBUG(errs() << "Dependent/multiply used variables: ");
2413     DEBUG(DumpDepVars(DepVars));
2414     DEBUG(errs() << "\n");
2415     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2416
2417     assert(!Variants.empty() && "Must create at least original variant!");
2418     Variants.erase(Variants.begin());  // Remove the original pattern.
2419
2420     if (Variants.empty())  // No variants for this pattern.
2421       continue;
2422
2423     DEBUG(errs() << "FOUND VARIANTS OF: ";
2424           PatternsToMatch[i].getSrcPattern()->dump();
2425           errs() << "\n");
2426
2427     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2428       TreePatternNode *Variant = Variants[v];
2429
2430       DEBUG(errs() << "  VAR#" << v <<  ": ";
2431             Variant->dump();
2432             errs() << "\n");
2433       
2434       // Scan to see if an instruction or explicit pattern already matches this.
2435       bool AlreadyExists = false;
2436       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2437         // Skip if the top level predicates do not match.
2438         if (PatternsToMatch[i].getPredicates() !=
2439             PatternsToMatch[p].getPredicates())
2440           continue;
2441         // Check to see if this variant already exists.
2442         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2443           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
2444           AlreadyExists = true;
2445           break;
2446         }
2447       }
2448       // If we already have it, ignore the variant.
2449       if (AlreadyExists) continue;
2450
2451       // Otherwise, add it to the list of patterns we have.
2452       PatternsToMatch.
2453         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2454                                  Variant, PatternsToMatch[i].getDstPattern(),
2455                                  PatternsToMatch[i].getDstRegs(),
2456                                  PatternsToMatch[i].getAddedComplexity()));
2457     }
2458
2459     DEBUG(errs() << "\n");
2460   }
2461 }
2462