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