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