1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CodeGenDAGPatterns class, which is used to read and
10 // represent the patterns present in a .td file for instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenDAGPatterns.h"
15 #include "CodeGenInstruction.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/TypeSize.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 #include <algorithm>
30 #include <cstdio>
31 #include <iterator>
32 #include <set>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "dag-patterns"
36 
37 static inline bool isIntegerOrPtr(MVT VT) {
38   return VT.isInteger() || VT == MVT::iPTR;
39 }
40 static inline bool isFloatingPoint(MVT VT) {
41   return VT.isFloatingPoint();
42 }
43 static inline bool isVector(MVT VT) {
44   return VT.isVector();
45 }
46 static inline bool isScalar(MVT VT) {
47   return !VT.isVector();
48 }
49 static inline bool isScalarInteger(MVT VT) {
50   return VT.isScalarInteger();
51 }
52 
53 template <typename Predicate>
54 static bool berase_if(MachineValueTypeSet &S, Predicate P) {
55   bool Erased = false;
56   // It is ok to iterate over MachineValueTypeSet and remove elements from it
57   // at the same time.
58   for (MVT T : S) {
59     if (!P(T))
60       continue;
61     Erased = true;
62     S.erase(T);
63   }
64   return Erased;
65 }
66 
67 void MachineValueTypeSet::writeToStream(raw_ostream &OS) const {
68   SmallVector<MVT, 4> Types(begin(), end());
69   array_pod_sort(Types.begin(), Types.end());
70 
71   OS << '[';
72   ListSeparator LS(" ");
73   for (const MVT &T : Types)
74     OS << LS << ValueTypeByHwMode::getMVTName(T);
75   OS << ']';
76 }
77 
78 // --- TypeSetByHwMode
79 
80 // This is a parameterized type-set class. For each mode there is a list
81 // of types that are currently possible for a given tree node. Type
82 // inference will apply to each mode separately.
83 
84 TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
85   for (const ValueTypeByHwMode &VVT : VTList) {
86     insert(VVT);
87     AddrSpaces.push_back(VVT.PtrAddrSpace);
88   }
89 }
90 
91 bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
92   for (const auto &I : *this) {
93     if (I.second.size() > 1)
94       return false;
95     if (!AllowEmpty && I.second.empty())
96       return false;
97   }
98   return true;
99 }
100 
101 ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
102   assert(isValueTypeByHwMode(true) &&
103          "The type set has multiple types for at least one HW mode");
104   ValueTypeByHwMode VVT;
105   auto ASI = AddrSpaces.begin();
106 
107   for (const auto &I : *this) {
108     MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
109     VVT.getOrCreateTypeForMode(I.first, T);
110     if (ASI != AddrSpaces.end())
111       VVT.PtrAddrSpace = *ASI++;
112   }
113   return VVT;
114 }
115 
116 bool TypeSetByHwMode::isPossible() const {
117   for (const auto &I : *this)
118     if (!I.second.empty())
119       return true;
120   return false;
121 }
122 
123 bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
124   bool Changed = false;
125   bool ContainsDefault = false;
126   MVT DT = MVT::Other;
127 
128   for (const auto &P : VVT) {
129     unsigned M = P.first;
130     // Make sure there exists a set for each specific mode from VVT.
131     Changed |= getOrCreate(M).insert(P.second).second;
132     // Cache VVT's default mode.
133     if (DefaultMode == M) {
134       ContainsDefault = true;
135       DT = P.second;
136     }
137   }
138 
139   // If VVT has a default mode, add the corresponding type to all
140   // modes in "this" that do not exist in VVT.
141   if (ContainsDefault)
142     for (auto &I : *this)
143       if (!VVT.hasMode(I.first))
144         Changed |= I.second.insert(DT).second;
145 
146   return Changed;
147 }
148 
149 // Constrain the type set to be the intersection with VTS.
150 bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
151   bool Changed = false;
152   if (hasDefault()) {
153     for (const auto &I : VTS) {
154       unsigned M = I.first;
155       if (M == DefaultMode || hasMode(M))
156         continue;
157       Map.insert({M, Map.at(DefaultMode)});
158       Changed = true;
159     }
160   }
161 
162   for (auto &I : *this) {
163     unsigned M = I.first;
164     SetType &S = I.second;
165     if (VTS.hasMode(M) || VTS.hasDefault()) {
166       Changed |= intersect(I.second, VTS.get(M));
167     } else if (!S.empty()) {
168       S.clear();
169       Changed = true;
170     }
171   }
172   return Changed;
173 }
174 
175 template <typename Predicate>
176 bool TypeSetByHwMode::constrain(Predicate P) {
177   bool Changed = false;
178   for (auto &I : *this)
179     Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
180   return Changed;
181 }
182 
183 template <typename Predicate>
184 bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
185   assert(empty());
186   for (const auto &I : VTS) {
187     SetType &S = getOrCreate(I.first);
188     for (auto J : I.second)
189       if (P(J))
190         S.insert(J);
191   }
192   return !empty();
193 }
194 
195 void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
196   SmallVector<unsigned, 4> Modes;
197   Modes.reserve(Map.size());
198 
199   for (const auto &I : *this)
200     Modes.push_back(I.first);
201   if (Modes.empty()) {
202     OS << "{}";
203     return;
204   }
205   array_pod_sort(Modes.begin(), Modes.end());
206 
207   OS << '{';
208   for (unsigned M : Modes) {
209     OS << ' ' << getModeName(M) << ':';
210     get(M).writeToStream(OS);
211   }
212   OS << " }";
213 }
214 
215 bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
216   // The isSimple call is much quicker than hasDefault - check this first.
217   bool IsSimple = isSimple();
218   bool VTSIsSimple = VTS.isSimple();
219   if (IsSimple && VTSIsSimple)
220     return *begin() == *VTS.begin();
221 
222   // Speedup: We have a default if the set is simple.
223   bool HaveDefault = IsSimple || hasDefault();
224   bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
225   if (HaveDefault != VTSHaveDefault)
226     return false;
227 
228   SmallSet<unsigned, 4> Modes;
229   for (auto &I : *this)
230     Modes.insert(I.first);
231   for (const auto &I : VTS)
232     Modes.insert(I.first);
233 
234   if (HaveDefault) {
235     // Both sets have default mode.
236     for (unsigned M : Modes) {
237       if (get(M) != VTS.get(M))
238         return false;
239     }
240   } else {
241     // Neither set has default mode.
242     for (unsigned M : Modes) {
243       // If there is no default mode, an empty set is equivalent to not having
244       // the corresponding mode.
245       bool NoModeThis = !hasMode(M) || get(M).empty();
246       bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
247       if (NoModeThis != NoModeVTS)
248         return false;
249       if (!NoModeThis)
250         if (get(M) != VTS.get(M))
251           return false;
252     }
253   }
254 
255   return true;
256 }
257 
258 namespace llvm {
259   raw_ostream &operator<<(raw_ostream &OS, const MachineValueTypeSet &T) {
260     T.writeToStream(OS);
261     return OS;
262   }
263   raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
264     T.writeToStream(OS);
265     return OS;
266   }
267 }
268 
269 LLVM_DUMP_METHOD
270 void TypeSetByHwMode::dump() const {
271   dbgs() << *this << '\n';
272 }
273 
274 bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
275   bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
276   // Complement of In.
277   auto CompIn = [&In](MVT T) -> bool { return !In.count(T); };
278 
279   if (OutP == InP)
280     return berase_if(Out, CompIn);
281 
282   // Compute the intersection of scalars separately to account for only
283   // one set containing iPTR.
284   // The intersection of iPTR with a set of integer scalar types that does not
285   // include iPTR will result in the most specific scalar type:
286   // - iPTR is more specific than any set with two elements or more
287   // - iPTR is less specific than any single integer scalar type.
288   // For example
289   // { iPTR } * { i32 }     -> { i32 }
290   // { iPTR } * { i32 i64 } -> { iPTR }
291   // and
292   // { iPTR i32 } * { i32 }          -> { i32 }
293   // { iPTR i32 } * { i32 i64 }      -> { i32 i64 }
294   // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
295 
296   // Let In' = elements only in In, Out' = elements only in Out, and
297   // IO = elements common to both. Normally IO would be returned as the result
298   // of the intersection, but we need to account for iPTR being a "wildcard" of
299   // sorts. Since elements in IO are those that match both sets exactly, they
300   // will all belong to the output. If any of the "leftovers" (i.e. In' or
301   // Out') contain iPTR, it means that the other set doesn't have it, but it
302   // could have (1) a more specific type, or (2) a set of types that is less
303   // specific. The "leftovers" from the other set is what we want to examine
304   // more closely.
305 
306   auto subtract = [](const SetType &A, const SetType &B) {
307     SetType Diff = A;
308     berase_if(Diff, [&B](MVT T) { return B.count(T); });
309     return Diff;
310   };
311 
312   if (InP) {
313     SetType OutOnly = subtract(Out, In);
314     if (OutOnly.empty()) {
315       // This means that Out \subset In, so no change to Out.
316       return false;
317     }
318     unsigned NumI = llvm::count_if(OutOnly, isScalarInteger);
319     if (NumI == 1 && OutOnly.size() == 1) {
320       // There is only one element in Out', and it happens to be a scalar
321       // integer that should be kept as a match for iPTR in In.
322       return false;
323     }
324     berase_if(Out, CompIn);
325     if (NumI == 1) {
326       // Replace the iPTR with the leftover scalar integer.
327       Out.insert(*llvm::find_if(OutOnly, isScalarInteger));
328     } else if (NumI > 1) {
329       Out.insert(MVT::iPTR);
330     }
331     return true;
332   }
333 
334   // OutP == true
335   SetType InOnly = subtract(In, Out);
336   unsigned SizeOut = Out.size();
337   berase_if(Out, CompIn);   // This will remove at least the iPTR.
338   unsigned NumI = llvm::count_if(InOnly, isScalarInteger);
339   if (NumI == 0) {
340     // iPTR deleted from Out.
341     return true;
342   }
343   if (NumI == 1) {
344     // Replace the iPTR with the leftover scalar integer.
345     Out.insert(*llvm::find_if(InOnly, isScalarInteger));
346     return true;
347   }
348 
349   // NumI > 1: Keep the iPTR in Out.
350   Out.insert(MVT::iPTR);
351   // If iPTR was the only element initially removed from Out, then Out
352   // has not changed.
353   return SizeOut != Out.size();
354 }
355 
356 bool TypeSetByHwMode::validate() const {
357 #ifndef NDEBUG
358   if (empty())
359     return true;
360   bool AllEmpty = true;
361   for (const auto &I : *this)
362     AllEmpty &= I.second.empty();
363   return !AllEmpty;
364 #endif
365   return true;
366 }
367 
368 // --- TypeInfer
369 
370 bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
371                                 const TypeSetByHwMode &In) {
372   ValidateOnExit _1(Out, *this);
373   In.validate();
374   if (In.empty() || Out == In || TP.hasError())
375     return false;
376   if (Out.empty()) {
377     Out = In;
378     return true;
379   }
380 
381   bool Changed = Out.constrain(In);
382   if (Changed && Out.empty())
383     TP.error("Type contradiction");
384 
385   return Changed;
386 }
387 
388 bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
389   ValidateOnExit _1(Out, *this);
390   if (TP.hasError())
391     return false;
392   assert(!Out.empty() && "cannot pick from an empty set");
393 
394   bool Changed = false;
395   for (auto &I : Out) {
396     TypeSetByHwMode::SetType &S = I.second;
397     if (S.size() <= 1)
398       continue;
399     MVT T = *S.begin(); // Pick the first element.
400     S.clear();
401     S.insert(T);
402     Changed = true;
403   }
404   return Changed;
405 }
406 
407 bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
408   ValidateOnExit _1(Out, *this);
409   if (TP.hasError())
410     return false;
411   if (!Out.empty())
412     return Out.constrain(isIntegerOrPtr);
413 
414   return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
415 }
416 
417 bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
418   ValidateOnExit _1(Out, *this);
419   if (TP.hasError())
420     return false;
421   if (!Out.empty())
422     return Out.constrain(isFloatingPoint);
423 
424   return Out.assign_if(getLegalTypes(), isFloatingPoint);
425 }
426 
427 bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
428   ValidateOnExit _1(Out, *this);
429   if (TP.hasError())
430     return false;
431   if (!Out.empty())
432     return Out.constrain(isScalar);
433 
434   return Out.assign_if(getLegalTypes(), isScalar);
435 }
436 
437 bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
438   ValidateOnExit _1(Out, *this);
439   if (TP.hasError())
440     return false;
441   if (!Out.empty())
442     return Out.constrain(isVector);
443 
444   return Out.assign_if(getLegalTypes(), isVector);
445 }
446 
447 bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
448   ValidateOnExit _1(Out, *this);
449   if (TP.hasError() || !Out.empty())
450     return false;
451 
452   Out = getLegalTypes();
453   return true;
454 }
455 
456 template <typename Iter, typename Pred, typename Less>
457 static Iter min_if(Iter B, Iter E, Pred P, Less L) {
458   if (B == E)
459     return E;
460   Iter Min = E;
461   for (Iter I = B; I != E; ++I) {
462     if (!P(*I))
463       continue;
464     if (Min == E || L(*I, *Min))
465       Min = I;
466   }
467   return Min;
468 }
469 
470 template <typename Iter, typename Pred, typename Less>
471 static Iter max_if(Iter B, Iter E, Pred P, Less L) {
472   if (B == E)
473     return E;
474   Iter Max = E;
475   for (Iter I = B; I != E; ++I) {
476     if (!P(*I))
477       continue;
478     if (Max == E || L(*Max, *I))
479       Max = I;
480   }
481   return Max;
482 }
483 
484 /// Make sure that for each type in Small, there exists a larger type in Big.
485 bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
486                                    bool SmallIsVT) {
487   ValidateOnExit _1(Small, *this), _2(Big, *this);
488   if (TP.hasError())
489     return false;
490   bool Changed = false;
491 
492   assert((!SmallIsVT || !Small.empty()) &&
493          "Small should not be empty for SDTCisVTSmallerThanOp");
494 
495   if (Small.empty())
496     Changed |= EnforceAny(Small);
497   if (Big.empty())
498     Changed |= EnforceAny(Big);
499 
500   assert(Small.hasDefault() && Big.hasDefault());
501 
502   SmallVector<unsigned, 4> Modes;
503   union_modes(Small, Big, Modes);
504 
505   // 1. Only allow integer or floating point types and make sure that
506   //    both sides are both integer or both floating point.
507   // 2. Make sure that either both sides have vector types, or neither
508   //    of them does.
509   for (unsigned M : Modes) {
510     TypeSetByHwMode::SetType &S = Small.get(M);
511     TypeSetByHwMode::SetType &B = Big.get(M);
512 
513     assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");
514 
515     if (any_of(S, isIntegerOrPtr) && any_of(B, isIntegerOrPtr)) {
516       auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
517       Changed |= berase_if(S, NotInt);
518       Changed |= berase_if(B, NotInt);
519     } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
520       auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
521       Changed |= berase_if(S, NotFP);
522       Changed |= berase_if(B, NotFP);
523     } else if (SmallIsVT && B.empty()) {
524       // B is empty and since S is a specific VT, it will never be empty. Don't
525       // report this as a change, just clear S and continue. This prevents an
526       // infinite loop.
527       S.clear();
528     } else if (S.empty() || B.empty()) {
529       Changed = !S.empty() || !B.empty();
530       S.clear();
531       B.clear();
532     } else {
533       TP.error("Incompatible types");
534       return Changed;
535     }
536 
537     if (none_of(S, isVector) || none_of(B, isVector)) {
538       Changed |= berase_if(S, isVector);
539       Changed |= berase_if(B, isVector);
540     }
541   }
542 
543   auto LT = [](MVT A, MVT B) -> bool {
544     // Always treat non-scalable MVTs as smaller than scalable MVTs for the
545     // purposes of ordering.
546     auto ASize = std::make_tuple(A.isScalableVector(), A.getScalarSizeInBits(),
547                                  A.getSizeInBits().getKnownMinSize());
548     auto BSize = std::make_tuple(B.isScalableVector(), B.getScalarSizeInBits(),
549                                  B.getSizeInBits().getKnownMinSize());
550     return ASize < BSize;
551   };
552   auto SameKindLE = [](MVT A, MVT B) -> bool {
553     // This function is used when removing elements: when a vector is compared
554     // to a non-vector or a scalable vector to any non-scalable MVT, it should
555     // return false (to avoid removal).
556     if (std::make_tuple(A.isVector(), A.isScalableVector()) !=
557         std::make_tuple(B.isVector(), B.isScalableVector()))
558       return false;
559 
560     return std::make_tuple(A.getScalarSizeInBits(),
561                            A.getSizeInBits().getKnownMinSize()) <=
562            std::make_tuple(B.getScalarSizeInBits(),
563                            B.getSizeInBits().getKnownMinSize());
564   };
565 
566   for (unsigned M : Modes) {
567     TypeSetByHwMode::SetType &S = Small.get(M);
568     TypeSetByHwMode::SetType &B = Big.get(M);
569     // MinS = min scalar in Small, remove all scalars from Big that are
570     // smaller-or-equal than MinS.
571     auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
572     if (MinS != S.end())
573       Changed |= berase_if(B, std::bind(SameKindLE,
574                                         std::placeholders::_1, *MinS));
575 
576     // MaxS = max scalar in Big, remove all scalars from Small that are
577     // larger than MaxS.
578     auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
579     if (MaxS != B.end())
580       Changed |= berase_if(S, std::bind(SameKindLE,
581                                         *MaxS, std::placeholders::_1));
582 
583     // MinV = min vector in Small, remove all vectors from Big that are
584     // smaller-or-equal than MinV.
585     auto MinV = min_if(S.begin(), S.end(), isVector, LT);
586     if (MinV != S.end())
587       Changed |= berase_if(B, std::bind(SameKindLE,
588                                         std::placeholders::_1, *MinV));
589 
590     // MaxV = max vector in Big, remove all vectors from Small that are
591     // larger than MaxV.
592     auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
593     if (MaxV != B.end())
594       Changed |= berase_if(S, std::bind(SameKindLE,
595                                         *MaxV, std::placeholders::_1));
596   }
597 
598   return Changed;
599 }
600 
601 /// 1. Ensure that for each type T in Vec, T is a vector type, and that
602 ///    for each type U in Elem, U is a scalar type.
603 /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
604 ///    type T in Vec, such that U is the element type of T.
605 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
606                                        TypeSetByHwMode &Elem) {
607   ValidateOnExit _1(Vec, *this), _2(Elem, *this);
608   if (TP.hasError())
609     return false;
610   bool Changed = false;
611 
612   if (Vec.empty())
613     Changed |= EnforceVector(Vec);
614   if (Elem.empty())
615     Changed |= EnforceScalar(Elem);
616 
617   SmallVector<unsigned, 4> Modes;
618   union_modes(Vec, Elem, Modes);
619   for (unsigned M : Modes) {
620     TypeSetByHwMode::SetType &V = Vec.get(M);
621     TypeSetByHwMode::SetType &E = Elem.get(M);
622 
623     Changed |= berase_if(V, isScalar);  // Scalar = !vector
624     Changed |= berase_if(E, isVector);  // Vector = !scalar
625     assert(!V.empty() && !E.empty());
626 
627     MachineValueTypeSet VT, ST;
628     // Collect element types from the "vector" set.
629     for (MVT T : V)
630       VT.insert(T.getVectorElementType());
631     // Collect scalar types from the "element" set.
632     for (MVT T : E)
633       ST.insert(T);
634 
635     // Remove from V all (vector) types whose element type is not in S.
636     Changed |= berase_if(V, [&ST](MVT T) -> bool {
637                               return !ST.count(T.getVectorElementType());
638                             });
639     // Remove from E all (scalar) types, for which there is no corresponding
640     // type in V.
641     Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
642   }
643 
644   return Changed;
645 }
646 
647 bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
648                                        const ValueTypeByHwMode &VVT) {
649   TypeSetByHwMode Tmp(VVT);
650   ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
651   return EnforceVectorEltTypeIs(Vec, Tmp);
652 }
653 
654 /// Ensure that for each type T in Sub, T is a vector type, and there
655 /// exists a type U in Vec such that U is a vector type with the same
656 /// element type as T and at least as many elements as T.
657 bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
658                                              TypeSetByHwMode &Sub) {
659   ValidateOnExit _1(Vec, *this), _2(Sub, *this);
660   if (TP.hasError())
661     return false;
662 
663   /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
664   auto IsSubVec = [](MVT B, MVT P) -> bool {
665     if (!B.isVector() || !P.isVector())
666       return false;
667     // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
668     // but until there are obvious use-cases for this, keep the
669     // types separate.
670     if (B.isScalableVector() != P.isScalableVector())
671       return false;
672     if (B.getVectorElementType() != P.getVectorElementType())
673       return false;
674     return B.getVectorMinNumElements() < P.getVectorMinNumElements();
675   };
676 
677   /// Return true if S has no element (vector type) that T is a sub-vector of,
678   /// i.e. has the same element type as T and more elements.
679   auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
680     for (auto I : S)
681       if (IsSubVec(T, I))
682         return false;
683     return true;
684   };
685 
686   /// Return true if S has no element (vector type) that T is a super-vector
687   /// of, i.e. has the same element type as T and fewer elements.
688   auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
689     for (auto I : S)
690       if (IsSubVec(I, T))
691         return false;
692     return true;
693   };
694 
695   bool Changed = false;
696 
697   if (Vec.empty())
698     Changed |= EnforceVector(Vec);
699   if (Sub.empty())
700     Changed |= EnforceVector(Sub);
701 
702   SmallVector<unsigned, 4> Modes;
703   union_modes(Vec, Sub, Modes);
704   for (unsigned M : Modes) {
705     TypeSetByHwMode::SetType &S = Sub.get(M);
706     TypeSetByHwMode::SetType &V = Vec.get(M);
707 
708     Changed |= berase_if(S, isScalar);
709 
710     // Erase all types from S that are not sub-vectors of a type in V.
711     Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
712 
713     // Erase all types from V that are not super-vectors of a type in S.
714     Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
715   }
716 
717   return Changed;
718 }
719 
720 /// 1. Ensure that V has a scalar type iff W has a scalar type.
721 /// 2. Ensure that for each vector type T in V, there exists a vector
722 ///    type U in W, such that T and U have the same number of elements.
723 /// 3. Ensure that for each vector type U in W, there exists a vector
724 ///    type T in V, such that T and U have the same number of elements
725 ///    (reverse of 2).
726 bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
727   ValidateOnExit _1(V, *this), _2(W, *this);
728   if (TP.hasError())
729     return false;
730 
731   bool Changed = false;
732   if (V.empty())
733     Changed |= EnforceAny(V);
734   if (W.empty())
735     Changed |= EnforceAny(W);
736 
737   // An actual vector type cannot have 0 elements, so we can treat scalars
738   // as zero-length vectors. This way both vectors and scalars can be
739   // processed identically.
740   auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,
741                      MVT T) -> bool {
742     return !Lengths.count(T.isVector() ? T.getVectorElementCount()
743                                        : ElementCount::getNull());
744   };
745 
746   SmallVector<unsigned, 4> Modes;
747   union_modes(V, W, Modes);
748   for (unsigned M : Modes) {
749     TypeSetByHwMode::SetType &VS = V.get(M);
750     TypeSetByHwMode::SetType &WS = W.get(M);
751 
752     SmallDenseSet<ElementCount> VN, WN;
753     for (MVT T : VS)
754       VN.insert(T.isVector() ? T.getVectorElementCount()
755                              : ElementCount::getNull());
756     for (MVT T : WS)
757       WN.insert(T.isVector() ? T.getVectorElementCount()
758                              : ElementCount::getNull());
759 
760     Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
761     Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
762   }
763   return Changed;
764 }
765 
766 namespace {
767 struct TypeSizeComparator {
768   bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {
769     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
770            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
771   }
772 };
773 } // end anonymous namespace
774 
775 /// 1. Ensure that for each type T in A, there exists a type U in B,
776 ///    such that T and U have equal size in bits.
777 /// 2. Ensure that for each type U in B, there exists a type T in A
778 ///    such that T and U have equal size in bits (reverse of 1).
779 bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
780   ValidateOnExit _1(A, *this), _2(B, *this);
781   if (TP.hasError())
782     return false;
783   bool Changed = false;
784   if (A.empty())
785     Changed |= EnforceAny(A);
786   if (B.empty())
787     Changed |= EnforceAny(B);
788 
789   typedef SmallSet<TypeSize, 2, TypeSizeComparator> TypeSizeSet;
790 
791   auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {
792     return !Sizes.count(T.getSizeInBits());
793   };
794 
795   SmallVector<unsigned, 4> Modes;
796   union_modes(A, B, Modes);
797   for (unsigned M : Modes) {
798     TypeSetByHwMode::SetType &AS = A.get(M);
799     TypeSetByHwMode::SetType &BS = B.get(M);
800     TypeSizeSet AN, BN;
801 
802     for (MVT T : AS)
803       AN.insert(T.getSizeInBits());
804     for (MVT T : BS)
805       BN.insert(T.getSizeInBits());
806 
807     Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
808     Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
809   }
810 
811   return Changed;
812 }
813 
814 void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
815   ValidateOnExit _1(VTS, *this);
816   const TypeSetByHwMode &Legal = getLegalTypes();
817   assert(Legal.isDefaultOnly() && "Default-mode only expected");
818   const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
819 
820   for (auto &I : VTS)
821     expandOverloads(I.second, LegalTypes);
822 }
823 
824 void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
825                                 const TypeSetByHwMode::SetType &Legal) {
826   std::set<MVT> Ovs;
827   for (MVT T : Out) {
828     if (!T.isOverloaded())
829       continue;
830 
831     Ovs.insert(T);
832     // MachineValueTypeSet allows iteration and erasing.
833     Out.erase(T);
834   }
835 
836   for (MVT Ov : Ovs) {
837     switch (Ov.SimpleTy) {
838       case MVT::iPTRAny:
839         Out.insert(MVT::iPTR);
840         return;
841       case MVT::iAny:
842         for (MVT T : MVT::integer_valuetypes())
843           if (Legal.count(T))
844             Out.insert(T);
845         for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
846           if (Legal.count(T))
847             Out.insert(T);
848         for (MVT T : MVT::integer_scalable_vector_valuetypes())
849           if (Legal.count(T))
850             Out.insert(T);
851         return;
852       case MVT::fAny:
853         for (MVT T : MVT::fp_valuetypes())
854           if (Legal.count(T))
855             Out.insert(T);
856         for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
857           if (Legal.count(T))
858             Out.insert(T);
859         for (MVT T : MVT::fp_scalable_vector_valuetypes())
860           if (Legal.count(T))
861             Out.insert(T);
862         return;
863       case MVT::vAny:
864         for (MVT T : MVT::vector_valuetypes())
865           if (Legal.count(T))
866             Out.insert(T);
867         return;
868       case MVT::Any:
869         for (MVT T : MVT::all_valuetypes())
870           if (Legal.count(T))
871             Out.insert(T);
872         return;
873       default:
874         break;
875     }
876   }
877 }
878 
879 const TypeSetByHwMode &TypeInfer::getLegalTypes() {
880   if (!LegalTypesCached) {
881     TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
882     // Stuff all types from all modes into the default mode.
883     const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
884     for (const auto &I : LTS)
885       LegalTypes.insert(I.second);
886     LegalTypesCached = true;
887   }
888   assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
889   return LegalCache;
890 }
891 
892 #ifndef NDEBUG
893 TypeInfer::ValidateOnExit::~ValidateOnExit() {
894   if (Infer.Validate && !VTS.validate()) {
895     dbgs() << "Type set is empty for each HW mode:\n"
896               "possible type contradiction in the pattern below "
897               "(use -print-records with llvm-tblgen to see all "
898               "expanded records).\n";
899     Infer.TP.dump();
900     dbgs() << "Generated from record:\n";
901     Infer.TP.getRecord()->dump();
902     PrintFatalError(Infer.TP.getRecord()->getLoc(),
903                     "Type set is empty for each HW mode in '" +
904                         Infer.TP.getRecord()->getName() + "'");
905   }
906 }
907 #endif
908 
909 
910 //===----------------------------------------------------------------------===//
911 // ScopedName Implementation
912 //===----------------------------------------------------------------------===//
913 
914 bool ScopedName::operator==(const ScopedName &o) const {
915   return Scope == o.Scope && Identifier == o.Identifier;
916 }
917 
918 bool ScopedName::operator!=(const ScopedName &o) const {
919   return !(*this == o);
920 }
921 
922 
923 //===----------------------------------------------------------------------===//
924 // TreePredicateFn Implementation
925 //===----------------------------------------------------------------------===//
926 
927 /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
928 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
929   assert(
930       (!hasPredCode() || !hasImmCode()) &&
931       ".td file corrupt: can't have a node predicate *and* an imm predicate");
932 }
933 
934 bool TreePredicateFn::hasPredCode() const {
935   return isLoad() || isStore() || isAtomic() ||
936          !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
937 }
938 
939 std::string TreePredicateFn::getPredCode() const {
940   std::string Code;
941 
942   if (!isLoad() && !isStore() && !isAtomic()) {
943     Record *MemoryVT = getMemoryVT();
944 
945     if (MemoryVT)
946       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947                       "MemoryVT requires IsLoad or IsStore");
948   }
949 
950   if (!isLoad() && !isStore()) {
951     if (isUnindexed())
952       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953                       "IsUnindexed requires IsLoad or IsStore");
954 
955     Record *ScalarMemoryVT = getScalarMemoryVT();
956 
957     if (ScalarMemoryVT)
958       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
959                       "ScalarMemoryVT requires IsLoad or IsStore");
960   }
961 
962   if (isLoad() + isStore() + isAtomic() > 1)
963     PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
964                     "IsLoad, IsStore, and IsAtomic are mutually exclusive");
965 
966   if (isLoad()) {
967     if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
968         !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
969         getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
970         getMinAlignment() < 1)
971       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
972                       "IsLoad cannot be used by itself");
973   } else {
974     if (isNonExtLoad())
975       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
976                       "IsNonExtLoad requires IsLoad");
977     if (isAnyExtLoad())
978       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
979                       "IsAnyExtLoad requires IsLoad");
980     if (isSignExtLoad())
981       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
982                       "IsSignExtLoad requires IsLoad");
983     if (isZeroExtLoad())
984       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
985                       "IsZeroExtLoad requires IsLoad");
986   }
987 
988   if (isStore()) {
989     if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
990         getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
991         getAddressSpaces() == nullptr && getMinAlignment() < 1)
992       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
993                       "IsStore cannot be used by itself");
994   } else {
995     if (isNonTruncStore())
996       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
997                       "IsNonTruncStore requires IsStore");
998     if (isTruncStore())
999       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1000                       "IsTruncStore requires IsStore");
1001   }
1002 
1003   if (isAtomic()) {
1004     if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
1005         getAddressSpaces() == nullptr &&
1006         !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
1007         !isAtomicOrderingAcquireRelease() &&
1008         !isAtomicOrderingSequentiallyConsistent() &&
1009         !isAtomicOrderingAcquireOrStronger() &&
1010         !isAtomicOrderingReleaseOrStronger() &&
1011         !isAtomicOrderingWeakerThanAcquire() &&
1012         !isAtomicOrderingWeakerThanRelease())
1013       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1014                       "IsAtomic cannot be used by itself");
1015   } else {
1016     if (isAtomicOrderingMonotonic())
1017       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1018                       "IsAtomicOrderingMonotonic requires IsAtomic");
1019     if (isAtomicOrderingAcquire())
1020       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1021                       "IsAtomicOrderingAcquire requires IsAtomic");
1022     if (isAtomicOrderingRelease())
1023       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1024                       "IsAtomicOrderingRelease requires IsAtomic");
1025     if (isAtomicOrderingAcquireRelease())
1026       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1027                       "IsAtomicOrderingAcquireRelease requires IsAtomic");
1028     if (isAtomicOrderingSequentiallyConsistent())
1029       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1030                       "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
1031     if (isAtomicOrderingAcquireOrStronger())
1032       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1033                       "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
1034     if (isAtomicOrderingReleaseOrStronger())
1035       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1036                       "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
1037     if (isAtomicOrderingWeakerThanAcquire())
1038       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1039                       "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
1040   }
1041 
1042   if (isLoad() || isStore() || isAtomic()) {
1043     if (ListInit *AddressSpaces = getAddressSpaces()) {
1044       Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
1045         " if (";
1046 
1047       ListSeparator LS(" && ");
1048       for (Init *Val : AddressSpaces->getValues()) {
1049         Code += LS;
1050 
1051         IntInit *IntVal = dyn_cast<IntInit>(Val);
1052         if (!IntVal) {
1053           PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1054                           "AddressSpaces element must be integer");
1055         }
1056 
1057         Code += "AddrSpace != " + utostr(IntVal->getValue());
1058       }
1059 
1060       Code += ")\nreturn false;\n";
1061     }
1062 
1063     int64_t MinAlign = getMinAlignment();
1064     if (MinAlign > 0) {
1065       Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
1066       Code += utostr(MinAlign);
1067       Code += "))\nreturn false;\n";
1068     }
1069 
1070     Record *MemoryVT = getMemoryVT();
1071 
1072     if (MemoryVT)
1073       Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
1074                MemoryVT->getName() + ") return false;\n")
1075                   .str();
1076   }
1077 
1078   if (isAtomic() && isAtomicOrderingMonotonic())
1079     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1080             "AtomicOrdering::Monotonic) return false;\n";
1081   if (isAtomic() && isAtomicOrderingAcquire())
1082     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1083             "AtomicOrdering::Acquire) return false;\n";
1084   if (isAtomic() && isAtomicOrderingRelease())
1085     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1086             "AtomicOrdering::Release) return false;\n";
1087   if (isAtomic() && isAtomicOrderingAcquireRelease())
1088     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1089             "AtomicOrdering::AcquireRelease) return false;\n";
1090   if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1091     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1092             "AtomicOrdering::SequentiallyConsistent) return false;\n";
1093 
1094   if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1095     Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1096             "return false;\n";
1097   if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1098     Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1099             "return false;\n";
1100 
1101   if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1102     Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1103             "return false;\n";
1104   if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1105     Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1106             "return false;\n";
1107 
1108   if (isLoad() || isStore()) {
1109     StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1110 
1111     if (isUnindexed())
1112       Code += ("if (cast<" + SDNodeName +
1113                ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1114                "return false;\n")
1115                   .str();
1116 
1117     if (isLoad()) {
1118       if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1119            isZeroExtLoad()) > 1)
1120         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1121                         "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1122                         "IsZeroExtLoad are mutually exclusive");
1123       if (isNonExtLoad())
1124         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1125                 "ISD::NON_EXTLOAD) return false;\n";
1126       if (isAnyExtLoad())
1127         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1128                 "return false;\n";
1129       if (isSignExtLoad())
1130         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1131                 "return false;\n";
1132       if (isZeroExtLoad())
1133         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1134                 "return false;\n";
1135     } else {
1136       if ((isNonTruncStore() + isTruncStore()) > 1)
1137         PrintFatalError(
1138             getOrigPatFragRecord()->getRecord()->getLoc(),
1139             "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1140       if (isNonTruncStore())
1141         Code +=
1142             " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1143       if (isTruncStore())
1144         Code +=
1145             " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1146     }
1147 
1148     Record *ScalarMemoryVT = getScalarMemoryVT();
1149 
1150     if (ScalarMemoryVT)
1151       Code += ("if (cast<" + SDNodeName +
1152                ">(N)->getMemoryVT().getScalarType() != MVT::" +
1153                ScalarMemoryVT->getName() + ") return false;\n")
1154                   .str();
1155   }
1156 
1157   std::string PredicateCode =
1158       std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
1159 
1160   Code += PredicateCode;
1161 
1162   if (PredicateCode.empty() && !Code.empty())
1163     Code += "return true;\n";
1164 
1165   return Code;
1166 }
1167 
1168 bool TreePredicateFn::hasImmCode() const {
1169   return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1170 }
1171 
1172 std::string TreePredicateFn::getImmCode() const {
1173   return std::string(
1174       PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
1175 }
1176 
1177 bool TreePredicateFn::immCodeUsesAPInt() const {
1178   return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1179 }
1180 
1181 bool TreePredicateFn::immCodeUsesAPFloat() const {
1182   bool Unset;
1183   // The return value will be false when IsAPFloat is unset.
1184   return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1185                                                                    Unset);
1186 }
1187 
1188 bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1189                                                    bool Value) const {
1190   bool Unset;
1191   bool Result =
1192       getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1193   if (Unset)
1194     return false;
1195   return Result == Value;
1196 }
1197 bool TreePredicateFn::usesOperands() const {
1198   return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1199 }
1200 bool TreePredicateFn::isLoad() const {
1201   return isPredefinedPredicateEqualTo("IsLoad", true);
1202 }
1203 bool TreePredicateFn::isStore() const {
1204   return isPredefinedPredicateEqualTo("IsStore", true);
1205 }
1206 bool TreePredicateFn::isAtomic() const {
1207   return isPredefinedPredicateEqualTo("IsAtomic", true);
1208 }
1209 bool TreePredicateFn::isUnindexed() const {
1210   return isPredefinedPredicateEqualTo("IsUnindexed", true);
1211 }
1212 bool TreePredicateFn::isNonExtLoad() const {
1213   return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1214 }
1215 bool TreePredicateFn::isAnyExtLoad() const {
1216   return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1217 }
1218 bool TreePredicateFn::isSignExtLoad() const {
1219   return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1220 }
1221 bool TreePredicateFn::isZeroExtLoad() const {
1222   return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1223 }
1224 bool TreePredicateFn::isNonTruncStore() const {
1225   return isPredefinedPredicateEqualTo("IsTruncStore", false);
1226 }
1227 bool TreePredicateFn::isTruncStore() const {
1228   return isPredefinedPredicateEqualTo("IsTruncStore", true);
1229 }
1230 bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1231   return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1232 }
1233 bool TreePredicateFn::isAtomicOrderingAcquire() const {
1234   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1235 }
1236 bool TreePredicateFn::isAtomicOrderingRelease() const {
1237   return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1238 }
1239 bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1240   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1241 }
1242 bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1243   return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1244                                       true);
1245 }
1246 bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1247   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1248 }
1249 bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1250   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1251 }
1252 bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1253   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1254 }
1255 bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1256   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1257 }
1258 Record *TreePredicateFn::getMemoryVT() const {
1259   Record *R = getOrigPatFragRecord()->getRecord();
1260   if (R->isValueUnset("MemoryVT"))
1261     return nullptr;
1262   return R->getValueAsDef("MemoryVT");
1263 }
1264 
1265 ListInit *TreePredicateFn::getAddressSpaces() const {
1266   Record *R = getOrigPatFragRecord()->getRecord();
1267   if (R->isValueUnset("AddressSpaces"))
1268     return nullptr;
1269   return R->getValueAsListInit("AddressSpaces");
1270 }
1271 
1272 int64_t TreePredicateFn::getMinAlignment() const {
1273   Record *R = getOrigPatFragRecord()->getRecord();
1274   if (R->isValueUnset("MinAlignment"))
1275     return 0;
1276   return R->getValueAsInt("MinAlignment");
1277 }
1278 
1279 Record *TreePredicateFn::getScalarMemoryVT() const {
1280   Record *R = getOrigPatFragRecord()->getRecord();
1281   if (R->isValueUnset("ScalarMemoryVT"))
1282     return nullptr;
1283   return R->getValueAsDef("ScalarMemoryVT");
1284 }
1285 bool TreePredicateFn::hasGISelPredicateCode() const {
1286   return !PatFragRec->getRecord()
1287               ->getValueAsString("GISelPredicateCode")
1288               .empty();
1289 }
1290 std::string TreePredicateFn::getGISelPredicateCode() const {
1291   return std::string(
1292       PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
1293 }
1294 
1295 StringRef TreePredicateFn::getImmType() const {
1296   if (immCodeUsesAPInt())
1297     return "const APInt &";
1298   if (immCodeUsesAPFloat())
1299     return "const APFloat &";
1300   return "int64_t";
1301 }
1302 
1303 StringRef TreePredicateFn::getImmTypeIdentifier() const {
1304   if (immCodeUsesAPInt())
1305     return "APInt";
1306   if (immCodeUsesAPFloat())
1307     return "APFloat";
1308   return "I64";
1309 }
1310 
1311 /// isAlwaysTrue - Return true if this is a noop predicate.
1312 bool TreePredicateFn::isAlwaysTrue() const {
1313   return !hasPredCode() && !hasImmCode();
1314 }
1315 
1316 /// Return the name to use in the generated code to reference this, this is
1317 /// "Predicate_foo" if from a pattern fragment "foo".
1318 std::string TreePredicateFn::getFnName() const {
1319   return "Predicate_" + PatFragRec->getRecord()->getName().str();
1320 }
1321 
1322 /// getCodeToRunOnSDNode - Return the code for the function body that
1323 /// evaluates this predicate.  The argument is expected to be in "Node",
1324 /// not N.  This handles casting and conversion to a concrete node type as
1325 /// appropriate.
1326 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1327   // Handle immediate predicates first.
1328   std::string ImmCode = getImmCode();
1329   if (!ImmCode.empty()) {
1330     if (isLoad())
1331       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1332                       "IsLoad cannot be used with ImmLeaf or its subclasses");
1333     if (isStore())
1334       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1335                       "IsStore cannot be used with ImmLeaf or its subclasses");
1336     if (isUnindexed())
1337       PrintFatalError(
1338           getOrigPatFragRecord()->getRecord()->getLoc(),
1339           "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1340     if (isNonExtLoad())
1341       PrintFatalError(
1342           getOrigPatFragRecord()->getRecord()->getLoc(),
1343           "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1344     if (isAnyExtLoad())
1345       PrintFatalError(
1346           getOrigPatFragRecord()->getRecord()->getLoc(),
1347           "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1348     if (isSignExtLoad())
1349       PrintFatalError(
1350           getOrigPatFragRecord()->getRecord()->getLoc(),
1351           "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1352     if (isZeroExtLoad())
1353       PrintFatalError(
1354           getOrigPatFragRecord()->getRecord()->getLoc(),
1355           "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1356     if (isNonTruncStore())
1357       PrintFatalError(
1358           getOrigPatFragRecord()->getRecord()->getLoc(),
1359           "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1360     if (isTruncStore())
1361       PrintFatalError(
1362           getOrigPatFragRecord()->getRecord()->getLoc(),
1363           "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1364     if (getMemoryVT())
1365       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1366                       "MemoryVT cannot be used with ImmLeaf or its subclasses");
1367     if (getScalarMemoryVT())
1368       PrintFatalError(
1369           getOrigPatFragRecord()->getRecord()->getLoc(),
1370           "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1371 
1372     std::string Result = ("    " + getImmType() + " Imm = ").str();
1373     if (immCodeUsesAPFloat())
1374       Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1375     else if (immCodeUsesAPInt())
1376       Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1377     else
1378       Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1379     return Result + ImmCode;
1380   }
1381 
1382   // Handle arbitrary node predicates.
1383   assert(hasPredCode() && "Don't have any predicate code!");
1384 
1385   // If this is using PatFrags, there are multiple trees to search. They should
1386   // all have the same class.  FIXME: Is there a way to find a common
1387   // superclass?
1388   StringRef ClassName;
1389   for (const auto &Tree : PatFragRec->getTrees()) {
1390     StringRef TreeClassName;
1391     if (Tree->isLeaf())
1392       TreeClassName = "SDNode";
1393     else {
1394       Record *Op = Tree->getOperator();
1395       const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
1396       TreeClassName = Info.getSDClassName();
1397     }
1398 
1399     if (ClassName.empty())
1400       ClassName = TreeClassName;
1401     else if (ClassName != TreeClassName) {
1402       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1403                       "PatFrags trees do not have consistent class");
1404     }
1405   }
1406 
1407   std::string Result;
1408   if (ClassName == "SDNode")
1409     Result = "    SDNode *N = Node;\n";
1410   else
1411     Result = "    auto *N = cast<" + ClassName.str() + ">(Node);\n";
1412 
1413   return (Twine(Result) + "    (void)N;\n" + getPredCode()).str();
1414 }
1415 
1416 //===----------------------------------------------------------------------===//
1417 // PatternToMatch implementation
1418 //
1419 
1420 static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
1421   if (!P->isLeaf())
1422     return false;
1423   DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
1424   if (!DI)
1425     return false;
1426 
1427   Record *R = DI->getDef();
1428   return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1429 }
1430 
1431 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1432 /// patterns before small ones.  This is used to determine the size of a
1433 /// pattern.
1434 static unsigned getPatternSize(const TreePatternNode *P,
1435                                const CodeGenDAGPatterns &CGP) {
1436   unsigned Size = 3;  // The node itself.
1437   // If the root node is a ConstantSDNode, increases its size.
1438   // e.g. (set R32:$dst, 0).
1439   if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1440     Size += 2;
1441 
1442   if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1443     Size += AM->getComplexity();
1444     // We don't want to count any children twice, so return early.
1445     return Size;
1446   }
1447 
1448   // If this node has some predicate function that must match, it adds to the
1449   // complexity of this node.
1450   if (!P->getPredicateCalls().empty())
1451     ++Size;
1452 
1453   // Count children in the count if they are also nodes.
1454   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1455     const TreePatternNode *Child = P->getChild(i);
1456     if (!Child->isLeaf() && Child->getNumTypes()) {
1457       const TypeSetByHwMode &T0 = Child->getExtType(0);
1458       // At this point, all variable type sets should be simple, i.e. only
1459       // have a default mode.
1460       if (T0.getMachineValueType() != MVT::Other) {
1461         Size += getPatternSize(Child, CGP);
1462         continue;
1463       }
1464     }
1465     if (Child->isLeaf()) {
1466       if (isa<IntInit>(Child->getLeafValue()))
1467         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
1468       else if (Child->getComplexPatternInfo(CGP))
1469         Size += getPatternSize(Child, CGP);
1470       else if (isImmAllOnesAllZerosMatch(Child))
1471         Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1472       else if (!Child->getPredicateCalls().empty())
1473         ++Size;
1474     }
1475   }
1476 
1477   return Size;
1478 }
1479 
1480 /// Compute the complexity metric for the input pattern.  This roughly
1481 /// corresponds to the number of nodes that are covered.
1482 int PatternToMatch::
1483 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1484   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1485 }
1486 
1487 void PatternToMatch::getPredicateRecords(
1488     SmallVectorImpl<Record *> &PredicateRecs) const {
1489   for (Init *I : Predicates->getValues()) {
1490     if (DefInit *Pred = dyn_cast<DefInit>(I)) {
1491       Record *Def = Pred->getDef();
1492       if (!Def->isSubClassOf("Predicate")) {
1493 #ifndef NDEBUG
1494         Def->dump();
1495 #endif
1496         llvm_unreachable("Unknown predicate type!");
1497       }
1498       PredicateRecs.push_back(Def);
1499     }
1500   }
1501   // Sort so that different orders get canonicalized to the same string.
1502   llvm::sort(PredicateRecs, LessRecord());
1503 }
1504 
1505 /// getPredicateCheck - Return a single string containing all of this
1506 /// pattern's predicates concatenated with "&&" operators.
1507 ///
1508 std::string PatternToMatch::getPredicateCheck() const {
1509   SmallVector<Record *, 4> PredicateRecs;
1510   getPredicateRecords(PredicateRecs);
1511 
1512   SmallString<128> PredicateCheck;
1513   for (Record *Pred : PredicateRecs) {
1514     StringRef CondString = Pred->getValueAsString("CondString");
1515     if (CondString.empty())
1516       continue;
1517     if (!PredicateCheck.empty())
1518       PredicateCheck += " && ";
1519     PredicateCheck += "(";
1520     PredicateCheck += CondString;
1521     PredicateCheck += ")";
1522   }
1523 
1524   if (!HwModeFeatures.empty()) {
1525     if (!PredicateCheck.empty())
1526       PredicateCheck += " && ";
1527     PredicateCheck += HwModeFeatures;
1528   }
1529 
1530   return std::string(PredicateCheck);
1531 }
1532 
1533 //===----------------------------------------------------------------------===//
1534 // SDTypeConstraint implementation
1535 //
1536 
1537 SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1538   OperandNo = R->getValueAsInt("OperandNum");
1539 
1540   if (R->isSubClassOf("SDTCisVT")) {
1541     ConstraintType = SDTCisVT;
1542     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1543     for (const auto &P : VVT)
1544       if (P.second == MVT::isVoid)
1545         PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1546   } else if (R->isSubClassOf("SDTCisPtrTy")) {
1547     ConstraintType = SDTCisPtrTy;
1548   } else if (R->isSubClassOf("SDTCisInt")) {
1549     ConstraintType = SDTCisInt;
1550   } else if (R->isSubClassOf("SDTCisFP")) {
1551     ConstraintType = SDTCisFP;
1552   } else if (R->isSubClassOf("SDTCisVec")) {
1553     ConstraintType = SDTCisVec;
1554   } else if (R->isSubClassOf("SDTCisSameAs")) {
1555     ConstraintType = SDTCisSameAs;
1556     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1557   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1558     ConstraintType = SDTCisVTSmallerThanOp;
1559     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1560       R->getValueAsInt("OtherOperandNum");
1561   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1562     ConstraintType = SDTCisOpSmallerThanOp;
1563     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1564       R->getValueAsInt("BigOperandNum");
1565   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1566     ConstraintType = SDTCisEltOfVec;
1567     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1568   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1569     ConstraintType = SDTCisSubVecOfVec;
1570     x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1571       R->getValueAsInt("OtherOpNum");
1572   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1573     ConstraintType = SDTCVecEltisVT;
1574     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1575     for (const auto &P : VVT) {
1576       MVT T = P.second;
1577       if (T.isVector())
1578         PrintFatalError(R->getLoc(),
1579                         "Cannot use vector type as SDTCVecEltisVT");
1580       if (!T.isInteger() && !T.isFloatingPoint())
1581         PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1582                                      "as SDTCVecEltisVT");
1583     }
1584   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1585     ConstraintType = SDTCisSameNumEltsAs;
1586     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1587       R->getValueAsInt("OtherOperandNum");
1588   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1589     ConstraintType = SDTCisSameSizeAs;
1590     x.SDTCisSameSizeAs_Info.OtherOperandNum =
1591       R->getValueAsInt("OtherOperandNum");
1592   } else {
1593     PrintFatalError(R->getLoc(),
1594                     "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1595   }
1596 }
1597 
1598 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1599 /// N, and the result number in ResNo.
1600 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1601                                       const SDNodeInfo &NodeInfo,
1602                                       unsigned &ResNo) {
1603   unsigned NumResults = NodeInfo.getNumResults();
1604   if (OpNo < NumResults) {
1605     ResNo = OpNo;
1606     return N;
1607   }
1608 
1609   OpNo -= NumResults;
1610 
1611   if (OpNo >= N->getNumChildren()) {
1612     std::string S;
1613     raw_string_ostream OS(S);
1614     OS << "Invalid operand number in type constraint "
1615            << (OpNo+NumResults) << " ";
1616     N->print(OS);
1617     PrintFatalError(S);
1618   }
1619 
1620   return N->getChild(OpNo);
1621 }
1622 
1623 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1624 /// constraint to the nodes operands.  This returns true if it makes a
1625 /// change, false otherwise.  If a type contradiction is found, flag an error.
1626 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1627                                            const SDNodeInfo &NodeInfo,
1628                                            TreePattern &TP) const {
1629   if (TP.hasError())
1630     return false;
1631 
1632   unsigned ResNo = 0; // The result number being referenced.
1633   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1634   TypeInfer &TI = TP.getInfer();
1635 
1636   switch (ConstraintType) {
1637   case SDTCisVT:
1638     // Operand must be a particular type.
1639     return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1640   case SDTCisPtrTy:
1641     // Operand must be same as target pointer type.
1642     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1643   case SDTCisInt:
1644     // Require it to be one of the legal integer VTs.
1645      return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1646   case SDTCisFP:
1647     // Require it to be one of the legal fp VTs.
1648     return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1649   case SDTCisVec:
1650     // Require it to be one of the legal vector VTs.
1651     return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1652   case SDTCisSameAs: {
1653     unsigned OResNo = 0;
1654     TreePatternNode *OtherNode =
1655       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1656     return (int)NodeToApply->UpdateNodeType(ResNo,
1657                                             OtherNode->getExtType(OResNo), TP) |
1658            (int)OtherNode->UpdateNodeType(OResNo,
1659                                           NodeToApply->getExtType(ResNo), TP);
1660   }
1661   case SDTCisVTSmallerThanOp: {
1662     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1663     // have an integer type that is smaller than the VT.
1664     if (!NodeToApply->isLeaf() ||
1665         !isa<DefInit>(NodeToApply->getLeafValue()) ||
1666         !cast<DefInit>(NodeToApply->getLeafValue())->getDef()
1667                ->isSubClassOf("ValueType")) {
1668       TP.error(N->getOperator()->getName() + " expects a VT operand!");
1669       return false;
1670     }
1671     DefInit *DI = cast<DefInit>(NodeToApply->getLeafValue());
1672     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1673     auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1674     TypeSetByHwMode TypeListTmp(VVT);
1675 
1676     unsigned OResNo = 0;
1677     TreePatternNode *OtherNode =
1678       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1679                     OResNo);
1680 
1681     return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo),
1682                                  /*SmallIsVT*/ true);
1683   }
1684   case SDTCisOpSmallerThanOp: {
1685     unsigned BResNo = 0;
1686     TreePatternNode *BigOperand =
1687       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1688                     BResNo);
1689     return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1690                                  BigOperand->getExtType(BResNo));
1691   }
1692   case SDTCisEltOfVec: {
1693     unsigned VResNo = 0;
1694     TreePatternNode *VecOperand =
1695       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1696                     VResNo);
1697     // Filter vector types out of VecOperand that don't have the right element
1698     // type.
1699     return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1700                                      NodeToApply->getExtType(ResNo));
1701   }
1702   case SDTCisSubVecOfVec: {
1703     unsigned VResNo = 0;
1704     TreePatternNode *BigVecOperand =
1705       getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1706                     VResNo);
1707 
1708     // Filter vector types out of BigVecOperand that don't have the
1709     // right subvector type.
1710     return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1711                                            NodeToApply->getExtType(ResNo));
1712   }
1713   case SDTCVecEltisVT: {
1714     return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1715   }
1716   case SDTCisSameNumEltsAs: {
1717     unsigned OResNo = 0;
1718     TreePatternNode *OtherNode =
1719       getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1720                     N, NodeInfo, OResNo);
1721     return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1722                                  NodeToApply->getExtType(ResNo));
1723   }
1724   case SDTCisSameSizeAs: {
1725     unsigned OResNo = 0;
1726     TreePatternNode *OtherNode =
1727       getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1728                     N, NodeInfo, OResNo);
1729     return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1730                               NodeToApply->getExtType(ResNo));
1731   }
1732   }
1733   llvm_unreachable("Invalid ConstraintType!");
1734 }
1735 
1736 // Update the node type to match an instruction operand or result as specified
1737 // in the ins or outs lists on the instruction definition. Return true if the
1738 // type was actually changed.
1739 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1740                                              Record *Operand,
1741                                              TreePattern &TP) {
1742   // The 'unknown' operand indicates that types should be inferred from the
1743   // context.
1744   if (Operand->isSubClassOf("unknown_class"))
1745     return false;
1746 
1747   // The Operand class specifies a type directly.
1748   if (Operand->isSubClassOf("Operand")) {
1749     Record *R = Operand->getValueAsDef("Type");
1750     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1751     return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1752   }
1753 
1754   // PointerLikeRegClass has a type that is determined at runtime.
1755   if (Operand->isSubClassOf("PointerLikeRegClass"))
1756     return UpdateNodeType(ResNo, MVT::iPTR, TP);
1757 
1758   // Both RegisterClass and RegisterOperand operands derive their types from a
1759   // register class def.
1760   Record *RC = nullptr;
1761   if (Operand->isSubClassOf("RegisterClass"))
1762     RC = Operand;
1763   else if (Operand->isSubClassOf("RegisterOperand"))
1764     RC = Operand->getValueAsDef("RegClass");
1765 
1766   assert(RC && "Unknown operand type");
1767   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1768   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1769 }
1770 
1771 bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1772   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1773     if (!TP.getInfer().isConcrete(Types[i], true))
1774       return true;
1775   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1776     if (getChild(i)->ContainsUnresolvedType(TP))
1777       return true;
1778   return false;
1779 }
1780 
1781 bool TreePatternNode::hasProperTypeByHwMode() const {
1782   for (const TypeSetByHwMode &S : Types)
1783     if (!S.isDefaultOnly())
1784       return true;
1785   for (const TreePatternNodePtr &C : Children)
1786     if (C->hasProperTypeByHwMode())
1787       return true;
1788   return false;
1789 }
1790 
1791 bool TreePatternNode::hasPossibleType() const {
1792   for (const TypeSetByHwMode &S : Types)
1793     if (!S.isPossible())
1794       return false;
1795   for (const TreePatternNodePtr &C : Children)
1796     if (!C->hasPossibleType())
1797       return false;
1798   return true;
1799 }
1800 
1801 bool TreePatternNode::setDefaultMode(unsigned Mode) {
1802   for (TypeSetByHwMode &S : Types) {
1803     S.makeSimple(Mode);
1804     // Check if the selected mode had a type conflict.
1805     if (S.get(DefaultMode).empty())
1806       return false;
1807   }
1808   for (const TreePatternNodePtr &C : Children)
1809     if (!C->setDefaultMode(Mode))
1810       return false;
1811   return true;
1812 }
1813 
1814 //===----------------------------------------------------------------------===//
1815 // SDNodeInfo implementation
1816 //
1817 SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1818   EnumName    = R->getValueAsString("Opcode");
1819   SDClassName = R->getValueAsString("SDClass");
1820   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1821   NumResults = TypeProfile->getValueAsInt("NumResults");
1822   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1823 
1824   // Parse the properties.
1825   Properties = parseSDPatternOperatorProperties(R);
1826 
1827   // Parse the type constraints.
1828   std::vector<Record*> ConstraintList =
1829     TypeProfile->getValueAsListOfDefs("Constraints");
1830   for (Record *R : ConstraintList)
1831     TypeConstraints.emplace_back(R, CGH);
1832 }
1833 
1834 /// getKnownType - If the type constraints on this node imply a fixed type
1835 /// (e.g. all stores return void, etc), then return it as an
1836 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
1837 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1838   unsigned NumResults = getNumResults();
1839   assert(NumResults <= 1 &&
1840          "We only work with nodes with zero or one result so far!");
1841   assert(ResNo == 0 && "Only handles single result nodes so far");
1842 
1843   for (const SDTypeConstraint &Constraint : TypeConstraints) {
1844     // Make sure that this applies to the correct node result.
1845     if (Constraint.OperandNo >= NumResults)  // FIXME: need value #
1846       continue;
1847 
1848     switch (Constraint.ConstraintType) {
1849     default: break;
1850     case SDTypeConstraint::SDTCisVT:
1851       if (Constraint.VVT.isSimple())
1852         return Constraint.VVT.getSimple().SimpleTy;
1853       break;
1854     case SDTypeConstraint::SDTCisPtrTy:
1855       return MVT::iPTR;
1856     }
1857   }
1858   return MVT::Other;
1859 }
1860 
1861 //===----------------------------------------------------------------------===//
1862 // TreePatternNode implementation
1863 //
1864 
1865 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1866   if (Operator->getName() == "set" ||
1867       Operator->getName() == "implicit")
1868     return 0;  // All return nothing.
1869 
1870   if (Operator->isSubClassOf("Intrinsic"))
1871     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1872 
1873   if (Operator->isSubClassOf("SDNode"))
1874     return CDP.getSDNodeInfo(Operator).getNumResults();
1875 
1876   if (Operator->isSubClassOf("PatFrags")) {
1877     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1878     // the forward reference case where one pattern fragment references another
1879     // before it is processed.
1880     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1881       // The number of results of a fragment with alternative records is the
1882       // maximum number of results across all alternatives.
1883       unsigned NumResults = 0;
1884       for (const auto &T : PFRec->getTrees())
1885         NumResults = std::max(NumResults, T->getNumTypes());
1886       return NumResults;
1887     }
1888 
1889     ListInit *LI = Operator->getValueAsListInit("Fragments");
1890     assert(LI && "Invalid Fragment");
1891     unsigned NumResults = 0;
1892     for (Init *I : LI->getValues()) {
1893       Record *Op = nullptr;
1894       if (DagInit *Dag = dyn_cast<DagInit>(I))
1895         if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1896           Op = DI->getDef();
1897       assert(Op && "Invalid Fragment");
1898       NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1899     }
1900     return NumResults;
1901   }
1902 
1903   if (Operator->isSubClassOf("Instruction")) {
1904     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1905 
1906     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1907 
1908     // Subtract any defaulted outputs.
1909     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1910       Record *OperandNode = InstInfo.Operands[i].Rec;
1911 
1912       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1913           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1914         --NumDefsToAdd;
1915     }
1916 
1917     // Add on one implicit def if it has a resolvable type.
1918     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1919       ++NumDefsToAdd;
1920     return NumDefsToAdd;
1921   }
1922 
1923   if (Operator->isSubClassOf("SDNodeXForm"))
1924     return 1;  // FIXME: Generalize SDNodeXForm
1925 
1926   if (Operator->isSubClassOf("ValueType"))
1927     return 1;  // A type-cast of one result.
1928 
1929   if (Operator->isSubClassOf("ComplexPattern"))
1930     return 1;
1931 
1932   errs() << *Operator;
1933   PrintFatalError("Unhandled node in GetNumNodeResults");
1934 }
1935 
1936 void TreePatternNode::print(raw_ostream &OS) const {
1937   if (isLeaf())
1938     OS << *getLeafValue();
1939   else
1940     OS << '(' << getOperator()->getName();
1941 
1942   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1943     OS << ':';
1944     getExtType(i).writeToStream(OS);
1945   }
1946 
1947   if (!isLeaf()) {
1948     if (getNumChildren() != 0) {
1949       OS << " ";
1950       ListSeparator LS;
1951       for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1952         OS << LS;
1953         getChild(i)->print(OS);
1954       }
1955     }
1956     OS << ")";
1957   }
1958 
1959   for (const TreePredicateCall &Pred : PredicateCalls) {
1960     OS << "<<P:";
1961     if (Pred.Scope)
1962       OS << Pred.Scope << ":";
1963     OS << Pred.Fn.getFnName() << ">>";
1964   }
1965   if (TransformFn)
1966     OS << "<<X:" << TransformFn->getName() << ">>";
1967   if (!getName().empty())
1968     OS << ":$" << getName();
1969 
1970   for (const ScopedName &Name : NamesAsPredicateArg)
1971     OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
1972 }
1973 void TreePatternNode::dump() const {
1974   print(errs());
1975 }
1976 
1977 /// isIsomorphicTo - Return true if this node is recursively
1978 /// isomorphic to the specified node.  For this comparison, the node's
1979 /// entire state is considered. The assigned name is ignored, since
1980 /// nodes with differing names are considered isomorphic. However, if
1981 /// the assigned name is present in the dependent variable set, then
1982 /// the assigned name is considered significant and the node is
1983 /// isomorphic if the names match.
1984 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1985                                      const MultipleUseVarSet &DepVars) const {
1986   if (N == this) return true;
1987   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1988       getPredicateCalls() != N->getPredicateCalls() ||
1989       getTransformFn() != N->getTransformFn())
1990     return false;
1991 
1992   if (isLeaf()) {
1993     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1994       if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1995         return ((DI->getDef() == NDI->getDef())
1996                 && (DepVars.find(getName()) == DepVars.end()
1997                     || getName() == N->getName()));
1998       }
1999     }
2000     return getLeafValue() == N->getLeafValue();
2001   }
2002 
2003   if (N->getOperator() != getOperator() ||
2004       N->getNumChildren() != getNumChildren()) return false;
2005   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2006     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
2007       return false;
2008   return true;
2009 }
2010 
2011 /// clone - Make a copy of this tree and all of its children.
2012 ///
2013 TreePatternNodePtr TreePatternNode::clone() const {
2014   TreePatternNodePtr New;
2015   if (isLeaf()) {
2016     New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
2017   } else {
2018     std::vector<TreePatternNodePtr> CChildren;
2019     CChildren.reserve(Children.size());
2020     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2021       CChildren.push_back(getChild(i)->clone());
2022     New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
2023                                             getNumTypes());
2024   }
2025   New->setName(getName());
2026   New->setNamesAsPredicateArg(getNamesAsPredicateArg());
2027   New->Types = Types;
2028   New->setPredicateCalls(getPredicateCalls());
2029   New->setTransformFn(getTransformFn());
2030   return New;
2031 }
2032 
2033 /// RemoveAllTypes - Recursively strip all the types of this tree.
2034 void TreePatternNode::RemoveAllTypes() {
2035   // Reset to unknown type.
2036   std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
2037   if (isLeaf()) return;
2038   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2039     getChild(i)->RemoveAllTypes();
2040 }
2041 
2042 
2043 /// SubstituteFormalArguments - Replace the formal arguments in this tree
2044 /// with actual values specified by ArgMap.
2045 void TreePatternNode::SubstituteFormalArguments(
2046     std::map<std::string, TreePatternNodePtr> &ArgMap) {
2047   if (isLeaf()) return;
2048 
2049   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2050     TreePatternNode *Child = getChild(i);
2051     if (Child->isLeaf()) {
2052       Init *Val = Child->getLeafValue();
2053       // Note that, when substituting into an output pattern, Val might be an
2054       // UnsetInit.
2055       if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
2056           cast<DefInit>(Val)->getDef()->getName() == "node")) {
2057         // We found a use of a formal argument, replace it with its value.
2058         TreePatternNodePtr NewChild = ArgMap[Child->getName()];
2059         assert(NewChild && "Couldn't find formal argument!");
2060         assert((Child->getPredicateCalls().empty() ||
2061                 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
2062                "Non-empty child predicate clobbered!");
2063         setChild(i, std::move(NewChild));
2064       }
2065     } else {
2066       getChild(i)->SubstituteFormalArguments(ArgMap);
2067     }
2068   }
2069 }
2070 
2071 
2072 /// InlinePatternFragments - If this pattern refers to any pattern
2073 /// fragments, return the set of inlined versions (this can be more than
2074 /// one if a PatFrags record has multiple alternatives).
2075 void TreePatternNode::InlinePatternFragments(
2076   TreePatternNodePtr T, TreePattern &TP,
2077   std::vector<TreePatternNodePtr> &OutAlternatives) {
2078 
2079   if (TP.hasError())
2080     return;
2081 
2082   if (isLeaf()) {
2083     OutAlternatives.push_back(T);  // nothing to do.
2084     return;
2085   }
2086 
2087   Record *Op = getOperator();
2088 
2089   if (!Op->isSubClassOf("PatFrags")) {
2090     if (getNumChildren() == 0) {
2091       OutAlternatives.push_back(T);
2092       return;
2093     }
2094 
2095     // Recursively inline children nodes.
2096     std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
2097     ChildAlternatives.resize(getNumChildren());
2098     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2099       TreePatternNodePtr Child = getChildShared(i);
2100       Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
2101       // If there are no alternatives for any child, there are no
2102       // alternatives for this expression as whole.
2103       if (ChildAlternatives[i].empty())
2104         return;
2105 
2106       assert((Child->getPredicateCalls().empty() ||
2107               llvm::all_of(ChildAlternatives[i],
2108                            [&](const TreePatternNodePtr &NewChild) {
2109                              return NewChild->getPredicateCalls() ==
2110                                     Child->getPredicateCalls();
2111                            })) &&
2112              "Non-empty child predicate clobbered!");
2113     }
2114 
2115     // The end result is an all-pairs construction of the resultant pattern.
2116     std::vector<unsigned> Idxs;
2117     Idxs.resize(ChildAlternatives.size());
2118     bool NotDone;
2119     do {
2120       // Create the variant and add it to the output list.
2121       std::vector<TreePatternNodePtr> NewChildren;
2122       for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2123         NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
2124       TreePatternNodePtr R = std::make_shared<TreePatternNode>(
2125           getOperator(), std::move(NewChildren), getNumTypes());
2126 
2127       // Copy over properties.
2128       R->setName(getName());
2129       R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2130       R->setPredicateCalls(getPredicateCalls());
2131       R->setTransformFn(getTransformFn());
2132       for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2133         R->setType(i, getExtType(i));
2134       for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2135         R->setResultIndex(i, getResultIndex(i));
2136 
2137       // Register alternative.
2138       OutAlternatives.push_back(R);
2139 
2140       // Increment indices to the next permutation by incrementing the
2141       // indices from last index backward, e.g., generate the sequence
2142       // [0, 0], [0, 1], [1, 0], [1, 1].
2143       int IdxsIdx;
2144       for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2145         if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2146           Idxs[IdxsIdx] = 0;
2147         else
2148           break;
2149       }
2150       NotDone = (IdxsIdx >= 0);
2151     } while (NotDone);
2152 
2153     return;
2154   }
2155 
2156   // Otherwise, we found a reference to a fragment.  First, look up its
2157   // TreePattern record.
2158   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
2159 
2160   // Verify that we are passing the right number of operands.
2161   if (Frag->getNumArgs() != Children.size()) {
2162     TP.error("'" + Op->getName() + "' fragment requires " +
2163              Twine(Frag->getNumArgs()) + " operands!");
2164     return;
2165   }
2166 
2167   TreePredicateFn PredFn(Frag);
2168   unsigned Scope = 0;
2169   if (TreePredicateFn(Frag).usesOperands())
2170     Scope = TP.getDAGPatterns().allocateScope();
2171 
2172   // Compute the map of formal to actual arguments.
2173   std::map<std::string, TreePatternNodePtr> ArgMap;
2174   for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2175     TreePatternNodePtr Child = getChildShared(i);
2176     if (Scope != 0) {
2177       Child = Child->clone();
2178       Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2179     }
2180     ArgMap[Frag->getArgName(i)] = Child;
2181   }
2182 
2183   // Loop over all fragment alternatives.
2184   for (const auto &Alternative : Frag->getTrees()) {
2185     TreePatternNodePtr FragTree = Alternative->clone();
2186 
2187     if (!PredFn.isAlwaysTrue())
2188       FragTree->addPredicateCall(PredFn, Scope);
2189 
2190     // Resolve formal arguments to their actual value.
2191     if (Frag->getNumArgs())
2192       FragTree->SubstituteFormalArguments(ArgMap);
2193 
2194     // Transfer types.  Note that the resolved alternative may have fewer
2195     // (but not more) results than the PatFrags node.
2196     FragTree->setName(getName());
2197     for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2198       FragTree->UpdateNodeType(i, getExtType(i), TP);
2199 
2200     // Transfer in the old predicates.
2201     for (const TreePredicateCall &Pred : getPredicateCalls())
2202       FragTree->addPredicateCall(Pred);
2203 
2204     // The fragment we inlined could have recursive inlining that is needed.  See
2205     // if there are any pattern fragments in it and inline them as needed.
2206     FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2207   }
2208 }
2209 
2210 /// getImplicitType - Check to see if the specified record has an implicit
2211 /// type which should be applied to it.  This will infer the type of register
2212 /// references from the register file information, for example.
2213 ///
2214 /// When Unnamed is set, return the type of a DAG operand with no name, such as
2215 /// the F8RC register class argument in:
2216 ///
2217 ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
2218 ///
2219 /// When Unnamed is false, return the type of a named DAG operand such as the
2220 /// GPR:$src operand above.
2221 ///
2222 static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2223                                        bool NotRegisters,
2224                                        bool Unnamed,
2225                                        TreePattern &TP) {
2226   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2227 
2228   // Check to see if this is a register operand.
2229   if (R->isSubClassOf("RegisterOperand")) {
2230     assert(ResNo == 0 && "Regoperand ref only has one result!");
2231     if (NotRegisters)
2232       return TypeSetByHwMode(); // Unknown.
2233     Record *RegClass = R->getValueAsDef("RegClass");
2234     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2235     return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
2236   }
2237 
2238   // Check to see if this is a register or a register class.
2239   if (R->isSubClassOf("RegisterClass")) {
2240     assert(ResNo == 0 && "Regclass ref only has one result!");
2241     // An unnamed register class represents itself as an i32 immediate, for
2242     // example on a COPY_TO_REGCLASS instruction.
2243     if (Unnamed)
2244       return TypeSetByHwMode(MVT::i32);
2245 
2246     // In a named operand, the register class provides the possible set of
2247     // types.
2248     if (NotRegisters)
2249       return TypeSetByHwMode(); // Unknown.
2250     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2251     return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2252   }
2253 
2254   if (R->isSubClassOf("PatFrags")) {
2255     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2256     // Pattern fragment types will be resolved when they are inlined.
2257     return TypeSetByHwMode(); // Unknown.
2258   }
2259 
2260   if (R->isSubClassOf("Register")) {
2261     assert(ResNo == 0 && "Registers only produce one result!");
2262     if (NotRegisters)
2263       return TypeSetByHwMode(); // Unknown.
2264     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2265     return TypeSetByHwMode(T.getRegisterVTs(R));
2266   }
2267 
2268   if (R->isSubClassOf("SubRegIndex")) {
2269     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2270     return TypeSetByHwMode(MVT::i32);
2271   }
2272 
2273   if (R->isSubClassOf("ValueType")) {
2274     assert(ResNo == 0 && "This node only has one result!");
2275     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2276     //
2277     //   (sext_inreg GPR:$src, i16)
2278     //                         ~~~
2279     if (Unnamed)
2280       return TypeSetByHwMode(MVT::Other);
2281     // With a name, the ValueType simply provides the type of the named
2282     // variable.
2283     //
2284     //   (sext_inreg i32:$src, i16)
2285     //               ~~~~~~~~
2286     if (NotRegisters)
2287       return TypeSetByHwMode(); // Unknown.
2288     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2289     return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
2290   }
2291 
2292   if (R->isSubClassOf("CondCode")) {
2293     assert(ResNo == 0 && "This node only has one result!");
2294     // Using a CondCodeSDNode.
2295     return TypeSetByHwMode(MVT::Other);
2296   }
2297 
2298   if (R->isSubClassOf("ComplexPattern")) {
2299     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2300     if (NotRegisters)
2301       return TypeSetByHwMode(); // Unknown.
2302     Record *T = CDP.getComplexPattern(R).getValueType();
2303     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2304     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2305   }
2306   if (R->isSubClassOf("PointerLikeRegClass")) {
2307     assert(ResNo == 0 && "Regclass can only have one result!");
2308     TypeSetByHwMode VTS(MVT::iPTR);
2309     TP.getInfer().expandOverloads(VTS);
2310     return VTS;
2311   }
2312 
2313   if (R->getName() == "node" || R->getName() == "srcvalue" ||
2314       R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2315       R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2316     // Placeholder.
2317     return TypeSetByHwMode(); // Unknown.
2318   }
2319 
2320   if (R->isSubClassOf("Operand")) {
2321     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2322     Record *T = R->getValueAsDef("Type");
2323     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2324   }
2325 
2326   TP.error("Unknown node flavor used in pattern: " + R->getName());
2327   return TypeSetByHwMode(MVT::Other);
2328 }
2329 
2330 
2331 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2332 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2333 const CodeGenIntrinsic *TreePatternNode::
2334 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2335   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2336       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2337       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2338     return nullptr;
2339 
2340   unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2341   return &CDP.getIntrinsicInfo(IID);
2342 }
2343 
2344 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2345 /// return the ComplexPattern information, otherwise return null.
2346 const ComplexPattern *
2347 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2348   Record *Rec;
2349   if (isLeaf()) {
2350     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2351     if (!DI)
2352       return nullptr;
2353     Rec = DI->getDef();
2354   } else
2355     Rec = getOperator();
2356 
2357   if (!Rec->isSubClassOf("ComplexPattern"))
2358     return nullptr;
2359   return &CGP.getComplexPattern(Rec);
2360 }
2361 
2362 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2363   // A ComplexPattern specifically declares how many results it fills in.
2364   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2365     return CP->getNumOperands();
2366 
2367   // If MIOperandInfo is specified, that gives the count.
2368   if (isLeaf()) {
2369     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2370     if (DI && DI->getDef()->isSubClassOf("Operand")) {
2371       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2372       if (MIOps->getNumArgs())
2373         return MIOps->getNumArgs();
2374     }
2375   }
2376 
2377   // Otherwise there is just one result.
2378   return 1;
2379 }
2380 
2381 /// NodeHasProperty - Return true if this node has the specified property.
2382 bool TreePatternNode::NodeHasProperty(SDNP Property,
2383                                       const CodeGenDAGPatterns &CGP) const {
2384   if (isLeaf()) {
2385     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2386       return CP->hasProperty(Property);
2387 
2388     return false;
2389   }
2390 
2391   if (Property != SDNPHasChain) {
2392     // The chain proprety is already present on the different intrinsic node
2393     // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2394     // on the intrinsic. Anything else is specific to the individual intrinsic.
2395     if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2396       return Int->hasProperty(Property);
2397   }
2398 
2399   if (!Operator->isSubClassOf("SDPatternOperator"))
2400     return false;
2401 
2402   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2403 }
2404 
2405 
2406 
2407 
2408 /// TreeHasProperty - Return true if any node in this tree has the specified
2409 /// property.
2410 bool TreePatternNode::TreeHasProperty(SDNP Property,
2411                                       const CodeGenDAGPatterns &CGP) const {
2412   if (NodeHasProperty(Property, CGP))
2413     return true;
2414   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2415     if (getChild(i)->TreeHasProperty(Property, CGP))
2416       return true;
2417   return false;
2418 }
2419 
2420 /// isCommutativeIntrinsic - Return true if the node corresponds to a
2421 /// commutative intrinsic.
2422 bool
2423 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2424   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2425     return Int->isCommutative;
2426   return false;
2427 }
2428 
2429 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2430   if (!N->isLeaf())
2431     return N->getOperator()->isSubClassOf(Class);
2432 
2433   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2434   if (DI && DI->getDef()->isSubClassOf(Class))
2435     return true;
2436 
2437   return false;
2438 }
2439 
2440 static void emitTooManyOperandsError(TreePattern &TP,
2441                                      StringRef InstName,
2442                                      unsigned Expected,
2443                                      unsigned Actual) {
2444   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2445            " operands but expected only " + Twine(Expected) + "!");
2446 }
2447 
2448 static void emitTooFewOperandsError(TreePattern &TP,
2449                                     StringRef InstName,
2450                                     unsigned Actual) {
2451   TP.error("Instruction '" + InstName +
2452            "' expects more than the provided " + Twine(Actual) + " operands!");
2453 }
2454 
2455 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2456 /// this node and its children in the tree.  This returns true if it makes a
2457 /// change, false otherwise.  If a type contradiction is found, flag an error.
2458 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2459   if (TP.hasError())
2460     return false;
2461 
2462   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2463   if (isLeaf()) {
2464     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2465       // If it's a regclass or something else known, include the type.
2466       bool MadeChange = false;
2467       for (unsigned i = 0, e = Types.size(); i != e; ++i)
2468         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2469                                                         NotRegisters,
2470                                                         !hasName(), TP), TP);
2471       return MadeChange;
2472     }
2473 
2474     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2475       assert(Types.size() == 1 && "Invalid IntInit");
2476 
2477       // Int inits are always integers. :)
2478       bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2479 
2480       if (!TP.getInfer().isConcrete(Types[0], false))
2481         return MadeChange;
2482 
2483       ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2484       for (auto &P : VVT) {
2485         MVT::SimpleValueType VT = P.second.SimpleTy;
2486         if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2487           continue;
2488         unsigned Size = MVT(VT).getFixedSizeInBits();
2489         // Make sure that the value is representable for this type.
2490         if (Size >= 32)
2491           continue;
2492         // Check that the value doesn't use more bits than we have. It must
2493         // either be a sign- or zero-extended equivalent of the original.
2494         int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2495         if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2496             SignBitAndAbove == 1)
2497           continue;
2498 
2499         TP.error("Integer value '" + Twine(II->getValue()) +
2500                  "' is out of range for type '" + getEnumName(VT) + "'!");
2501         break;
2502       }
2503       return MadeChange;
2504     }
2505 
2506     return false;
2507   }
2508 
2509   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2510     bool MadeChange = false;
2511 
2512     // Apply the result type to the node.
2513     unsigned NumRetVTs = Int->IS.RetVTs.size();
2514     unsigned NumParamVTs = Int->IS.ParamVTs.size();
2515 
2516     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2517       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2518 
2519     if (getNumChildren() != NumParamVTs + 1) {
2520       TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2521                " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2522       return false;
2523     }
2524 
2525     // Apply type info to the intrinsic ID.
2526     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2527 
2528     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2529       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2530 
2531       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2532       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2533       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2534     }
2535     return MadeChange;
2536   }
2537 
2538   if (getOperator()->isSubClassOf("SDNode")) {
2539     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2540 
2541     // Check that the number of operands is sane.  Negative operands -> varargs.
2542     if (NI.getNumOperands() >= 0 &&
2543         getNumChildren() != (unsigned)NI.getNumOperands()) {
2544       TP.error(getOperator()->getName() + " node requires exactly " +
2545                Twine(NI.getNumOperands()) + " operands!");
2546       return false;
2547     }
2548 
2549     bool MadeChange = false;
2550     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2551       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2552     MadeChange |= NI.ApplyTypeConstraints(this, TP);
2553     return MadeChange;
2554   }
2555 
2556   if (getOperator()->isSubClassOf("Instruction")) {
2557     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2558     CodeGenInstruction &InstInfo =
2559       CDP.getTargetInfo().getInstruction(getOperator());
2560 
2561     bool MadeChange = false;
2562 
2563     // Apply the result types to the node, these come from the things in the
2564     // (outs) list of the instruction.
2565     unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2566                                         Inst.getNumResults());
2567     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2568       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2569 
2570     // If the instruction has implicit defs, we apply the first one as a result.
2571     // FIXME: This sucks, it should apply all implicit defs.
2572     if (!InstInfo.ImplicitDefs.empty()) {
2573       unsigned ResNo = NumResultsToAdd;
2574 
2575       // FIXME: Generalize to multiple possible types and multiple possible
2576       // ImplicitDefs.
2577       MVT::SimpleValueType VT =
2578         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2579 
2580       if (VT != MVT::Other)
2581         MadeChange |= UpdateNodeType(ResNo, VT, TP);
2582     }
2583 
2584     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2585     // be the same.
2586     if (getOperator()->getName() == "INSERT_SUBREG") {
2587       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2588       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2589       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
2590     } else if (getOperator()->getName() == "REG_SEQUENCE") {
2591       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2592       // variadic.
2593 
2594       unsigned NChild = getNumChildren();
2595       if (NChild < 3) {
2596         TP.error("REG_SEQUENCE requires at least 3 operands!");
2597         return false;
2598       }
2599 
2600       if (NChild % 2 == 0) {
2601         TP.error("REG_SEQUENCE requires an odd number of operands!");
2602         return false;
2603       }
2604 
2605       if (!isOperandClass(getChild(0), "RegisterClass")) {
2606         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2607         return false;
2608       }
2609 
2610       for (unsigned I = 1; I < NChild; I += 2) {
2611         TreePatternNode *SubIdxChild = getChild(I + 1);
2612         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2613           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2614                    Twine(I + 1) + "!");
2615           return false;
2616         }
2617       }
2618     }
2619 
2620     unsigned NumResults = Inst.getNumResults();
2621     unsigned NumFixedOperands = InstInfo.Operands.size();
2622 
2623     // If one or more operands with a default value appear at the end of the
2624     // formal operand list for an instruction, we allow them to be overridden
2625     // by optional operands provided in the pattern.
2626     //
2627     // But if an operand B without a default appears at any point after an
2628     // operand A with a default, then we don't allow A to be overridden,
2629     // because there would be no way to specify whether the next operand in
2630     // the pattern was intended to override A or skip it.
2631     unsigned NonOverridableOperands = NumFixedOperands;
2632     while (NonOverridableOperands > NumResults &&
2633            CDP.operandHasDefault(InstInfo.Operands[NonOverridableOperands-1].Rec))
2634       --NonOverridableOperands;
2635 
2636     unsigned ChildNo = 0;
2637     assert(NumResults <= NumFixedOperands);
2638     for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2639       Record *OperandNode = InstInfo.Operands[i].Rec;
2640 
2641       // If the operand has a default value, do we use it? We must use the
2642       // default if we've run out of children of the pattern DAG to consume,
2643       // or if the operand is followed by a non-defaulted one.
2644       if (CDP.operandHasDefault(OperandNode) &&
2645           (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2646         continue;
2647 
2648       // If we have run out of child nodes and there _isn't_ a default
2649       // value we can use for the next operand, give an error.
2650       if (ChildNo >= getNumChildren()) {
2651         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2652         return false;
2653       }
2654 
2655       TreePatternNode *Child = getChild(ChildNo++);
2656       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
2657 
2658       // If the operand has sub-operands, they may be provided by distinct
2659       // child patterns, so attempt to match each sub-operand separately.
2660       if (OperandNode->isSubClassOf("Operand")) {
2661         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2662         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2663           // But don't do that if the whole operand is being provided by
2664           // a single ComplexPattern-related Operand.
2665 
2666           if (Child->getNumMIResults(CDP) < NumArgs) {
2667             // Match first sub-operand against the child we already have.
2668             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2669             MadeChange |=
2670               Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2671 
2672             // And the remaining sub-operands against subsequent children.
2673             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2674               if (ChildNo >= getNumChildren()) {
2675                 emitTooFewOperandsError(TP, getOperator()->getName(),
2676                                         getNumChildren());
2677                 return false;
2678               }
2679               Child = getChild(ChildNo++);
2680 
2681               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2682               MadeChange |=
2683                 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2684             }
2685             continue;
2686           }
2687         }
2688       }
2689 
2690       // If we didn't match by pieces above, attempt to match the whole
2691       // operand now.
2692       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2693     }
2694 
2695     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2696       emitTooManyOperandsError(TP, getOperator()->getName(),
2697                                ChildNo, getNumChildren());
2698       return false;
2699     }
2700 
2701     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2702       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2703     return MadeChange;
2704   }
2705 
2706   if (getOperator()->isSubClassOf("ComplexPattern")) {
2707     bool MadeChange = false;
2708 
2709     if (!NotRegisters) {
2710       assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
2711       Record *T = CDP.getComplexPattern(getOperator()).getValueType();
2712       const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2713       const ValueTypeByHwMode VVT = getValueTypeByHwMode(T, CGH);
2714       // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
2715       // exclusively use those as non-leaf nodes with explicit type casts, so
2716       // for backwards compatibility we do no inference in that case. This is
2717       // not supported when the ComplexPattern is used as a leaf value,
2718       // however; this inconsistency should be resolved, either by adding this
2719       // case there or by altering the backends to not do this (e.g. using Any
2720       // instead may work).
2721       if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
2722         MadeChange |= UpdateNodeType(0, VVT, TP);
2723     }
2724 
2725     for (unsigned i = 0; i < getNumChildren(); ++i)
2726       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2727 
2728     return MadeChange;
2729   }
2730 
2731   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2732 
2733   // Node transforms always take one operand.
2734   if (getNumChildren() != 1) {
2735     TP.error("Node transform '" + getOperator()->getName() +
2736              "' requires one operand!");
2737     return false;
2738   }
2739 
2740   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2741   return MadeChange;
2742 }
2743 
2744 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2745 /// RHS of a commutative operation, not the on LHS.
2746 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2747   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2748     return true;
2749   if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2750     return true;
2751   if (isImmAllOnesAllZerosMatch(N))
2752     return true;
2753   return false;
2754 }
2755 
2756 
2757 /// canPatternMatch - If it is impossible for this pattern to match on this
2758 /// target, fill in Reason and return false.  Otherwise, return true.  This is
2759 /// used as a sanity check for .td files (to prevent people from writing stuff
2760 /// that can never possibly work), and to prevent the pattern permuter from
2761 /// generating stuff that is useless.
2762 bool TreePatternNode::canPatternMatch(std::string &Reason,
2763                                       const CodeGenDAGPatterns &CDP) {
2764   if (isLeaf()) return true;
2765 
2766   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2767     if (!getChild(i)->canPatternMatch(Reason, CDP))
2768       return false;
2769 
2770   // If this is an intrinsic, handle cases that would make it not match.  For
2771   // example, if an operand is required to be an immediate.
2772   if (getOperator()->isSubClassOf("Intrinsic")) {
2773     // TODO:
2774     return true;
2775   }
2776 
2777   if (getOperator()->isSubClassOf("ComplexPattern"))
2778     return true;
2779 
2780   // If this node is a commutative operator, check that the LHS isn't an
2781   // immediate.
2782   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2783   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2784   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2785     // Scan all of the operands of the node and make sure that only the last one
2786     // is a constant node, unless the RHS also is.
2787     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2788       unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2789       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2790         if (OnlyOnRHSOfCommutative(getChild(i))) {
2791           Reason="Immediate value must be on the RHS of commutative operators!";
2792           return false;
2793         }
2794     }
2795   }
2796 
2797   return true;
2798 }
2799 
2800 //===----------------------------------------------------------------------===//
2801 // TreePattern implementation
2802 //
2803 
2804 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2805                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2806                          isInputPattern(isInput), HasError(false),
2807                          Infer(*this) {
2808   for (Init *I : RawPat->getValues())
2809     Trees.push_back(ParseTreePattern(I, ""));
2810 }
2811 
2812 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2813                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2814                          isInputPattern(isInput), HasError(false),
2815                          Infer(*this) {
2816   Trees.push_back(ParseTreePattern(Pat, ""));
2817 }
2818 
2819 TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2820                          CodeGenDAGPatterns &cdp)
2821     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2822       Infer(*this) {
2823   Trees.push_back(Pat);
2824 }
2825 
2826 void TreePattern::error(const Twine &Msg) {
2827   if (HasError)
2828     return;
2829   dump();
2830   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2831   HasError = true;
2832 }
2833 
2834 void TreePattern::ComputeNamedNodes() {
2835   for (TreePatternNodePtr &Tree : Trees)
2836     ComputeNamedNodes(Tree.get());
2837 }
2838 
2839 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2840   if (!N->getName().empty())
2841     NamedNodes[N->getName()].push_back(N);
2842 
2843   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2844     ComputeNamedNodes(N->getChild(i));
2845 }
2846 
2847 TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2848                                                  StringRef OpName) {
2849   RecordKeeper &RK = TheInit->getRecordKeeper();
2850   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2851     Record *R = DI->getDef();
2852 
2853     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
2854     // TreePatternNode of its own.  For example:
2855     ///   (foo GPR, imm) -> (foo GPR, (imm))
2856     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
2857       return ParseTreePattern(
2858         DagInit::get(DI, nullptr,
2859                      std::vector<std::pair<Init*, StringInit*> >()),
2860         OpName);
2861 
2862     // Input argument?
2863     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
2864     if (R->getName() == "node" && !OpName.empty()) {
2865       if (OpName.empty())
2866         error("'node' argument requires a name to match with operand list");
2867       Args.push_back(std::string(OpName));
2868     }
2869 
2870     Res->setName(OpName);
2871     return Res;
2872   }
2873 
2874   // ?:$name or just $name.
2875   if (isa<UnsetInit>(TheInit)) {
2876     if (OpName.empty())
2877       error("'?' argument requires a name to match with operand list");
2878     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
2879     Args.push_back(std::string(OpName));
2880     Res->setName(OpName);
2881     return Res;
2882   }
2883 
2884   if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2885     if (!OpName.empty())
2886       error("Constant int or bit argument should not have a name!");
2887     if (isa<BitInit>(TheInit))
2888       TheInit = TheInit->convertInitializerTo(IntRecTy::get(RK));
2889     return std::make_shared<TreePatternNode>(TheInit, 1);
2890   }
2891 
2892   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2893     // Turn this into an IntInit.
2894     Init *II = BI->convertInitializerTo(IntRecTy::get(RK));
2895     if (!II || !isa<IntInit>(II))
2896       error("Bits value must be constants!");
2897     return ParseTreePattern(II, OpName);
2898   }
2899 
2900   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2901   if (!Dag) {
2902     TheInit->print(errs());
2903     error("Pattern has unexpected init kind!");
2904   }
2905   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2906   if (!OpDef) error("Pattern has unexpected operator type!");
2907   Record *Operator = OpDef->getDef();
2908 
2909   if (Operator->isSubClassOf("ValueType")) {
2910     // If the operator is a ValueType, then this must be "type cast" of a leaf
2911     // node.
2912     if (Dag->getNumArgs() != 1)
2913       error("Type cast only takes one operand!");
2914 
2915     TreePatternNodePtr New =
2916         ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2917 
2918     // Apply the type cast.
2919     if (New->getNumTypes() != 1)
2920       error("Type cast can only have one type!");
2921     const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2922     New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2923 
2924     if (!OpName.empty())
2925       error("ValueType cast should not have a name!");
2926     return New;
2927   }
2928 
2929   // Verify that this is something that makes sense for an operator.
2930   if (!Operator->isSubClassOf("PatFrags") &&
2931       !Operator->isSubClassOf("SDNode") &&
2932       !Operator->isSubClassOf("Instruction") &&
2933       !Operator->isSubClassOf("SDNodeXForm") &&
2934       !Operator->isSubClassOf("Intrinsic") &&
2935       !Operator->isSubClassOf("ComplexPattern") &&
2936       Operator->getName() != "set" &&
2937       Operator->getName() != "implicit")
2938     error("Unrecognized node '" + Operator->getName() + "'!");
2939 
2940   //  Check to see if this is something that is illegal in an input pattern.
2941   if (isInputPattern) {
2942     if (Operator->isSubClassOf("Instruction") ||
2943         Operator->isSubClassOf("SDNodeXForm"))
2944       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2945   } else {
2946     if (Operator->isSubClassOf("Intrinsic"))
2947       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2948 
2949     if (Operator->isSubClassOf("SDNode") &&
2950         Operator->getName() != "imm" &&
2951         Operator->getName() != "timm" &&
2952         Operator->getName() != "fpimm" &&
2953         Operator->getName() != "tglobaltlsaddr" &&
2954         Operator->getName() != "tconstpool" &&
2955         Operator->getName() != "tjumptable" &&
2956         Operator->getName() != "tframeindex" &&
2957         Operator->getName() != "texternalsym" &&
2958         Operator->getName() != "tblockaddress" &&
2959         Operator->getName() != "tglobaladdr" &&
2960         Operator->getName() != "bb" &&
2961         Operator->getName() != "vt" &&
2962         Operator->getName() != "mcsym")
2963       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2964   }
2965 
2966   std::vector<TreePatternNodePtr> Children;
2967 
2968   // Parse all the operands.
2969   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2970     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2971 
2972   // Get the actual number of results before Operator is converted to an intrinsic
2973   // node (which is hard-coded to have either zero or one result).
2974   unsigned NumResults = GetNumNodeResults(Operator, CDP);
2975 
2976   // If the operator is an intrinsic, then this is just syntactic sugar for
2977   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2978   // convert the intrinsic name to a number.
2979   if (Operator->isSubClassOf("Intrinsic")) {
2980     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2981     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2982 
2983     // If this intrinsic returns void, it must have side-effects and thus a
2984     // chain.
2985     if (Int.IS.RetVTs.empty())
2986       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2987     else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
2988       // Has side-effects, requires chain.
2989       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2990     else // Otherwise, no chain.
2991       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2992 
2993     Children.insert(Children.begin(), std::make_shared<TreePatternNode>(
2994                                           IntInit::get(RK, IID), 1));
2995   }
2996 
2997   if (Operator->isSubClassOf("ComplexPattern")) {
2998     for (unsigned i = 0; i < Children.size(); ++i) {
2999       TreePatternNodePtr Child = Children[i];
3000 
3001       if (Child->getName().empty())
3002         error("All arguments to a ComplexPattern must be named");
3003 
3004       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
3005       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
3006       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3007       auto OperandId = std::make_pair(Operator, i);
3008       auto PrevOp = ComplexPatternOperands.find(Child->getName());
3009       if (PrevOp != ComplexPatternOperands.end()) {
3010         if (PrevOp->getValue() != OperandId)
3011           error("All ComplexPattern operands must appear consistently: "
3012                 "in the same order in just one ComplexPattern instance.");
3013       } else
3014         ComplexPatternOperands[Child->getName()] = OperandId;
3015     }
3016   }
3017 
3018   TreePatternNodePtr Result =
3019       std::make_shared<TreePatternNode>(Operator, std::move(Children),
3020                                         NumResults);
3021   Result->setName(OpName);
3022 
3023   if (Dag->getName()) {
3024     assert(Result->getName().empty());
3025     Result->setName(Dag->getNameStr());
3026   }
3027   return Result;
3028 }
3029 
3030 /// SimplifyTree - See if we can simplify this tree to eliminate something that
3031 /// will never match in favor of something obvious that will.  This is here
3032 /// strictly as a convenience to target authors because it allows them to write
3033 /// more type generic things and have useless type casts fold away.
3034 ///
3035 /// This returns true if any change is made.
3036 static bool SimplifyTree(TreePatternNodePtr &N) {
3037   if (N->isLeaf())
3038     return false;
3039 
3040   // If we have a bitconvert with a resolved type and if the source and
3041   // destination types are the same, then the bitconvert is useless, remove it.
3042   //
3043   // We make an exception if the types are completely empty. This can come up
3044   // when the pattern being simplified is in the Fragments list of a PatFrags,
3045   // so that the operand is just an untyped "node". In that situation we leave
3046   // bitconverts unsimplified, and simplify them later once the fragment is
3047   // expanded into its true context.
3048   if (N->getOperator()->getName() == "bitconvert" &&
3049       N->getExtType(0).isValueTypeByHwMode(false) &&
3050       !N->getExtType(0).empty() &&
3051       N->getExtType(0) == N->getChild(0)->getExtType(0) &&
3052       N->getName().empty()) {
3053     N = N->getChildShared(0);
3054     SimplifyTree(N);
3055     return true;
3056   }
3057 
3058   // Walk all children.
3059   bool MadeChange = false;
3060   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3061     TreePatternNodePtr Child = N->getChildShared(i);
3062     MadeChange |= SimplifyTree(Child);
3063     N->setChild(i, std::move(Child));
3064   }
3065   return MadeChange;
3066 }
3067 
3068 
3069 
3070 /// InferAllTypes - Infer/propagate as many types throughout the expression
3071 /// patterns as possible.  Return true if all types are inferred, false
3072 /// otherwise.  Flags an error if a type contradiction is found.
3073 bool TreePattern::
3074 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
3075   if (NamedNodes.empty())
3076     ComputeNamedNodes();
3077 
3078   bool MadeChange = true;
3079   while (MadeChange) {
3080     MadeChange = false;
3081     for (TreePatternNodePtr &Tree : Trees) {
3082       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
3083       MadeChange |= SimplifyTree(Tree);
3084     }
3085 
3086     // If there are constraints on our named nodes, apply them.
3087     for (auto &Entry : NamedNodes) {
3088       SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
3089 
3090       // If we have input named node types, propagate their types to the named
3091       // values here.
3092       if (InNamedTypes) {
3093         if (!InNamedTypes->count(Entry.getKey())) {
3094           error("Node '" + std::string(Entry.getKey()) +
3095                 "' in output pattern but not input pattern");
3096           return true;
3097         }
3098 
3099         const SmallVectorImpl<TreePatternNode*> &InNodes =
3100           InNamedTypes->find(Entry.getKey())->second;
3101 
3102         // The input types should be fully resolved by now.
3103         for (TreePatternNode *Node : Nodes) {
3104           // If this node is a register class, and it is the root of the pattern
3105           // then we're mapping something onto an input register.  We allow
3106           // changing the type of the input register in this case.  This allows
3107           // us to match things like:
3108           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3109           if (Node == Trees[0].get() && Node->isLeaf()) {
3110             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
3111             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3112                        DI->getDef()->isSubClassOf("RegisterOperand")))
3113               continue;
3114           }
3115 
3116           assert(Node->getNumTypes() == 1 &&
3117                  InNodes[0]->getNumTypes() == 1 &&
3118                  "FIXME: cannot name multiple result nodes yet");
3119           MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
3120                                              *this);
3121         }
3122       }
3123 
3124       // If there are multiple nodes with the same name, they must all have the
3125       // same type.
3126       if (Entry.second.size() > 1) {
3127         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
3128           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
3129           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
3130                  "FIXME: cannot name multiple result nodes yet");
3131 
3132           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
3133           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
3134         }
3135       }
3136     }
3137   }
3138 
3139   bool HasUnresolvedTypes = false;
3140   for (const TreePatternNodePtr &Tree : Trees)
3141     HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
3142   return !HasUnresolvedTypes;
3143 }
3144 
3145 void TreePattern::print(raw_ostream &OS) const {
3146   OS << getRecord()->getName();
3147   if (!Args.empty()) {
3148     OS << "(";
3149     ListSeparator LS;
3150     for (const std::string &Arg : Args)
3151       OS << LS << Arg;
3152     OS << ")";
3153   }
3154   OS << ": ";
3155 
3156   if (Trees.size() > 1)
3157     OS << "[\n";
3158   for (const TreePatternNodePtr &Tree : Trees) {
3159     OS << "\t";
3160     Tree->print(OS);
3161     OS << "\n";
3162   }
3163 
3164   if (Trees.size() > 1)
3165     OS << "]\n";
3166 }
3167 
3168 void TreePattern::dump() const { print(errs()); }
3169 
3170 //===----------------------------------------------------------------------===//
3171 // CodeGenDAGPatterns implementation
3172 //
3173 
3174 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3175                                        PatternRewriterFn PatternRewriter)
3176     : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3177       PatternRewriter(PatternRewriter) {
3178 
3179   Intrinsics = CodeGenIntrinsicTable(Records);
3180   ParseNodeInfo();
3181   ParseNodeTransforms();
3182   ParseComplexPatterns();
3183   ParsePatternFragments();
3184   ParseDefaultOperands();
3185   ParseInstructions();
3186   ParsePatternFragments(/*OutFrags*/true);
3187   ParsePatterns();
3188 
3189   // Generate variants.  For example, commutative patterns can match
3190   // multiple ways.  Add them to PatternsToMatch as well.
3191   GenerateVariants();
3192 
3193   // Break patterns with parameterized types into a series of patterns,
3194   // where each one has a fixed type and is predicated on the conditions
3195   // of the associated HW mode.
3196   ExpandHwModeBasedTypes();
3197 
3198   // Infer instruction flags.  For example, we can detect loads,
3199   // stores, and side effects in many cases by examining an
3200   // instruction's pattern.
3201   InferInstructionFlags();
3202 
3203   // Verify that instruction flags match the patterns.
3204   VerifyInstructionFlags();
3205 }
3206 
3207 Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3208   Record *N = Records.getDef(Name);
3209   if (!N || !N->isSubClassOf("SDNode"))
3210     PrintFatalError("Error getting SDNode '" + Name + "'!");
3211 
3212   return N;
3213 }
3214 
3215 // Parse all of the SDNode definitions for the target, populating SDNodes.
3216 void CodeGenDAGPatterns::ParseNodeInfo() {
3217   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
3218   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3219 
3220   while (!Nodes.empty()) {
3221     Record *R = Nodes.back();
3222     SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
3223     Nodes.pop_back();
3224   }
3225 
3226   // Get the builtin intrinsic nodes.
3227   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
3228   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
3229   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3230 }
3231 
3232 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3233 /// map, and emit them to the file as functions.
3234 void CodeGenDAGPatterns::ParseNodeTransforms() {
3235   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3236   while (!Xforms.empty()) {
3237     Record *XFormNode = Xforms.back();
3238     Record *SDNode = XFormNode->getValueAsDef("Opcode");
3239     StringRef Code = XFormNode->getValueAsString("XFormFunction");
3240     SDNodeXForms.insert(
3241         std::make_pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
3242 
3243     Xforms.pop_back();
3244   }
3245 }
3246 
3247 void CodeGenDAGPatterns::ParseComplexPatterns() {
3248   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3249   while (!AMs.empty()) {
3250     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3251     AMs.pop_back();
3252   }
3253 }
3254 
3255 
3256 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3257 /// file, building up the PatternFragments map.  After we've collected them all,
3258 /// inline fragments together as necessary, so that there are no references left
3259 /// inside a pattern fragment to a pattern fragment.
3260 ///
3261 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3262   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
3263 
3264   // First step, parse all of the fragments.
3265   for (Record *Frag : Fragments) {
3266     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3267       continue;
3268 
3269     ListInit *LI = Frag->getValueAsListInit("Fragments");
3270     TreePattern *P =
3271         (PatternFragments[Frag] = std::make_unique<TreePattern>(
3272              Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
3273              *this)).get();
3274 
3275     // Validate the argument list, converting it to set, to discard duplicates.
3276     std::vector<std::string> &Args = P->getArgList();
3277     // Copy the args so we can take StringRefs to them.
3278     auto ArgsCopy = Args;
3279     SmallDenseSet<StringRef, 4> OperandsSet;
3280     OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3281 
3282     if (OperandsSet.count(""))
3283       P->error("Cannot have unnamed 'node' values in pattern fragment!");
3284 
3285     // Parse the operands list.
3286     DagInit *OpsList = Frag->getValueAsDag("Operands");
3287     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3288     // Special cases: ops == outs == ins. Different names are used to
3289     // improve readability.
3290     if (!OpsOp ||
3291         (OpsOp->getDef()->getName() != "ops" &&
3292          OpsOp->getDef()->getName() != "outs" &&
3293          OpsOp->getDef()->getName() != "ins"))
3294       P->error("Operands list should start with '(ops ... '!");
3295 
3296     // Copy over the arguments.
3297     Args.clear();
3298     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3299       if (!isa<DefInit>(OpsList->getArg(j)) ||
3300           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3301         P->error("Operands list should all be 'node' values.");
3302       if (!OpsList->getArgName(j))
3303         P->error("Operands list should have names for each operand!");
3304       StringRef ArgNameStr = OpsList->getArgNameStr(j);
3305       if (!OperandsSet.count(ArgNameStr))
3306         P->error("'" + ArgNameStr +
3307                  "' does not occur in pattern or was multiply specified!");
3308       OperandsSet.erase(ArgNameStr);
3309       Args.push_back(std::string(ArgNameStr));
3310     }
3311 
3312     if (!OperandsSet.empty())
3313       P->error("Operands list does not contain an entry for operand '" +
3314                *OperandsSet.begin() + "'!");
3315 
3316     // If there is a node transformation corresponding to this, keep track of
3317     // it.
3318     Record *Transform = Frag->getValueAsDef("OperandTransform");
3319     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
3320       for (const auto &T : P->getTrees())
3321         T->setTransformFn(Transform);
3322   }
3323 
3324   // Now that we've parsed all of the tree fragments, do a closure on them so
3325   // that there are not references to PatFrags left inside of them.
3326   for (Record *Frag : Fragments) {
3327     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
3328       continue;
3329 
3330     TreePattern &ThePat = *PatternFragments[Frag];
3331     ThePat.InlinePatternFragments();
3332 
3333     // Infer as many types as possible.  Don't worry about it if we don't infer
3334     // all of them, some may depend on the inputs of the pattern.  Also, don't
3335     // validate type sets; validation may cause spurious failures e.g. if a
3336     // fragment needs floating-point types but the current target does not have
3337     // any (this is only an error if that fragment is ever used!).
3338     {
3339       TypeInfer::SuppressValidation SV(ThePat.getInfer());
3340       ThePat.InferAllTypes();
3341       ThePat.resetError();
3342     }
3343 
3344     // If debugging, print out the pattern fragment result.
3345     LLVM_DEBUG(ThePat.dump());
3346   }
3347 }
3348 
3349 void CodeGenDAGPatterns::ParseDefaultOperands() {
3350   std::vector<Record*> DefaultOps;
3351   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3352 
3353   // Find some SDNode.
3354   assert(!SDNodes.empty() && "No SDNodes parsed?");
3355   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3356 
3357   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3358     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3359 
3360     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3361     // SomeSDnode so that we can parse this.
3362     std::vector<std::pair<Init*, StringInit*> > Ops;
3363     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3364       Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3365                                    DefaultInfo->getArgName(op)));
3366     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3367 
3368     // Create a TreePattern to parse this.
3369     TreePattern P(DefaultOps[i], DI, false, *this);
3370     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3371 
3372     // Copy the operands over into a DAGDefaultOperand.
3373     DAGDefaultOperand DefaultOpInfo;
3374 
3375     const TreePatternNodePtr &T = P.getTree(0);
3376     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3377       TreePatternNodePtr TPN = T->getChildShared(op);
3378       while (TPN->ApplyTypeConstraints(P, false))
3379         /* Resolve all types */;
3380 
3381       if (TPN->ContainsUnresolvedType(P)) {
3382         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3383                         DefaultOps[i]->getName() +
3384                         "' doesn't have a concrete type!");
3385       }
3386       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3387     }
3388 
3389     // Insert it into the DefaultOperands map so we can find it later.
3390     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3391   }
3392 }
3393 
3394 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3395 /// instruction input.  Return true if this is a real use.
3396 static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3397                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3398   // No name -> not interesting.
3399   if (Pat->getName().empty()) {
3400     if (Pat->isLeaf()) {
3401       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3402       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3403                  DI->getDef()->isSubClassOf("RegisterOperand")))
3404         I.error("Input " + DI->getDef()->getName() + " must be named!");
3405     }
3406     return false;
3407   }
3408 
3409   Record *Rec;
3410   if (Pat->isLeaf()) {
3411     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3412     if (!DI)
3413       I.error("Input $" + Pat->getName() + " must be an identifier!");
3414     Rec = DI->getDef();
3415   } else {
3416     Rec = Pat->getOperator();
3417   }
3418 
3419   // SRCVALUE nodes are ignored.
3420   if (Rec->getName() == "srcvalue")
3421     return false;
3422 
3423   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3424   if (!Slot) {
3425     Slot = Pat;
3426     return true;
3427   }
3428   Record *SlotRec;
3429   if (Slot->isLeaf()) {
3430     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3431   } else {
3432     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3433     SlotRec = Slot->getOperator();
3434   }
3435 
3436   // Ensure that the inputs agree if we've already seen this input.
3437   if (Rec != SlotRec)
3438     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3439   // Ensure that the types can agree as well.
3440   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3441   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3442   if (Slot->getExtTypes() != Pat->getExtTypes())
3443     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3444   return true;
3445 }
3446 
3447 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3448 /// part of "I", the instruction), computing the set of inputs and outputs of
3449 /// the pattern.  Report errors if we see anything naughty.
3450 void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3451     TreePattern &I, TreePatternNodePtr Pat,
3452     std::map<std::string, TreePatternNodePtr> &InstInputs,
3453     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3454         &InstResults,
3455     std::vector<Record *> &InstImpResults) {
3456 
3457   // The instruction pattern still has unresolved fragments.  For *named*
3458   // nodes we must resolve those here.  This may not result in multiple
3459   // alternatives.
3460   if (!Pat->getName().empty()) {
3461     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3462     SrcPattern.InlinePatternFragments();
3463     SrcPattern.InferAllTypes();
3464     Pat = SrcPattern.getOnlyTree();
3465   }
3466 
3467   if (Pat->isLeaf()) {
3468     bool isUse = HandleUse(I, Pat, InstInputs);
3469     if (!isUse && Pat->getTransformFn())
3470       I.error("Cannot specify a transform function for a non-input value!");
3471     return;
3472   }
3473 
3474   if (Pat->getOperator()->getName() == "implicit") {
3475     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3476       TreePatternNode *Dest = Pat->getChild(i);
3477       if (!Dest->isLeaf())
3478         I.error("implicitly defined value should be a register!");
3479 
3480       DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3481       if (!Val || !Val->getDef()->isSubClassOf("Register"))
3482         I.error("implicitly defined value should be a register!");
3483       InstImpResults.push_back(Val->getDef());
3484     }
3485     return;
3486   }
3487 
3488   if (Pat->getOperator()->getName() != "set") {
3489     // If this is not a set, verify that the children nodes are not void typed,
3490     // and recurse.
3491     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3492       if (Pat->getChild(i)->getNumTypes() == 0)
3493         I.error("Cannot have void nodes inside of patterns!");
3494       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3495                                   InstResults, InstImpResults);
3496     }
3497 
3498     // If this is a non-leaf node with no children, treat it basically as if
3499     // it were a leaf.  This handles nodes like (imm).
3500     bool isUse = HandleUse(I, Pat, InstInputs);
3501 
3502     if (!isUse && Pat->getTransformFn())
3503       I.error("Cannot specify a transform function for a non-input value!");
3504     return;
3505   }
3506 
3507   // Otherwise, this is a set, validate and collect instruction results.
3508   if (Pat->getNumChildren() == 0)
3509     I.error("set requires operands!");
3510 
3511   if (Pat->getTransformFn())
3512     I.error("Cannot specify a transform function on a set node!");
3513 
3514   // Check the set destinations.
3515   unsigned NumDests = Pat->getNumChildren()-1;
3516   for (unsigned i = 0; i != NumDests; ++i) {
3517     TreePatternNodePtr Dest = Pat->getChildShared(i);
3518     // For set destinations we also must resolve fragments here.
3519     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3520     DestPattern.InlinePatternFragments();
3521     DestPattern.InferAllTypes();
3522     Dest = DestPattern.getOnlyTree();
3523 
3524     if (!Dest->isLeaf())
3525       I.error("set destination should be a register!");
3526 
3527     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3528     if (!Val) {
3529       I.error("set destination should be a register!");
3530       continue;
3531     }
3532 
3533     if (Val->getDef()->isSubClassOf("RegisterClass") ||
3534         Val->getDef()->isSubClassOf("ValueType") ||
3535         Val->getDef()->isSubClassOf("RegisterOperand") ||
3536         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3537       if (Dest->getName().empty())
3538         I.error("set destination must have a name!");
3539       if (InstResults.count(Dest->getName()))
3540         I.error("cannot set '" + Dest->getName() + "' multiple times");
3541       InstResults[Dest->getName()] = Dest;
3542     } else if (Val->getDef()->isSubClassOf("Register")) {
3543       InstImpResults.push_back(Val->getDef());
3544     } else {
3545       I.error("set destination should be a register!");
3546     }
3547   }
3548 
3549   // Verify and collect info from the computation.
3550   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3551                               InstResults, InstImpResults);
3552 }
3553 
3554 //===----------------------------------------------------------------------===//
3555 // Instruction Analysis
3556 //===----------------------------------------------------------------------===//
3557 
3558 class InstAnalyzer {
3559   const CodeGenDAGPatterns &CDP;
3560 public:
3561   bool hasSideEffects;
3562   bool mayStore;
3563   bool mayLoad;
3564   bool isBitcast;
3565   bool isVariadic;
3566   bool hasChain;
3567 
3568   InstAnalyzer(const CodeGenDAGPatterns &cdp)
3569     : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3570       isBitcast(false), isVariadic(false), hasChain(false) {}
3571 
3572   void Analyze(const PatternToMatch &Pat) {
3573     const TreePatternNode *N = Pat.getSrcPattern();
3574     AnalyzeNode(N);
3575     // These properties are detected only on the root node.
3576     isBitcast = IsNodeBitcast(N);
3577   }
3578 
3579 private:
3580   bool IsNodeBitcast(const TreePatternNode *N) const {
3581     if (hasSideEffects || mayLoad || mayStore || isVariadic)
3582       return false;
3583 
3584     if (N->isLeaf())
3585       return false;
3586     if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
3587       return false;
3588 
3589     if (N->getOperator()->isSubClassOf("ComplexPattern"))
3590       return false;
3591 
3592     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
3593     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3594       return false;
3595     return OpInfo.getEnumName() == "ISD::BITCAST";
3596   }
3597 
3598 public:
3599   void AnalyzeNode(const TreePatternNode *N) {
3600     if (N->isLeaf()) {
3601       if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3602         Record *LeafRec = DI->getDef();
3603         // Handle ComplexPattern leaves.
3604         if (LeafRec->isSubClassOf("ComplexPattern")) {
3605           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3606           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3607           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3608           if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3609         }
3610       }
3611       return;
3612     }
3613 
3614     // Analyze children.
3615     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3616       AnalyzeNode(N->getChild(i));
3617 
3618     // Notice properties of the node.
3619     if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3620     if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3621     if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3622     if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3623     if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
3624 
3625     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3626       // If this is an intrinsic, analyze it.
3627       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3628         mayLoad = true;// These may load memory.
3629 
3630       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3631         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3632 
3633       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3634           IntInfo->hasSideEffects)
3635         // ReadWriteMem intrinsics can have other strange effects.
3636         hasSideEffects = true;
3637     }
3638   }
3639 
3640 };
3641 
3642 static bool InferFromPattern(CodeGenInstruction &InstInfo,
3643                              const InstAnalyzer &PatInfo,
3644                              Record *PatDef) {
3645   bool Error = false;
3646 
3647   // Remember where InstInfo got its flags.
3648   if (InstInfo.hasUndefFlags())
3649       InstInfo.InferredFrom = PatDef;
3650 
3651   // Check explicitly set flags for consistency.
3652   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3653       !InstInfo.hasSideEffects_Unset) {
3654     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3655     // the pattern has no side effects. That could be useful for div/rem
3656     // instructions that may trap.
3657     if (!InstInfo.hasSideEffects) {
3658       Error = true;
3659       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3660                  Twine(InstInfo.hasSideEffects));
3661     }
3662   }
3663 
3664   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3665     Error = true;
3666     PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3667                Twine(InstInfo.mayStore));
3668   }
3669 
3670   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3671     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3672     // Some targets translate immediates to loads.
3673     if (!InstInfo.mayLoad) {
3674       Error = true;
3675       PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3676                  Twine(InstInfo.mayLoad));
3677     }
3678   }
3679 
3680   // Transfer inferred flags.
3681   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3682   InstInfo.mayStore |= PatInfo.mayStore;
3683   InstInfo.mayLoad |= PatInfo.mayLoad;
3684 
3685   // These flags are silently added without any verification.
3686   // FIXME: To match historical behavior of TableGen, for now add those flags
3687   // only when we're inferring from the primary instruction pattern.
3688   if (PatDef->isSubClassOf("Instruction")) {
3689     InstInfo.isBitcast |= PatInfo.isBitcast;
3690     InstInfo.hasChain |= PatInfo.hasChain;
3691     InstInfo.hasChain_Inferred = true;
3692   }
3693 
3694   // Don't infer isVariadic. This flag means something different on SDNodes and
3695   // instructions. For example, a CALL SDNode is variadic because it has the
3696   // call arguments as operands, but a CALL instruction is not variadic - it
3697   // has argument registers as implicit, not explicit uses.
3698 
3699   return Error;
3700 }
3701 
3702 /// hasNullFragReference - Return true if the DAG has any reference to the
3703 /// null_frag operator.
3704 static bool hasNullFragReference(DagInit *DI) {
3705   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3706   if (!OpDef) return false;
3707   Record *Operator = OpDef->getDef();
3708 
3709   // If this is the null fragment, return true.
3710   if (Operator->getName() == "null_frag") return true;
3711   // If any of the arguments reference the null fragment, return true.
3712   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3713     if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))
3714       if (Arg->getDef()->getName() == "null_frag")
3715         return true;
3716     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3717     if (Arg && hasNullFragReference(Arg))
3718       return true;
3719   }
3720 
3721   return false;
3722 }
3723 
3724 /// hasNullFragReference - Return true if any DAG in the list references
3725 /// the null_frag operator.
3726 static bool hasNullFragReference(ListInit *LI) {
3727   for (Init *I : LI->getValues()) {
3728     DagInit *DI = dyn_cast<DagInit>(I);
3729     assert(DI && "non-dag in an instruction Pattern list?!");
3730     if (hasNullFragReference(DI))
3731       return true;
3732   }
3733   return false;
3734 }
3735 
3736 /// Get all the instructions in a tree.
3737 static void
3738 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3739   if (Tree->isLeaf())
3740     return;
3741   if (Tree->getOperator()->isSubClassOf("Instruction"))
3742     Instrs.push_back(Tree->getOperator());
3743   for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3744     getInstructionsInTree(Tree->getChild(i), Instrs);
3745 }
3746 
3747 /// Check the class of a pattern leaf node against the instruction operand it
3748 /// represents.
3749 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3750                               Record *Leaf) {
3751   if (OI.Rec == Leaf)
3752     return true;
3753 
3754   // Allow direct value types to be used in instruction set patterns.
3755   // The type will be checked later.
3756   if (Leaf->isSubClassOf("ValueType"))
3757     return true;
3758 
3759   // Patterns can also be ComplexPattern instances.
3760   if (Leaf->isSubClassOf("ComplexPattern"))
3761     return true;
3762 
3763   return false;
3764 }
3765 
3766 void CodeGenDAGPatterns::parseInstructionPattern(
3767     CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3768 
3769   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3770 
3771   // Parse the instruction.
3772   TreePattern I(CGI.TheDef, Pat, true, *this);
3773 
3774   // InstInputs - Keep track of all of the inputs of the instruction, along
3775   // with the record they are declared as.
3776   std::map<std::string, TreePatternNodePtr> InstInputs;
3777 
3778   // InstResults - Keep track of all the virtual registers that are 'set'
3779   // in the instruction, including what reg class they are.
3780   MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3781       InstResults;
3782 
3783   std::vector<Record*> InstImpResults;
3784 
3785   // Verify that the top-level forms in the instruction are of void type, and
3786   // fill in the InstResults map.
3787   SmallString<32> TypesString;
3788   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3789     TypesString.clear();
3790     TreePatternNodePtr Pat = I.getTree(j);
3791     if (Pat->getNumTypes() != 0) {
3792       raw_svector_ostream OS(TypesString);
3793       ListSeparator LS;
3794       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3795         OS << LS;
3796         Pat->getExtType(k).writeToStream(OS);
3797       }
3798       I.error("Top-level forms in instruction pattern should have"
3799                " void types, has types " +
3800                OS.str());
3801     }
3802 
3803     // Find inputs and outputs, and verify the structure of the uses/defs.
3804     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3805                                 InstImpResults);
3806   }
3807 
3808   // Now that we have inputs and outputs of the pattern, inspect the operands
3809   // list for the instruction.  This determines the order that operands are
3810   // added to the machine instruction the node corresponds to.
3811   unsigned NumResults = InstResults.size();
3812 
3813   // Parse the operands list from the (ops) list, validating it.
3814   assert(I.getArgList().empty() && "Args list should still be empty here!");
3815 
3816   // Check that all of the results occur first in the list.
3817   std::vector<Record*> Results;
3818   std::vector<unsigned> ResultIndices;
3819   SmallVector<TreePatternNodePtr, 2> ResNodes;
3820   for (unsigned i = 0; i != NumResults; ++i) {
3821     if (i == CGI.Operands.size()) {
3822       const std::string &OpName =
3823           llvm::find_if(
3824               InstResults,
3825               [](const std::pair<std::string, TreePatternNodePtr> &P) {
3826                 return P.second;
3827               })
3828               ->first;
3829 
3830       I.error("'" + OpName + "' set but does not appear in operand list!");
3831     }
3832 
3833     const std::string &OpName = CGI.Operands[i].Name;
3834 
3835     // Check that it exists in InstResults.
3836     auto InstResultIter = InstResults.find(OpName);
3837     if (InstResultIter == InstResults.end() || !InstResultIter->second)
3838       I.error("Operand $" + OpName + " does not exist in operand list!");
3839 
3840     TreePatternNodePtr RNode = InstResultIter->second;
3841     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3842     ResNodes.push_back(std::move(RNode));
3843     if (!R)
3844       I.error("Operand $" + OpName + " should be a set destination: all "
3845                "outputs must occur before inputs in operand list!");
3846 
3847     if (!checkOperandClass(CGI.Operands[i], R))
3848       I.error("Operand $" + OpName + " class mismatch!");
3849 
3850     // Remember the return type.
3851     Results.push_back(CGI.Operands[i].Rec);
3852 
3853     // Remember the result index.
3854     ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3855 
3856     // Okay, this one checks out.
3857     InstResultIter->second = nullptr;
3858   }
3859 
3860   // Loop over the inputs next.
3861   std::vector<TreePatternNodePtr> ResultNodeOperands;
3862   std::vector<Record*> Operands;
3863   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3864     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3865     const std::string &OpName = Op.Name;
3866     if (OpName.empty())
3867       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3868 
3869     if (!InstInputs.count(OpName)) {
3870       // If this is an operand with a DefaultOps set filled in, we can ignore
3871       // this.  When we codegen it, we will do so as always executed.
3872       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3873         // Does it have a non-empty DefaultOps field?  If so, ignore this
3874         // operand.
3875         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3876           continue;
3877       }
3878       I.error("Operand $" + OpName +
3879                " does not appear in the instruction pattern");
3880     }
3881     TreePatternNodePtr InVal = InstInputs[OpName];
3882     InstInputs.erase(OpName);   // It occurred, remove from map.
3883 
3884     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3885       Record *InRec = cast<DefInit>(InVal->getLeafValue())->getDef();
3886       if (!checkOperandClass(Op, InRec))
3887         I.error("Operand $" + OpName + "'s register class disagrees"
3888                  " between the operand and pattern");
3889     }
3890     Operands.push_back(Op.Rec);
3891 
3892     // Construct the result for the dest-pattern operand list.
3893     TreePatternNodePtr OpNode = InVal->clone();
3894 
3895     // No predicate is useful on the result.
3896     OpNode->clearPredicateCalls();
3897 
3898     // Promote the xform function to be an explicit node if set.
3899     if (Record *Xform = OpNode->getTransformFn()) {
3900       OpNode->setTransformFn(nullptr);
3901       std::vector<TreePatternNodePtr> Children;
3902       Children.push_back(OpNode);
3903       OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
3904                                                  OpNode->getNumTypes());
3905     }
3906 
3907     ResultNodeOperands.push_back(std::move(OpNode));
3908   }
3909 
3910   if (!InstInputs.empty())
3911     I.error("Input operand $" + InstInputs.begin()->first +
3912             " occurs in pattern but not in operands list!");
3913 
3914   TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
3915       I.getRecord(), std::move(ResultNodeOperands),
3916       GetNumNodeResults(I.getRecord(), *this));
3917   // Copy fully inferred output node types to instruction result pattern.
3918   for (unsigned i = 0; i != NumResults; ++i) {
3919     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3920     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3921     ResultPattern->setResultIndex(i, ResultIndices[i]);
3922   }
3923 
3924   // FIXME: Assume only the first tree is the pattern. The others are clobber
3925   // nodes.
3926   TreePatternNodePtr Pattern = I.getTree(0);
3927   TreePatternNodePtr SrcPattern;
3928   if (Pattern->getOperator()->getName() == "set") {
3929     SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3930   } else{
3931     // Not a set (store or something?)
3932     SrcPattern = Pattern;
3933   }
3934 
3935   // Create and insert the instruction.
3936   // FIXME: InstImpResults should not be part of DAGInstruction.
3937   Record *R = I.getRecord();
3938   DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3939                    std::forward_as_tuple(Results, Operands, InstImpResults,
3940                                          SrcPattern, ResultPattern));
3941 
3942   LLVM_DEBUG(I.dump());
3943 }
3944 
3945 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3946 /// any fragments involved.  This populates the Instructions list with fully
3947 /// resolved instructions.
3948 void CodeGenDAGPatterns::ParseInstructions() {
3949   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3950 
3951   for (Record *Instr : Instrs) {
3952     ListInit *LI = nullptr;
3953 
3954     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3955       LI = Instr->getValueAsListInit("Pattern");
3956 
3957     // If there is no pattern, only collect minimal information about the
3958     // instruction for its operand list.  We have to assume that there is one
3959     // result, as we have no detailed info. A pattern which references the
3960     // null_frag operator is as-if no pattern were specified. Normally this
3961     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3962     // null_frag.
3963     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3964       std::vector<Record*> Results;
3965       std::vector<Record*> Operands;
3966 
3967       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3968 
3969       if (InstInfo.Operands.size() != 0) {
3970         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3971           Results.push_back(InstInfo.Operands[j].Rec);
3972 
3973         // The rest are inputs.
3974         for (unsigned j = InstInfo.Operands.NumDefs,
3975                e = InstInfo.Operands.size(); j < e; ++j)
3976           Operands.push_back(InstInfo.Operands[j].Rec);
3977       }
3978 
3979       // Create and insert the instruction.
3980       std::vector<Record*> ImpResults;
3981       Instructions.insert(std::make_pair(Instr,
3982                             DAGInstruction(Results, Operands, ImpResults)));
3983       continue;  // no pattern.
3984     }
3985 
3986     CodeGenInstruction &CGI = Target.getInstruction(Instr);
3987     parseInstructionPattern(CGI, LI, Instructions);
3988   }
3989 
3990   // If we can, convert the instructions to be patterns that are matched!
3991   for (auto &Entry : Instructions) {
3992     Record *Instr = Entry.first;
3993     DAGInstruction &TheInst = Entry.second;
3994     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3995     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3996 
3997     if (SrcPattern && ResultPattern) {
3998       TreePattern Pattern(Instr, SrcPattern, true, *this);
3999       TreePattern Result(Instr, ResultPattern, false, *this);
4000       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
4001     }
4002   }
4003 }
4004 
4005 typedef std::pair<TreePatternNode *, unsigned> NameRecord;
4006 
4007 static void FindNames(TreePatternNode *P,
4008                       std::map<std::string, NameRecord> &Names,
4009                       TreePattern *PatternTop) {
4010   if (!P->getName().empty()) {
4011     NameRecord &Rec = Names[P->getName()];
4012     // If this is the first instance of the name, remember the node.
4013     if (Rec.second++ == 0)
4014       Rec.first = P;
4015     else if (Rec.first->getExtTypes() != P->getExtTypes())
4016       PatternTop->error("repetition of value: $" + P->getName() +
4017                         " where different uses have different types!");
4018   }
4019 
4020   if (!P->isLeaf()) {
4021     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
4022       FindNames(P->getChild(i), Names, PatternTop);
4023   }
4024 }
4025 
4026 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
4027                                            PatternToMatch &&PTM) {
4028   // Do some sanity checking on the pattern we're about to match.
4029   std::string Reason;
4030   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
4031     PrintWarning(Pattern->getRecord()->getLoc(),
4032       Twine("Pattern can never match: ") + Reason);
4033     return;
4034   }
4035 
4036   // If the source pattern's root is a complex pattern, that complex pattern
4037   // must specify the nodes it can potentially match.
4038   if (const ComplexPattern *CP =
4039         PTM.getSrcPattern()->getComplexPatternInfo(*this))
4040     if (CP->getRootNodes().empty())
4041       Pattern->error("ComplexPattern at root must specify list of opcodes it"
4042                      " could match");
4043 
4044 
4045   // Find all of the named values in the input and output, ensure they have the
4046   // same type.
4047   std::map<std::string, NameRecord> SrcNames, DstNames;
4048   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
4049   FindNames(PTM.getDstPattern(), DstNames, Pattern);
4050 
4051   // Scan all of the named values in the destination pattern, rejecting them if
4052   // they don't exist in the input pattern.
4053   for (const auto &Entry : DstNames) {
4054     if (SrcNames[Entry.first].first == nullptr)
4055       Pattern->error("Pattern has input without matching name in output: $" +
4056                      Entry.first);
4057   }
4058 
4059   // Scan all of the named values in the source pattern, rejecting them if the
4060   // name isn't used in the dest, and isn't used to tie two values together.
4061   for (const auto &Entry : SrcNames)
4062     if (DstNames[Entry.first].first == nullptr &&
4063         SrcNames[Entry.first].second == 1)
4064       Pattern->error("Pattern has dead named input: $" + Entry.first);
4065 
4066   PatternsToMatch.push_back(std::move(PTM));
4067 }
4068 
4069 void CodeGenDAGPatterns::InferInstructionFlags() {
4070   ArrayRef<const CodeGenInstruction*> Instructions =
4071     Target.getInstructionsByEnumValue();
4072 
4073   unsigned Errors = 0;
4074 
4075   // Try to infer flags from all patterns in PatternToMatch.  These include
4076   // both the primary instruction patterns (which always come first) and
4077   // patterns defined outside the instruction.
4078   for (const PatternToMatch &PTM : ptms()) {
4079     // We can only infer from single-instruction patterns, otherwise we won't
4080     // know which instruction should get the flags.
4081     SmallVector<Record*, 8> PatInstrs;
4082     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
4083     if (PatInstrs.size() != 1)
4084       continue;
4085 
4086     // Get the single instruction.
4087     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
4088 
4089     // Only infer properties from the first pattern. We'll verify the others.
4090     if (InstInfo.InferredFrom)
4091       continue;
4092 
4093     InstAnalyzer PatInfo(*this);
4094     PatInfo.Analyze(PTM);
4095     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
4096   }
4097 
4098   if (Errors)
4099     PrintFatalError("pattern conflicts");
4100 
4101   // If requested by the target, guess any undefined properties.
4102   if (Target.guessInstructionProperties()) {
4103     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4104       CodeGenInstruction *InstInfo =
4105         const_cast<CodeGenInstruction *>(Instructions[i]);
4106       if (InstInfo->InferredFrom)
4107         continue;
4108       // The mayLoad and mayStore flags default to false.
4109       // Conservatively assume hasSideEffects if it wasn't explicit.
4110       if (InstInfo->hasSideEffects_Unset)
4111         InstInfo->hasSideEffects = true;
4112     }
4113     return;
4114   }
4115 
4116   // Complain about any flags that are still undefined.
4117   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4118     CodeGenInstruction *InstInfo =
4119       const_cast<CodeGenInstruction *>(Instructions[i]);
4120     if (InstInfo->InferredFrom)
4121       continue;
4122     if (InstInfo->hasSideEffects_Unset)
4123       PrintError(InstInfo->TheDef->getLoc(),
4124                  "Can't infer hasSideEffects from patterns");
4125     if (InstInfo->mayStore_Unset)
4126       PrintError(InstInfo->TheDef->getLoc(),
4127                  "Can't infer mayStore from patterns");
4128     if (InstInfo->mayLoad_Unset)
4129       PrintError(InstInfo->TheDef->getLoc(),
4130                  "Can't infer mayLoad from patterns");
4131   }
4132 }
4133 
4134 
4135 /// Verify instruction flags against pattern node properties.
4136 void CodeGenDAGPatterns::VerifyInstructionFlags() {
4137   unsigned Errors = 0;
4138   for (const PatternToMatch &PTM : ptms()) {
4139     SmallVector<Record*, 8> Instrs;
4140     getInstructionsInTree(PTM.getDstPattern(), Instrs);
4141     if (Instrs.empty())
4142       continue;
4143 
4144     // Count the number of instructions with each flag set.
4145     unsigned NumSideEffects = 0;
4146     unsigned NumStores = 0;
4147     unsigned NumLoads = 0;
4148     for (const Record *Instr : Instrs) {
4149       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4150       NumSideEffects += InstInfo.hasSideEffects;
4151       NumStores += InstInfo.mayStore;
4152       NumLoads += InstInfo.mayLoad;
4153     }
4154 
4155     // Analyze the source pattern.
4156     InstAnalyzer PatInfo(*this);
4157     PatInfo.Analyze(PTM);
4158 
4159     // Collect error messages.
4160     SmallVector<std::string, 4> Msgs;
4161 
4162     // Check for missing flags in the output.
4163     // Permit extra flags for now at least.
4164     if (PatInfo.hasSideEffects && !NumSideEffects)
4165       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4166 
4167     // Don't verify store flags on instructions with side effects. At least for
4168     // intrinsics, side effects implies mayStore.
4169     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4170       Msgs.push_back("pattern may store, but mayStore isn't set");
4171 
4172     // Similarly, mayStore implies mayLoad on intrinsics.
4173     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4174       Msgs.push_back("pattern may load, but mayLoad isn't set");
4175 
4176     // Print error messages.
4177     if (Msgs.empty())
4178       continue;
4179     ++Errors;
4180 
4181     for (const std::string &Msg : Msgs)
4182       PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
4183                  (Instrs.size() == 1 ?
4184                   "instruction" : "output instructions"));
4185     // Provide the location of the relevant instruction definitions.
4186     for (const Record *Instr : Instrs) {
4187       if (Instr != PTM.getSrcRecord())
4188         PrintError(Instr->getLoc(), "defined here");
4189       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4190       if (InstInfo.InferredFrom &&
4191           InstInfo.InferredFrom != InstInfo.TheDef &&
4192           InstInfo.InferredFrom != PTM.getSrcRecord())
4193         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
4194     }
4195   }
4196   if (Errors)
4197     PrintFatalError("Errors in DAG patterns");
4198 }
4199 
4200 /// Given a pattern result with an unresolved type, see if we can find one
4201 /// instruction with an unresolved result type.  Force this result type to an
4202 /// arbitrary element if it's possible types to converge results.
4203 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
4204   if (N->isLeaf())
4205     return false;
4206 
4207   // Analyze children.
4208   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4209     if (ForceArbitraryInstResultType(N->getChild(i), TP))
4210       return true;
4211 
4212   if (!N->getOperator()->isSubClassOf("Instruction"))
4213     return false;
4214 
4215   // If this type is already concrete or completely unknown we can't do
4216   // anything.
4217   TypeInfer &TI = TP.getInfer();
4218   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
4219     if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
4220       continue;
4221 
4222     // Otherwise, force its type to an arbitrary choice.
4223     if (TI.forceArbitrary(N->getExtType(i)))
4224       return true;
4225   }
4226 
4227   return false;
4228 }
4229 
4230 // Promote xform function to be an explicit node wherever set.
4231 static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4232   if (Record *Xform = N->getTransformFn()) {
4233       N->setTransformFn(nullptr);
4234       std::vector<TreePatternNodePtr> Children;
4235       Children.push_back(PromoteXForms(N));
4236       return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4237                                                N->getNumTypes());
4238   }
4239 
4240   if (!N->isLeaf())
4241     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4242       TreePatternNodePtr Child = N->getChildShared(i);
4243       N->setChild(i, PromoteXForms(Child));
4244     }
4245   return N;
4246 }
4247 
4248 void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4249        TreePattern &Pattern, TreePattern &Result,
4250        const std::vector<Record *> &InstImpResults) {
4251 
4252   // Inline pattern fragments and expand multiple alternatives.
4253   Pattern.InlinePatternFragments();
4254   Result.InlinePatternFragments();
4255 
4256   if (Result.getNumTrees() != 1)
4257     Result.error("Cannot use multi-alternative fragments in result pattern!");
4258 
4259   // Infer types.
4260   bool IterateInference;
4261   bool InferredAllPatternTypes, InferredAllResultTypes;
4262   do {
4263     // Infer as many types as possible.  If we cannot infer all of them, we
4264     // can never do anything with this pattern: report it to the user.
4265     InferredAllPatternTypes =
4266         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4267 
4268     // Infer as many types as possible.  If we cannot infer all of them, we
4269     // can never do anything with this pattern: report it to the user.
4270     InferredAllResultTypes =
4271         Result.InferAllTypes(&Pattern.getNamedNodesMap());
4272 
4273     IterateInference = false;
4274 
4275     // Apply the type of the result to the source pattern.  This helps us
4276     // resolve cases where the input type is known to be a pointer type (which
4277     // is considered resolved), but the result knows it needs to be 32- or
4278     // 64-bits.  Infer the other way for good measure.
4279     for (const auto &T : Pattern.getTrees())
4280       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4281                                         T->getNumTypes());
4282          i != e; ++i) {
4283         IterateInference |= T->UpdateNodeType(
4284             i, Result.getOnlyTree()->getExtType(i), Result);
4285         IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4286             i, T->getExtType(i), Result);
4287       }
4288 
4289     // If our iteration has converged and the input pattern's types are fully
4290     // resolved but the result pattern is not fully resolved, we may have a
4291     // situation where we have two instructions in the result pattern and
4292     // the instructions require a common register class, but don't care about
4293     // what actual MVT is used.  This is actually a bug in our modelling:
4294     // output patterns should have register classes, not MVTs.
4295     //
4296     // In any case, to handle this, we just go through and disambiguate some
4297     // arbitrary types to the result pattern's nodes.
4298     if (!IterateInference && InferredAllPatternTypes &&
4299         !InferredAllResultTypes)
4300       IterateInference =
4301           ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4302   } while (IterateInference);
4303 
4304   // Verify that we inferred enough types that we can do something with the
4305   // pattern and result.  If these fire the user has to add type casts.
4306   if (!InferredAllPatternTypes)
4307     Pattern.error("Could not infer all types in pattern!");
4308   if (!InferredAllResultTypes) {
4309     Pattern.dump();
4310     Result.error("Could not infer all types in pattern result!");
4311   }
4312 
4313   // Promote xform function to be an explicit node wherever set.
4314   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4315 
4316   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4317   Temp.InferAllTypes();
4318 
4319   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4320   int Complexity = TheDef->getValueAsInt("AddedComplexity");
4321 
4322   if (PatternRewriter)
4323     PatternRewriter(&Pattern);
4324 
4325   // A pattern may end up with an "impossible" type, i.e. a situation
4326   // where all types have been eliminated for some node in this pattern.
4327   // This could occur for intrinsics that only make sense for a specific
4328   // value type, and use a specific register class. If, for some mode,
4329   // that register class does not accept that type, the type inference
4330   // will lead to a contradiction, which is not an error however, but
4331   // a sign that this pattern will simply never match.
4332   if (Temp.getOnlyTree()->hasPossibleType())
4333     for (const auto &T : Pattern.getTrees())
4334       if (T->hasPossibleType())
4335         AddPatternToMatch(&Pattern,
4336                           PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4337                                          InstImpResults, Complexity,
4338                                          TheDef->getID()));
4339 }
4340 
4341 void CodeGenDAGPatterns::ParsePatterns() {
4342   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4343 
4344   for (Record *CurPattern : Patterns) {
4345     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4346 
4347     // If the pattern references the null_frag, there's nothing to do.
4348     if (hasNullFragReference(Tree))
4349       continue;
4350 
4351     TreePattern Pattern(CurPattern, Tree, true, *this);
4352 
4353     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4354     if (LI->empty()) continue;  // no pattern.
4355 
4356     // Parse the instruction.
4357     TreePattern Result(CurPattern, LI, false, *this);
4358 
4359     if (Result.getNumTrees() != 1)
4360       Result.error("Cannot handle instructions producing instructions "
4361                    "with temporaries yet!");
4362 
4363     // Validate that the input pattern is correct.
4364     std::map<std::string, TreePatternNodePtr> InstInputs;
4365     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4366         InstResults;
4367     std::vector<Record*> InstImpResults;
4368     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4369       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4370                                   InstResults, InstImpResults);
4371 
4372     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
4373   }
4374 }
4375 
4376 static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4377   for (const TypeSetByHwMode &VTS : N->getExtTypes())
4378     for (const auto &I : VTS)
4379       Modes.insert(I.first);
4380 
4381   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4382     collectModes(Modes, N->getChild(i));
4383 }
4384 
4385 void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4386   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4387   std::vector<PatternToMatch> Copy;
4388   PatternsToMatch.swap(Copy);
4389 
4390   auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4391                               StringRef Check) {
4392     TreePatternNodePtr NewSrc = P.getSrcPattern()->clone();
4393     TreePatternNodePtr NewDst = P.getDstPattern()->clone();
4394     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4395       return;
4396     }
4397 
4398     PatternsToMatch.emplace_back(P.getSrcRecord(), P.getPredicates(),
4399                                  std::move(NewSrc), std::move(NewDst),
4400                                  P.getDstRegs(), P.getAddedComplexity(),
4401                                  Record::getNewUID(Records), Mode, Check);
4402   };
4403 
4404   for (PatternToMatch &P : Copy) {
4405     TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
4406     if (P.getSrcPattern()->hasProperTypeByHwMode())
4407       SrcP = P.getSrcPatternShared();
4408     if (P.getDstPattern()->hasProperTypeByHwMode())
4409       DstP = P.getDstPatternShared();
4410     if (!SrcP && !DstP) {
4411       PatternsToMatch.push_back(P);
4412       continue;
4413     }
4414 
4415     std::set<unsigned> Modes;
4416     if (SrcP)
4417       collectModes(Modes, SrcP.get());
4418     if (DstP)
4419       collectModes(Modes, DstP.get());
4420 
4421     // The predicate for the default mode needs to be constructed for each
4422     // pattern separately.
4423     // Since not all modes must be present in each pattern, if a mode m is
4424     // absent, then there is no point in constructing a check for m. If such
4425     // a check was created, it would be equivalent to checking the default
4426     // mode, except not all modes' predicates would be a part of the checking
4427     // code. The subsequently generated check for the default mode would then
4428     // have the exact same patterns, but a different predicate code. To avoid
4429     // duplicated patterns with different predicate checks, construct the
4430     // default check as a negation of all predicates that are actually present
4431     // in the source/destination patterns.
4432     SmallString<128> DefaultCheck;
4433 
4434     for (unsigned M : Modes) {
4435       if (M == DefaultMode)
4436         continue;
4437 
4438       // Fill the map entry for this mode.
4439       const HwMode &HM = CGH.getMode(M);
4440       AppendPattern(P, M, "(MF->getSubtarget().checkFeatures(\"" + HM.Features + "\"))");
4441 
4442       // Add negations of the HM's predicates to the default predicate.
4443       if (!DefaultCheck.empty())
4444         DefaultCheck += " && ";
4445       DefaultCheck += "(!(MF->getSubtarget().checkFeatures(\"";
4446       DefaultCheck += HM.Features;
4447       DefaultCheck += "\")))";
4448     }
4449 
4450     bool HasDefault = Modes.count(DefaultMode);
4451     if (HasDefault)
4452       AppendPattern(P, DefaultMode, DefaultCheck);
4453   }
4454 }
4455 
4456 /// Dependent variable map for CodeGenDAGPattern variant generation
4457 typedef StringMap<int> DepVarMap;
4458 
4459 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4460   if (N->isLeaf()) {
4461     if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4462       DepMap[N->getName()]++;
4463   } else {
4464     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4465       FindDepVarsOf(N->getChild(i), DepMap);
4466   }
4467 }
4468 
4469 /// Find dependent variables within child patterns
4470 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4471   DepVarMap depcounts;
4472   FindDepVarsOf(N, depcounts);
4473   for (const auto &Pair : depcounts) {
4474     if (Pair.getValue() > 1)
4475       DepVars.insert(Pair.getKey());
4476   }
4477 }
4478 
4479 #ifndef NDEBUG
4480 /// Dump the dependent variable set:
4481 static void DumpDepVars(MultipleUseVarSet &DepVars) {
4482   if (DepVars.empty()) {
4483     LLVM_DEBUG(errs() << "<empty set>");
4484   } else {
4485     LLVM_DEBUG(errs() << "[ ");
4486     for (const auto &DepVar : DepVars) {
4487       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4488     }
4489     LLVM_DEBUG(errs() << "]");
4490   }
4491 }
4492 #endif
4493 
4494 
4495 /// CombineChildVariants - Given a bunch of permutations of each child of the
4496 /// 'operator' node, put them together in all possible ways.
4497 static void CombineChildVariants(
4498     TreePatternNodePtr Orig,
4499     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4500     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4501     const MultipleUseVarSet &DepVars) {
4502   // Make sure that each operand has at least one variant to choose from.
4503   for (const auto &Variants : ChildVariants)
4504     if (Variants.empty())
4505       return;
4506 
4507   // The end result is an all-pairs construction of the resultant pattern.
4508   std::vector<unsigned> Idxs;
4509   Idxs.resize(ChildVariants.size());
4510   bool NotDone;
4511   do {
4512 #ifndef NDEBUG
4513     LLVM_DEBUG(if (!Idxs.empty()) {
4514       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4515       for (unsigned Idx : Idxs) {
4516         errs() << Idx << " ";
4517       }
4518       errs() << "]\n";
4519     });
4520 #endif
4521     // Create the variant and add it to the output list.
4522     std::vector<TreePatternNodePtr> NewChildren;
4523     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4524       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4525     TreePatternNodePtr R = std::make_shared<TreePatternNode>(
4526         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4527 
4528     // Copy over properties.
4529     R->setName(Orig->getName());
4530     R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4531     R->setPredicateCalls(Orig->getPredicateCalls());
4532     R->setTransformFn(Orig->getTransformFn());
4533     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4534       R->setType(i, Orig->getExtType(i));
4535 
4536     // If this pattern cannot match, do not include it as a variant.
4537     std::string ErrString;
4538     // Scan to see if this pattern has already been emitted.  We can get
4539     // duplication due to things like commuting:
4540     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4541     // which are the same pattern.  Ignore the dups.
4542     if (R->canPatternMatch(ErrString, CDP) &&
4543         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4544           return R->isIsomorphicTo(Variant.get(), DepVars);
4545         }))
4546       OutVariants.push_back(R);
4547 
4548     // Increment indices to the next permutation by incrementing the
4549     // indices from last index backward, e.g., generate the sequence
4550     // [0, 0], [0, 1], [1, 0], [1, 1].
4551     int IdxsIdx;
4552     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4553       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4554         Idxs[IdxsIdx] = 0;
4555       else
4556         break;
4557     }
4558     NotDone = (IdxsIdx >= 0);
4559   } while (NotDone);
4560 }
4561 
4562 /// CombineChildVariants - A helper function for binary operators.
4563 ///
4564 static void CombineChildVariants(TreePatternNodePtr Orig,
4565                                  const std::vector<TreePatternNodePtr> &LHS,
4566                                  const std::vector<TreePatternNodePtr> &RHS,
4567                                  std::vector<TreePatternNodePtr> &OutVariants,
4568                                  CodeGenDAGPatterns &CDP,
4569                                  const MultipleUseVarSet &DepVars) {
4570   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4571   ChildVariants.push_back(LHS);
4572   ChildVariants.push_back(RHS);
4573   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4574 }
4575 
4576 static void
4577 GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4578                                   std::vector<TreePatternNodePtr> &Children) {
4579   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4580   Record *Operator = N->getOperator();
4581 
4582   // Only permit raw nodes.
4583   if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4584       N->getTransformFn()) {
4585     Children.push_back(N);
4586     return;
4587   }
4588 
4589   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4590     Children.push_back(N->getChildShared(0));
4591   else
4592     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4593 
4594   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4595     Children.push_back(N->getChildShared(1));
4596   else
4597     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4598 }
4599 
4600 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4601 /// the (potentially recursive) pattern by using algebraic laws.
4602 ///
4603 static void GenerateVariantsOf(TreePatternNodePtr N,
4604                                std::vector<TreePatternNodePtr> &OutVariants,
4605                                CodeGenDAGPatterns &CDP,
4606                                const MultipleUseVarSet &DepVars) {
4607   // We cannot permute leaves or ComplexPattern uses.
4608   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4609     OutVariants.push_back(N);
4610     return;
4611   }
4612 
4613   // Look up interesting info about the node.
4614   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4615 
4616   // If this node is associative, re-associate.
4617   if (NodeInfo.hasProperty(SDNPAssociative)) {
4618     // Re-associate by pulling together all of the linked operators
4619     std::vector<TreePatternNodePtr> MaximalChildren;
4620     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4621 
4622     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4623     // permutations.
4624     if (MaximalChildren.size() == 3) {
4625       // Find the variants of all of our maximal children.
4626       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4627       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4628       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4629       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4630 
4631       // There are only two ways we can permute the tree:
4632       //   (A op B) op C    and    A op (B op C)
4633       // Within these forms, we can also permute A/B/C.
4634 
4635       // Generate legal pair permutations of A/B/C.
4636       std::vector<TreePatternNodePtr> ABVariants;
4637       std::vector<TreePatternNodePtr> BAVariants;
4638       std::vector<TreePatternNodePtr> ACVariants;
4639       std::vector<TreePatternNodePtr> CAVariants;
4640       std::vector<TreePatternNodePtr> BCVariants;
4641       std::vector<TreePatternNodePtr> CBVariants;
4642       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4643       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4644       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4645       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4646       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4647       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4648 
4649       // Combine those into the result: (x op x) op x
4650       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4651       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4652       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4653       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4654       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4655       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4656 
4657       // Combine those into the result: x op (x op x)
4658       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4659       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4660       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4661       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4662       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4663       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4664       return;
4665     }
4666   }
4667 
4668   // Compute permutations of all children.
4669   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4670   ChildVariants.resize(N->getNumChildren());
4671   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4672     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4673 
4674   // Build all permutations based on how the children were formed.
4675   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4676 
4677   // If this node is commutative, consider the commuted order.
4678   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4679   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4680     unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4681     assert(N->getNumChildren() >= (2 + Skip) &&
4682            "Commutative but doesn't have 2 children!");
4683     // Don't allow commuting children which are actually register references.
4684     bool NoRegisters = true;
4685     unsigned i = 0 + Skip;
4686     unsigned e = 2 + Skip;
4687     for (; i != e; ++i) {
4688       TreePatternNode *Child = N->getChild(i);
4689       if (Child->isLeaf())
4690         if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4691           Record *RR = DI->getDef();
4692           if (RR->isSubClassOf("Register"))
4693             NoRegisters = false;
4694         }
4695     }
4696     // Consider the commuted order.
4697     if (NoRegisters) {
4698       std::vector<std::vector<TreePatternNodePtr>> Variants;
4699       unsigned i = 0;
4700       if (isCommIntrinsic)
4701         Variants.push_back(std::move(ChildVariants[i++])); // Intrinsic id.
4702       Variants.push_back(std::move(ChildVariants[i + 1]));
4703       Variants.push_back(std::move(ChildVariants[i]));
4704       i += 2;
4705       // Remaining operands are not commuted.
4706       for (; i != N->getNumChildren(); ++i)
4707         Variants.push_back(std::move(ChildVariants[i]));
4708       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4709     }
4710   }
4711 }
4712 
4713 
4714 // GenerateVariants - Generate variants.  For example, commutative patterns can
4715 // match multiple ways.  Add them to PatternsToMatch as well.
4716 void CodeGenDAGPatterns::GenerateVariants() {
4717   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4718 
4719   // Loop over all of the patterns we've collected, checking to see if we can
4720   // generate variants of the instruction, through the exploitation of
4721   // identities.  This permits the target to provide aggressive matching without
4722   // the .td file having to contain tons of variants of instructions.
4723   //
4724   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4725   // intentionally do not reconsider these.  Any variants of added patterns have
4726   // already been added.
4727   //
4728   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4729     MultipleUseVarSet DepVars;
4730     std::vector<TreePatternNodePtr> Variants;
4731     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4732     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4733     LLVM_DEBUG(DumpDepVars(DepVars));
4734     LLVM_DEBUG(errs() << "\n");
4735     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4736                        *this, DepVars);
4737 
4738     assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4739            "HwModes should not have been expanded yet!");
4740 
4741     assert(!Variants.empty() && "Must create at least original variant!");
4742     if (Variants.size() == 1) // No additional variants for this pattern.
4743       continue;
4744 
4745     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4746                PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
4747 
4748     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4749       TreePatternNodePtr Variant = Variants[v];
4750 
4751       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
4752                  errs() << "\n");
4753 
4754       // Scan to see if an instruction or explicit pattern already matches this.
4755       bool AlreadyExists = false;
4756       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4757         // Skip if the top level predicates do not match.
4758         if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4759                          PatternsToMatch[p].getPredicates()))
4760           continue;
4761         // Check to see if this variant already exists.
4762         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4763                                     DepVars)) {
4764           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4765           AlreadyExists = true;
4766           break;
4767         }
4768       }
4769       // If we already have it, ignore the variant.
4770       if (AlreadyExists) continue;
4771 
4772       // Otherwise, add it to the list of patterns we have.
4773       PatternsToMatch.emplace_back(
4774           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4775           Variant, PatternsToMatch[i].getDstPatternShared(),
4776           PatternsToMatch[i].getDstRegs(),
4777           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID(Records),
4778           PatternsToMatch[i].getForceMode(),
4779           PatternsToMatch[i].getHwModeFeatures());
4780     }
4781 
4782     LLVM_DEBUG(errs() << "\n");
4783   }
4784 }
4785