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