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