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