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