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