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