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