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