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