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