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