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