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