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