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