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