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