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