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