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