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