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