xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/PatternMatch.h (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 //===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides a simple and efficient mechanism for performing general
10 // tree-based pattern matches on the LLVM IR. The power of these routines is
11 // that it allows you to write concise patterns that are expressive and easy to
12 // understand. The other major advantage of this is that it allows you to
13 // trivially capture/bind elements in the pattern to variables. For example,
14 // you can do something like this:
15 //
16 //  Value *Exp = ...
17 //  Value *X, *Y;  ConstantInt *C1, *C2;      // (X & C1) | (Y & C2)
18 //  if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
19 //                      m_And(m_Value(Y), m_ConstantInt(C2))))) {
20 //    ... Pattern is matched and variables are bound ...
21 //  }
22 //
23 // This is primarily useful to things like the instruction combiner, but can
24 // also be useful for static analysis tools or code generators.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #ifndef LLVM_IR_PATTERNMATCH_H
29 #define LLVM_IR_PATTERNMATCH_H
30 
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
44 #include <cstdint>
45 
46 namespace llvm {
47 namespace PatternMatch {
48 
49 template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50   return const_cast<Pattern &>(P).match(V);
51 }
52 
53 template <typename Pattern> bool match(ArrayRef<int> Mask, const Pattern &P) {
54   return const_cast<Pattern &>(P).match(Mask);
55 }
56 
57 template <typename SubPattern_t> struct OneUse_match {
58   SubPattern_t SubPattern;
59 
60   OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
61 
62   template <typename OpTy> bool match(OpTy *V) {
63     return V->hasOneUse() && SubPattern.match(V);
64   }
65 };
66 
67 template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
68   return SubPattern;
69 }
70 
71 template <typename SubPattern_t> struct AllowReassoc_match {
72   SubPattern_t SubPattern;
73 
74   AllowReassoc_match(const SubPattern_t &SP) : SubPattern(SP) {}
75 
76   template <typename OpTy> bool match(OpTy *V) {
77     auto *I = dyn_cast<FPMathOperator>(V);
78     return I && I->hasAllowReassoc() && SubPattern.match(I);
79   }
80 };
81 
82 template <typename T>
83 inline AllowReassoc_match<T> m_AllowReassoc(const T &SubPattern) {
84   return SubPattern;
85 }
86 
87 template <typename Class> struct class_match {
88   template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
89 };
90 
91 /// Match an arbitrary value and ignore it.
92 inline class_match<Value> m_Value() { return class_match<Value>(); }
93 
94 /// Match an arbitrary unary operation and ignore it.
95 inline class_match<UnaryOperator> m_UnOp() {
96   return class_match<UnaryOperator>();
97 }
98 
99 /// Match an arbitrary binary operation and ignore it.
100 inline class_match<BinaryOperator> m_BinOp() {
101   return class_match<BinaryOperator>();
102 }
103 
104 /// Matches any compare instruction and ignore it.
105 inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
106 
107 struct undef_match {
108   static bool check(const Value *V) {
109     if (isa<UndefValue>(V))
110       return true;
111 
112     const auto *CA = dyn_cast<ConstantAggregate>(V);
113     if (!CA)
114       return false;
115 
116     SmallPtrSet<const ConstantAggregate *, 8> Seen;
117     SmallVector<const ConstantAggregate *, 8> Worklist;
118 
119     // Either UndefValue, PoisonValue, or an aggregate that only contains
120     // these is accepted by matcher.
121     // CheckValue returns false if CA cannot satisfy this constraint.
122     auto CheckValue = [&](const ConstantAggregate *CA) {
123       for (const Value *Op : CA->operand_values()) {
124         if (isa<UndefValue>(Op))
125           continue;
126 
127         const auto *CA = dyn_cast<ConstantAggregate>(Op);
128         if (!CA)
129           return false;
130         if (Seen.insert(CA).second)
131           Worklist.emplace_back(CA);
132       }
133 
134       return true;
135     };
136 
137     if (!CheckValue(CA))
138       return false;
139 
140     while (!Worklist.empty()) {
141       if (!CheckValue(Worklist.pop_back_val()))
142         return false;
143     }
144     return true;
145   }
146   template <typename ITy> bool match(ITy *V) { return check(V); }
147 };
148 
149 /// Match an arbitrary undef constant. This matches poison as well.
150 /// If this is an aggregate and contains a non-aggregate element that is
151 /// neither undef nor poison, the aggregate is not matched.
152 inline auto m_Undef() { return undef_match(); }
153 
154 /// Match an arbitrary UndefValue constant.
155 inline class_match<UndefValue> m_UndefValue() {
156   return class_match<UndefValue>();
157 }
158 
159 /// Match an arbitrary poison constant.
160 inline class_match<PoisonValue> m_Poison() {
161   return class_match<PoisonValue>();
162 }
163 
164 /// Match an arbitrary Constant and ignore it.
165 inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
166 
167 /// Match an arbitrary ConstantInt and ignore it.
168 inline class_match<ConstantInt> m_ConstantInt() {
169   return class_match<ConstantInt>();
170 }
171 
172 /// Match an arbitrary ConstantFP and ignore it.
173 inline class_match<ConstantFP> m_ConstantFP() {
174   return class_match<ConstantFP>();
175 }
176 
177 struct constantexpr_match {
178   template <typename ITy> bool match(ITy *V) {
179     auto *C = dyn_cast<Constant>(V);
180     return C && (isa<ConstantExpr>(C) || C->containsConstantExpression());
181   }
182 };
183 
184 /// Match a constant expression or a constant that contains a constant
185 /// expression.
186 inline constantexpr_match m_ConstantExpr() { return constantexpr_match(); }
187 
188 /// Match an arbitrary basic block value and ignore it.
189 inline class_match<BasicBlock> m_BasicBlock() {
190   return class_match<BasicBlock>();
191 }
192 
193 /// Inverting matcher
194 template <typename Ty> struct match_unless {
195   Ty M;
196 
197   match_unless(const Ty &Matcher) : M(Matcher) {}
198 
199   template <typename ITy> bool match(ITy *V) { return !M.match(V); }
200 };
201 
202 /// Match if the inner matcher does *NOT* match.
203 template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) {
204   return match_unless<Ty>(M);
205 }
206 
207 /// Matching combinators
208 template <typename LTy, typename RTy> struct match_combine_or {
209   LTy L;
210   RTy R;
211 
212   match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
213 
214   template <typename ITy> bool match(ITy *V) {
215     if (L.match(V))
216       return true;
217     if (R.match(V))
218       return true;
219     return false;
220   }
221 };
222 
223 template <typename LTy, typename RTy> struct match_combine_and {
224   LTy L;
225   RTy R;
226 
227   match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
228 
229   template <typename ITy> bool match(ITy *V) {
230     if (L.match(V))
231       if (R.match(V))
232         return true;
233     return false;
234   }
235 };
236 
237 /// Combine two pattern matchers matching L || R
238 template <typename LTy, typename RTy>
239 inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
240   return match_combine_or<LTy, RTy>(L, R);
241 }
242 
243 /// Combine two pattern matchers matching L && R
244 template <typename LTy, typename RTy>
245 inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
246   return match_combine_and<LTy, RTy>(L, R);
247 }
248 
249 struct apint_match {
250   const APInt *&Res;
251   bool AllowPoison;
252 
253   apint_match(const APInt *&Res, bool AllowPoison)
254       : Res(Res), AllowPoison(AllowPoison) {}
255 
256   template <typename ITy> bool match(ITy *V) {
257     if (auto *CI = dyn_cast<ConstantInt>(V)) {
258       Res = &CI->getValue();
259       return true;
260     }
261     if (V->getType()->isVectorTy())
262       if (const auto *C = dyn_cast<Constant>(V))
263         if (auto *CI =
264                 dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowPoison))) {
265           Res = &CI->getValue();
266           return true;
267         }
268     return false;
269   }
270 };
271 // Either constexpr if or renaming ConstantFP::getValueAPF to
272 // ConstantFP::getValue is needed to do it via single template
273 // function for both apint/apfloat.
274 struct apfloat_match {
275   const APFloat *&Res;
276   bool AllowPoison;
277 
278   apfloat_match(const APFloat *&Res, bool AllowPoison)
279       : Res(Res), AllowPoison(AllowPoison) {}
280 
281   template <typename ITy> bool match(ITy *V) {
282     if (auto *CI = dyn_cast<ConstantFP>(V)) {
283       Res = &CI->getValueAPF();
284       return true;
285     }
286     if (V->getType()->isVectorTy())
287       if (const auto *C = dyn_cast<Constant>(V))
288         if (auto *CI =
289                 dyn_cast_or_null<ConstantFP>(C->getSplatValue(AllowPoison))) {
290           Res = &CI->getValueAPF();
291           return true;
292         }
293     return false;
294   }
295 };
296 
297 /// Match a ConstantInt or splatted ConstantVector, binding the
298 /// specified pointer to the contained APInt.
299 inline apint_match m_APInt(const APInt *&Res) {
300   // Forbid poison by default to maintain previous behavior.
301   return apint_match(Res, /* AllowPoison */ false);
302 }
303 
304 /// Match APInt while allowing poison in splat vector constants.
305 inline apint_match m_APIntAllowPoison(const APInt *&Res) {
306   return apint_match(Res, /* AllowPoison */ true);
307 }
308 
309 /// Match APInt while forbidding poison in splat vector constants.
310 inline apint_match m_APIntForbidPoison(const APInt *&Res) {
311   return apint_match(Res, /* AllowPoison */ false);
312 }
313 
314 /// Match a ConstantFP or splatted ConstantVector, binding the
315 /// specified pointer to the contained APFloat.
316 inline apfloat_match m_APFloat(const APFloat *&Res) {
317   // Forbid undefs by default to maintain previous behavior.
318   return apfloat_match(Res, /* AllowPoison */ false);
319 }
320 
321 /// Match APFloat while allowing poison in splat vector constants.
322 inline apfloat_match m_APFloatAllowPoison(const APFloat *&Res) {
323   return apfloat_match(Res, /* AllowPoison */ true);
324 }
325 
326 /// Match APFloat while forbidding poison in splat vector constants.
327 inline apfloat_match m_APFloatForbidPoison(const APFloat *&Res) {
328   return apfloat_match(Res, /* AllowPoison */ false);
329 }
330 
331 template <int64_t Val> struct constantint_match {
332   template <typename ITy> bool match(ITy *V) {
333     if (const auto *CI = dyn_cast<ConstantInt>(V)) {
334       const APInt &CIV = CI->getValue();
335       if (Val >= 0)
336         return CIV == static_cast<uint64_t>(Val);
337       // If Val is negative, and CI is shorter than it, truncate to the right
338       // number of bits.  If it is larger, then we have to sign extend.  Just
339       // compare their negated values.
340       return -CIV == -Val;
341     }
342     return false;
343   }
344 };
345 
346 /// Match a ConstantInt with a specific value.
347 template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
348   return constantint_match<Val>();
349 }
350 
351 /// This helper class is used to match constant scalars, vector splats,
352 /// and fixed width vectors that satisfy a specified predicate.
353 /// For fixed width vector constants, poison elements are ignored if AllowPoison
354 /// is true.
355 template <typename Predicate, typename ConstantVal, bool AllowPoison>
356 struct cstval_pred_ty : public Predicate {
357   const Constant **Res = nullptr;
358   template <typename ITy> bool match_impl(ITy *V) {
359     if (const auto *CV = dyn_cast<ConstantVal>(V))
360       return this->isValue(CV->getValue());
361     if (const auto *VTy = dyn_cast<VectorType>(V->getType())) {
362       if (const auto *C = dyn_cast<Constant>(V)) {
363         if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue()))
364           return this->isValue(CV->getValue());
365 
366         // Number of elements of a scalable vector unknown at compile time
367         auto *FVTy = dyn_cast<FixedVectorType>(VTy);
368         if (!FVTy)
369           return false;
370 
371         // Non-splat vector constant: check each element for a match.
372         unsigned NumElts = FVTy->getNumElements();
373         assert(NumElts != 0 && "Constant vector with no elements?");
374         bool HasNonPoisonElements = false;
375         for (unsigned i = 0; i != NumElts; ++i) {
376           Constant *Elt = C->getAggregateElement(i);
377           if (!Elt)
378             return false;
379           if (AllowPoison && isa<PoisonValue>(Elt))
380             continue;
381           auto *CV = dyn_cast<ConstantVal>(Elt);
382           if (!CV || !this->isValue(CV->getValue()))
383             return false;
384           HasNonPoisonElements = true;
385         }
386         return HasNonPoisonElements;
387       }
388     }
389     return false;
390   }
391 
392   template <typename ITy> bool match(ITy *V) {
393     if (this->match_impl(V)) {
394       if (Res)
395         *Res = cast<Constant>(V);
396       return true;
397     }
398     return false;
399   }
400 };
401 
402 /// specialization of cstval_pred_ty for ConstantInt
403 template <typename Predicate, bool AllowPoison = true>
404 using cst_pred_ty = cstval_pred_ty<Predicate, ConstantInt, AllowPoison>;
405 
406 /// specialization of cstval_pred_ty for ConstantFP
407 template <typename Predicate>
408 using cstfp_pred_ty = cstval_pred_ty<Predicate, ConstantFP,
409                                      /*AllowPoison=*/true>;
410 
411 /// This helper class is used to match scalar and vector constants that
412 /// satisfy a specified predicate, and bind them to an APInt.
413 template <typename Predicate> struct api_pred_ty : public Predicate {
414   const APInt *&Res;
415 
416   api_pred_ty(const APInt *&R) : Res(R) {}
417 
418   template <typename ITy> bool match(ITy *V) {
419     if (const auto *CI = dyn_cast<ConstantInt>(V))
420       if (this->isValue(CI->getValue())) {
421         Res = &CI->getValue();
422         return true;
423       }
424     if (V->getType()->isVectorTy())
425       if (const auto *C = dyn_cast<Constant>(V))
426         if (auto *CI = dyn_cast_or_null<ConstantInt>(
427                 C->getSplatValue(/*AllowPoison=*/true)))
428           if (this->isValue(CI->getValue())) {
429             Res = &CI->getValue();
430             return true;
431           }
432 
433     return false;
434   }
435 };
436 
437 /// This helper class is used to match scalar and vector constants that
438 /// satisfy a specified predicate, and bind them to an APFloat.
439 /// Poison is allowed in splat vector constants.
440 template <typename Predicate> struct apf_pred_ty : public Predicate {
441   const APFloat *&Res;
442 
443   apf_pred_ty(const APFloat *&R) : Res(R) {}
444 
445   template <typename ITy> bool match(ITy *V) {
446     if (const auto *CI = dyn_cast<ConstantFP>(V))
447       if (this->isValue(CI->getValue())) {
448         Res = &CI->getValue();
449         return true;
450       }
451     if (V->getType()->isVectorTy())
452       if (const auto *C = dyn_cast<Constant>(V))
453         if (auto *CI = dyn_cast_or_null<ConstantFP>(
454                 C->getSplatValue(/* AllowPoison */ true)))
455           if (this->isValue(CI->getValue())) {
456             Res = &CI->getValue();
457             return true;
458           }
459 
460     return false;
461   }
462 };
463 
464 ///////////////////////////////////////////////////////////////////////////////
465 //
466 // Encapsulate constant value queries for use in templated predicate matchers.
467 // This allows checking if constants match using compound predicates and works
468 // with vector constants, possibly with relaxed constraints. For example, ignore
469 // undef values.
470 //
471 ///////////////////////////////////////////////////////////////////////////////
472 
473 template <typename APTy> struct custom_checkfn {
474   function_ref<bool(const APTy &)> CheckFn;
475   bool isValue(const APTy &C) { return CheckFn(C); }
476 };
477 
478 /// Match an integer or vector where CheckFn(ele) for each element is true.
479 /// For vectors, poison elements are assumed to match.
480 inline cst_pred_ty<custom_checkfn<APInt>>
481 m_CheckedInt(function_ref<bool(const APInt &)> CheckFn) {
482   return cst_pred_ty<custom_checkfn<APInt>>{{CheckFn}};
483 }
484 
485 inline cst_pred_ty<custom_checkfn<APInt>>
486 m_CheckedInt(const Constant *&V, function_ref<bool(const APInt &)> CheckFn) {
487   return cst_pred_ty<custom_checkfn<APInt>>{{CheckFn}, &V};
488 }
489 
490 /// Match a float or vector where CheckFn(ele) for each element is true.
491 /// For vectors, poison elements are assumed to match.
492 inline cstfp_pred_ty<custom_checkfn<APFloat>>
493 m_CheckedFp(function_ref<bool(const APFloat &)> CheckFn) {
494   return cstfp_pred_ty<custom_checkfn<APFloat>>{{CheckFn}};
495 }
496 
497 inline cstfp_pred_ty<custom_checkfn<APFloat>>
498 m_CheckedFp(const Constant *&V, function_ref<bool(const APFloat &)> CheckFn) {
499   return cstfp_pred_ty<custom_checkfn<APFloat>>{{CheckFn}, &V};
500 }
501 
502 struct is_any_apint {
503   bool isValue(const APInt &C) { return true; }
504 };
505 /// Match an integer or vector with any integral constant.
506 /// For vectors, this includes constants with undefined elements.
507 inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() {
508   return cst_pred_ty<is_any_apint>();
509 }
510 
511 struct is_shifted_mask {
512   bool isValue(const APInt &C) { return C.isShiftedMask(); }
513 };
514 
515 inline cst_pred_ty<is_shifted_mask> m_ShiftedMask() {
516   return cst_pred_ty<is_shifted_mask>();
517 }
518 
519 struct is_all_ones {
520   bool isValue(const APInt &C) { return C.isAllOnes(); }
521 };
522 /// Match an integer or vector with all bits set.
523 /// For vectors, this includes constants with undefined elements.
524 inline cst_pred_ty<is_all_ones> m_AllOnes() {
525   return cst_pred_ty<is_all_ones>();
526 }
527 
528 inline cst_pred_ty<is_all_ones, false> m_AllOnesForbidPoison() {
529   return cst_pred_ty<is_all_ones, false>();
530 }
531 
532 struct is_maxsignedvalue {
533   bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
534 };
535 /// Match an integer or vector with values having all bits except for the high
536 /// bit set (0x7f...).
537 /// For vectors, this includes constants with undefined elements.
538 inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
539   return cst_pred_ty<is_maxsignedvalue>();
540 }
541 inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
542   return V;
543 }
544 
545 struct is_negative {
546   bool isValue(const APInt &C) { return C.isNegative(); }
547 };
548 /// Match an integer or vector of negative values.
549 /// For vectors, this includes constants with undefined elements.
550 inline cst_pred_ty<is_negative> m_Negative() {
551   return cst_pred_ty<is_negative>();
552 }
553 inline api_pred_ty<is_negative> m_Negative(const APInt *&V) { return V; }
554 
555 struct is_nonnegative {
556   bool isValue(const APInt &C) { return C.isNonNegative(); }
557 };
558 /// Match an integer or vector of non-negative values.
559 /// For vectors, this includes constants with undefined elements.
560 inline cst_pred_ty<is_nonnegative> m_NonNegative() {
561   return cst_pred_ty<is_nonnegative>();
562 }
563 inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) { return V; }
564 
565 struct is_strictlypositive {
566   bool isValue(const APInt &C) { return C.isStrictlyPositive(); }
567 };
568 /// Match an integer or vector of strictly positive values.
569 /// For vectors, this includes constants with undefined elements.
570 inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() {
571   return cst_pred_ty<is_strictlypositive>();
572 }
573 inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) {
574   return V;
575 }
576 
577 struct is_nonpositive {
578   bool isValue(const APInt &C) { return C.isNonPositive(); }
579 };
580 /// Match an integer or vector of non-positive values.
581 /// For vectors, this includes constants with undefined elements.
582 inline cst_pred_ty<is_nonpositive> m_NonPositive() {
583   return cst_pred_ty<is_nonpositive>();
584 }
585 inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; }
586 
587 struct is_one {
588   bool isValue(const APInt &C) { return C.isOne(); }
589 };
590 /// Match an integer 1 or a vector with all elements equal to 1.
591 /// For vectors, this includes constants with undefined elements.
592 inline cst_pred_ty<is_one> m_One() { return cst_pred_ty<is_one>(); }
593 
594 struct is_zero_int {
595   bool isValue(const APInt &C) { return C.isZero(); }
596 };
597 /// Match an integer 0 or a vector with all elements equal to 0.
598 /// For vectors, this includes constants with undefined elements.
599 inline cst_pred_ty<is_zero_int> m_ZeroInt() {
600   return cst_pred_ty<is_zero_int>();
601 }
602 
603 struct is_zero {
604   template <typename ITy> bool match(ITy *V) {
605     auto *C = dyn_cast<Constant>(V);
606     // FIXME: this should be able to do something for scalable vectors
607     return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
608   }
609 };
610 /// Match any null constant or a vector with all elements equal to 0.
611 /// For vectors, this includes constants with undefined elements.
612 inline is_zero m_Zero() { return is_zero(); }
613 
614 struct is_power2 {
615   bool isValue(const APInt &C) { return C.isPowerOf2(); }
616 };
617 /// Match an integer or vector power-of-2.
618 /// For vectors, this includes constants with undefined elements.
619 inline cst_pred_ty<is_power2> m_Power2() { return cst_pred_ty<is_power2>(); }
620 inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { return V; }
621 
622 struct is_negated_power2 {
623   bool isValue(const APInt &C) { return C.isNegatedPowerOf2(); }
624 };
625 /// Match a integer or vector negated power-of-2.
626 /// For vectors, this includes constants with undefined elements.
627 inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
628   return cst_pred_ty<is_negated_power2>();
629 }
630 inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
631   return V;
632 }
633 
634 struct is_negated_power2_or_zero {
635   bool isValue(const APInt &C) { return !C || C.isNegatedPowerOf2(); }
636 };
637 /// Match a integer or vector negated power-of-2.
638 /// For vectors, this includes constants with undefined elements.
639 inline cst_pred_ty<is_negated_power2_or_zero> m_NegatedPower2OrZero() {
640   return cst_pred_ty<is_negated_power2_or_zero>();
641 }
642 inline api_pred_ty<is_negated_power2_or_zero>
643 m_NegatedPower2OrZero(const APInt *&V) {
644   return V;
645 }
646 
647 struct is_power2_or_zero {
648   bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
649 };
650 /// Match an integer or vector of 0 or power-of-2 values.
651 /// For vectors, this includes constants with undefined elements.
652 inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
653   return cst_pred_ty<is_power2_or_zero>();
654 }
655 inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
656   return V;
657 }
658 
659 struct is_sign_mask {
660   bool isValue(const APInt &C) { return C.isSignMask(); }
661 };
662 /// Match an integer or vector with only the sign bit(s) set.
663 /// For vectors, this includes constants with undefined elements.
664 inline cst_pred_ty<is_sign_mask> m_SignMask() {
665   return cst_pred_ty<is_sign_mask>();
666 }
667 
668 struct is_lowbit_mask {
669   bool isValue(const APInt &C) { return C.isMask(); }
670 };
671 /// Match an integer or vector with only the low bit(s) set.
672 /// For vectors, this includes constants with undefined elements.
673 inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
674   return cst_pred_ty<is_lowbit_mask>();
675 }
676 inline api_pred_ty<is_lowbit_mask> m_LowBitMask(const APInt *&V) { return V; }
677 
678 struct is_lowbit_mask_or_zero {
679   bool isValue(const APInt &C) { return !C || C.isMask(); }
680 };
681 /// Match an integer or vector with only the low bit(s) set.
682 /// For vectors, this includes constants with undefined elements.
683 inline cst_pred_ty<is_lowbit_mask_or_zero> m_LowBitMaskOrZero() {
684   return cst_pred_ty<is_lowbit_mask_or_zero>();
685 }
686 inline api_pred_ty<is_lowbit_mask_or_zero> m_LowBitMaskOrZero(const APInt *&V) {
687   return V;
688 }
689 
690 struct icmp_pred_with_threshold {
691   ICmpInst::Predicate Pred;
692   const APInt *Thr;
693   bool isValue(const APInt &C) { return ICmpInst::compare(C, *Thr, Pred); }
694 };
695 /// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
696 /// to Threshold. For vectors, this includes constants with undefined elements.
697 inline cst_pred_ty<icmp_pred_with_threshold>
698 m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
699   cst_pred_ty<icmp_pred_with_threshold> P;
700   P.Pred = Predicate;
701   P.Thr = &Threshold;
702   return P;
703 }
704 
705 struct is_nan {
706   bool isValue(const APFloat &C) { return C.isNaN(); }
707 };
708 /// Match an arbitrary NaN constant. This includes quiet and signalling nans.
709 /// For vectors, this includes constants with undefined elements.
710 inline cstfp_pred_ty<is_nan> m_NaN() { return cstfp_pred_ty<is_nan>(); }
711 
712 struct is_nonnan {
713   bool isValue(const APFloat &C) { return !C.isNaN(); }
714 };
715 /// Match a non-NaN FP constant.
716 /// For vectors, this includes constants with undefined elements.
717 inline cstfp_pred_ty<is_nonnan> m_NonNaN() {
718   return cstfp_pred_ty<is_nonnan>();
719 }
720 
721 struct is_inf {
722   bool isValue(const APFloat &C) { return C.isInfinity(); }
723 };
724 /// Match a positive or negative infinity FP constant.
725 /// For vectors, this includes constants with undefined elements.
726 inline cstfp_pred_ty<is_inf> m_Inf() { return cstfp_pred_ty<is_inf>(); }
727 
728 struct is_noninf {
729   bool isValue(const APFloat &C) { return !C.isInfinity(); }
730 };
731 /// Match a non-infinity FP constant, i.e. finite or NaN.
732 /// For vectors, this includes constants with undefined elements.
733 inline cstfp_pred_ty<is_noninf> m_NonInf() {
734   return cstfp_pred_ty<is_noninf>();
735 }
736 
737 struct is_finite {
738   bool isValue(const APFloat &C) { return C.isFinite(); }
739 };
740 /// Match a finite FP constant, i.e. not infinity or NaN.
741 /// For vectors, this includes constants with undefined elements.
742 inline cstfp_pred_ty<is_finite> m_Finite() {
743   return cstfp_pred_ty<is_finite>();
744 }
745 inline apf_pred_ty<is_finite> m_Finite(const APFloat *&V) { return V; }
746 
747 struct is_finitenonzero {
748   bool isValue(const APFloat &C) { return C.isFiniteNonZero(); }
749 };
750 /// Match a finite non-zero FP constant.
751 /// For vectors, this includes constants with undefined elements.
752 inline cstfp_pred_ty<is_finitenonzero> m_FiniteNonZero() {
753   return cstfp_pred_ty<is_finitenonzero>();
754 }
755 inline apf_pred_ty<is_finitenonzero> m_FiniteNonZero(const APFloat *&V) {
756   return V;
757 }
758 
759 struct is_any_zero_fp {
760   bool isValue(const APFloat &C) { return C.isZero(); }
761 };
762 /// Match a floating-point negative zero or positive zero.
763 /// For vectors, this includes constants with undefined elements.
764 inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
765   return cstfp_pred_ty<is_any_zero_fp>();
766 }
767 
768 struct is_pos_zero_fp {
769   bool isValue(const APFloat &C) { return C.isPosZero(); }
770 };
771 /// Match a floating-point positive zero.
772 /// For vectors, this includes constants with undefined elements.
773 inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
774   return cstfp_pred_ty<is_pos_zero_fp>();
775 }
776 
777 struct is_neg_zero_fp {
778   bool isValue(const APFloat &C) { return C.isNegZero(); }
779 };
780 /// Match a floating-point negative zero.
781 /// For vectors, this includes constants with undefined elements.
782 inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
783   return cstfp_pred_ty<is_neg_zero_fp>();
784 }
785 
786 struct is_non_zero_fp {
787   bool isValue(const APFloat &C) { return C.isNonZero(); }
788 };
789 /// Match a floating-point non-zero.
790 /// For vectors, this includes constants with undefined elements.
791 inline cstfp_pred_ty<is_non_zero_fp> m_NonZeroFP() {
792   return cstfp_pred_ty<is_non_zero_fp>();
793 }
794 
795 ///////////////////////////////////////////////////////////////////////////////
796 
797 template <typename Class> struct bind_ty {
798   Class *&VR;
799 
800   bind_ty(Class *&V) : VR(V) {}
801 
802   template <typename ITy> bool match(ITy *V) {
803     if (auto *CV = dyn_cast<Class>(V)) {
804       VR = CV;
805       return true;
806     }
807     return false;
808   }
809 };
810 
811 /// Match a value, capturing it if we match.
812 inline bind_ty<Value> m_Value(Value *&V) { return V; }
813 inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
814 
815 /// Match an instruction, capturing it if we match.
816 inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
817 /// Match a unary operator, capturing it if we match.
818 inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; }
819 /// Match a binary operator, capturing it if we match.
820 inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
821 /// Match a with overflow intrinsic, capturing it if we match.
822 inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) {
823   return I;
824 }
825 inline bind_ty<const WithOverflowInst>
826 m_WithOverflowInst(const WithOverflowInst *&I) {
827   return I;
828 }
829 
830 /// Match an UndefValue, capturing the value if we match.
831 inline bind_ty<UndefValue> m_UndefValue(UndefValue *&U) { return U; }
832 
833 /// Match a Constant, capturing the value if we match.
834 inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
835 
836 /// Match a ConstantInt, capturing the value if we match.
837 inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
838 
839 /// Match a ConstantFP, capturing the value if we match.
840 inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
841 
842 /// Match a ConstantExpr, capturing the value if we match.
843 inline bind_ty<ConstantExpr> m_ConstantExpr(ConstantExpr *&C) { return C; }
844 
845 /// Match a basic block value, capturing it if we match.
846 inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
847 inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
848   return V;
849 }
850 
851 /// Match an arbitrary immediate Constant and ignore it.
852 inline match_combine_and<class_match<Constant>,
853                          match_unless<constantexpr_match>>
854 m_ImmConstant() {
855   return m_CombineAnd(m_Constant(), m_Unless(m_ConstantExpr()));
856 }
857 
858 /// Match an immediate Constant, capturing the value if we match.
859 inline match_combine_and<bind_ty<Constant>,
860                          match_unless<constantexpr_match>>
861 m_ImmConstant(Constant *&C) {
862   return m_CombineAnd(m_Constant(C), m_Unless(m_ConstantExpr()));
863 }
864 
865 /// Match a specified Value*.
866 struct specificval_ty {
867   const Value *Val;
868 
869   specificval_ty(const Value *V) : Val(V) {}
870 
871   template <typename ITy> bool match(ITy *V) { return V == Val; }
872 };
873 
874 /// Match if we have a specific specified value.
875 inline specificval_ty m_Specific(const Value *V) { return V; }
876 
877 /// Stores a reference to the Value *, not the Value * itself,
878 /// thus can be used in commutative matchers.
879 template <typename Class> struct deferredval_ty {
880   Class *const &Val;
881 
882   deferredval_ty(Class *const &V) : Val(V) {}
883 
884   template <typename ITy> bool match(ITy *const V) { return V == Val; }
885 };
886 
887 /// Like m_Specific(), but works if the specific value to match is determined
888 /// as part of the same match() expression. For example:
889 /// m_Add(m_Value(X), m_Specific(X)) is incorrect, because m_Specific() will
890 /// bind X before the pattern match starts.
891 /// m_Add(m_Value(X), m_Deferred(X)) is correct, and will check against
892 /// whichever value m_Value(X) populated.
893 inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
894 inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
895   return V;
896 }
897 
898 /// Match a specified floating point value or vector of all elements of
899 /// that value.
900 struct specific_fpval {
901   double Val;
902 
903   specific_fpval(double V) : Val(V) {}
904 
905   template <typename ITy> bool match(ITy *V) {
906     if (const auto *CFP = dyn_cast<ConstantFP>(V))
907       return CFP->isExactlyValue(Val);
908     if (V->getType()->isVectorTy())
909       if (const auto *C = dyn_cast<Constant>(V))
910         if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
911           return CFP->isExactlyValue(Val);
912     return false;
913   }
914 };
915 
916 /// Match a specific floating point value or vector with all elements
917 /// equal to the value.
918 inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
919 
920 /// Match a float 1.0 or vector with all elements equal to 1.0.
921 inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
922 
923 struct bind_const_intval_ty {
924   uint64_t &VR;
925 
926   bind_const_intval_ty(uint64_t &V) : VR(V) {}
927 
928   template <typename ITy> bool match(ITy *V) {
929     if (const auto *CV = dyn_cast<ConstantInt>(V))
930       if (CV->getValue().ule(UINT64_MAX)) {
931         VR = CV->getZExtValue();
932         return true;
933       }
934     return false;
935   }
936 };
937 
938 /// Match a specified integer value or vector of all elements of that
939 /// value.
940 template <bool AllowPoison> struct specific_intval {
941   const APInt &Val;
942 
943   specific_intval(const APInt &V) : Val(V) {}
944 
945   template <typename ITy> bool match(ITy *V) {
946     const auto *CI = dyn_cast<ConstantInt>(V);
947     if (!CI && V->getType()->isVectorTy())
948       if (const auto *C = dyn_cast<Constant>(V))
949         CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowPoison));
950 
951     return CI && APInt::isSameValue(CI->getValue(), Val);
952   }
953 };
954 
955 template <bool AllowPoison> struct specific_intval64 {
956   uint64_t Val;
957 
958   specific_intval64(uint64_t V) : Val(V) {}
959 
960   template <typename ITy> bool match(ITy *V) {
961     const auto *CI = dyn_cast<ConstantInt>(V);
962     if (!CI && V->getType()->isVectorTy())
963       if (const auto *C = dyn_cast<Constant>(V))
964         CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowPoison));
965 
966     return CI && CI->getValue() == Val;
967   }
968 };
969 
970 /// Match a specific integer value or vector with all elements equal to
971 /// the value.
972 inline specific_intval<false> m_SpecificInt(const APInt &V) {
973   return specific_intval<false>(V);
974 }
975 
976 inline specific_intval64<false> m_SpecificInt(uint64_t V) {
977   return specific_intval64<false>(V);
978 }
979 
980 inline specific_intval<true> m_SpecificIntAllowPoison(const APInt &V) {
981   return specific_intval<true>(V);
982 }
983 
984 inline specific_intval64<true> m_SpecificIntAllowPoison(uint64_t V) {
985   return specific_intval64<true>(V);
986 }
987 
988 /// Match a ConstantInt and bind to its value.  This does not match
989 /// ConstantInts wider than 64-bits.
990 inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
991 
992 /// Match a specified basic block value.
993 struct specific_bbval {
994   BasicBlock *Val;
995 
996   specific_bbval(BasicBlock *Val) : Val(Val) {}
997 
998   template <typename ITy> bool match(ITy *V) {
999     const auto *BB = dyn_cast<BasicBlock>(V);
1000     return BB && BB == Val;
1001   }
1002 };
1003 
1004 /// Match a specific basic block value.
1005 inline specific_bbval m_SpecificBB(BasicBlock *BB) {
1006   return specific_bbval(BB);
1007 }
1008 
1009 /// A commutative-friendly version of m_Specific().
1010 inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
1011   return BB;
1012 }
1013 inline deferredval_ty<const BasicBlock>
1014 m_Deferred(const BasicBlock *const &BB) {
1015   return BB;
1016 }
1017 
1018 //===----------------------------------------------------------------------===//
1019 // Matcher for any binary operator.
1020 //
1021 template <typename LHS_t, typename RHS_t, bool Commutable = false>
1022 struct AnyBinaryOp_match {
1023   LHS_t L;
1024   RHS_t R;
1025 
1026   // The evaluation order is always stable, regardless of Commutability.
1027   // The LHS is always matched first.
1028   AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1029 
1030   template <typename OpTy> bool match(OpTy *V) {
1031     if (auto *I = dyn_cast<BinaryOperator>(V))
1032       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
1033              (Commutable && L.match(I->getOperand(1)) &&
1034               R.match(I->getOperand(0)));
1035     return false;
1036   }
1037 };
1038 
1039 template <typename LHS, typename RHS>
1040 inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
1041   return AnyBinaryOp_match<LHS, RHS>(L, R);
1042 }
1043 
1044 //===----------------------------------------------------------------------===//
1045 // Matcher for any unary operator.
1046 // TODO fuse unary, binary matcher into n-ary matcher
1047 //
1048 template <typename OP_t> struct AnyUnaryOp_match {
1049   OP_t X;
1050 
1051   AnyUnaryOp_match(const OP_t &X) : X(X) {}
1052 
1053   template <typename OpTy> bool match(OpTy *V) {
1054     if (auto *I = dyn_cast<UnaryOperator>(V))
1055       return X.match(I->getOperand(0));
1056     return false;
1057   }
1058 };
1059 
1060 template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) {
1061   return AnyUnaryOp_match<OP_t>(X);
1062 }
1063 
1064 //===----------------------------------------------------------------------===//
1065 // Matchers for specific binary operators.
1066 //
1067 
1068 template <typename LHS_t, typename RHS_t, unsigned Opcode,
1069           bool Commutable = false>
1070 struct BinaryOp_match {
1071   LHS_t L;
1072   RHS_t R;
1073 
1074   // The evaluation order is always stable, regardless of Commutability.
1075   // The LHS is always matched first.
1076   BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1077 
1078   template <typename OpTy> inline bool match(unsigned Opc, OpTy *V) {
1079     if (V->getValueID() == Value::InstructionVal + Opc) {
1080       auto *I = cast<BinaryOperator>(V);
1081       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
1082              (Commutable && L.match(I->getOperand(1)) &&
1083               R.match(I->getOperand(0)));
1084     }
1085     return false;
1086   }
1087 
1088   template <typename OpTy> bool match(OpTy *V) { return match(Opcode, V); }
1089 };
1090 
1091 template <typename LHS, typename RHS>
1092 inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
1093                                                         const RHS &R) {
1094   return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
1095 }
1096 
1097 template <typename LHS, typename RHS>
1098 inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
1099                                                           const RHS &R) {
1100   return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
1101 }
1102 
1103 template <typename LHS, typename RHS>
1104 inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
1105                                                         const RHS &R) {
1106   return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
1107 }
1108 
1109 template <typename LHS, typename RHS>
1110 inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
1111                                                           const RHS &R) {
1112   return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
1113 }
1114 
1115 template <typename Op_t> struct FNeg_match {
1116   Op_t X;
1117 
1118   FNeg_match(const Op_t &Op) : X(Op) {}
1119   template <typename OpTy> bool match(OpTy *V) {
1120     auto *FPMO = dyn_cast<FPMathOperator>(V);
1121     if (!FPMO)
1122       return false;
1123 
1124     if (FPMO->getOpcode() == Instruction::FNeg)
1125       return X.match(FPMO->getOperand(0));
1126 
1127     if (FPMO->getOpcode() == Instruction::FSub) {
1128       if (FPMO->hasNoSignedZeros()) {
1129         // With 'nsz', any zero goes.
1130         if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
1131           return false;
1132       } else {
1133         // Without 'nsz', we need fsub -0.0, X exactly.
1134         if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
1135           return false;
1136       }
1137 
1138       return X.match(FPMO->getOperand(1));
1139     }
1140 
1141     return false;
1142   }
1143 };
1144 
1145 /// Match 'fneg X' as 'fsub -0.0, X'.
1146 template <typename OpTy> inline FNeg_match<OpTy> m_FNeg(const OpTy &X) {
1147   return FNeg_match<OpTy>(X);
1148 }
1149 
1150 /// Match 'fneg X' as 'fsub +-0.0, X'.
1151 template <typename RHS>
1152 inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
1153 m_FNegNSZ(const RHS &X) {
1154   return m_FSub(m_AnyZeroFP(), X);
1155 }
1156 
1157 template <typename LHS, typename RHS>
1158 inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
1159                                                         const RHS &R) {
1160   return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
1161 }
1162 
1163 template <typename LHS, typename RHS>
1164 inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
1165                                                           const RHS &R) {
1166   return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
1167 }
1168 
1169 template <typename LHS, typename RHS>
1170 inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
1171                                                           const RHS &R) {
1172   return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
1173 }
1174 
1175 template <typename LHS, typename RHS>
1176 inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
1177                                                           const RHS &R) {
1178   return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
1179 }
1180 
1181 template <typename LHS, typename RHS>
1182 inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
1183                                                           const RHS &R) {
1184   return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
1185 }
1186 
1187 template <typename LHS, typename RHS>
1188 inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
1189                                                           const RHS &R) {
1190   return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
1191 }
1192 
1193 template <typename LHS, typename RHS>
1194 inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
1195                                                           const RHS &R) {
1196   return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
1197 }
1198 
1199 template <typename LHS, typename RHS>
1200 inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
1201                                                           const RHS &R) {
1202   return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
1203 }
1204 
1205 template <typename LHS, typename RHS>
1206 inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
1207                                                         const RHS &R) {
1208   return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
1209 }
1210 
1211 template <typename LHS, typename RHS>
1212 inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
1213                                                       const RHS &R) {
1214   return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
1215 }
1216 
1217 template <typename LHS, typename RHS>
1218 inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
1219                                                         const RHS &R) {
1220   return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
1221 }
1222 
1223 template <typename LHS, typename RHS>
1224 inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
1225                                                         const RHS &R) {
1226   return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
1227 }
1228 
1229 template <typename LHS, typename RHS>
1230 inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
1231                                                           const RHS &R) {
1232   return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
1233 }
1234 
1235 template <typename LHS, typename RHS>
1236 inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
1237                                                           const RHS &R) {
1238   return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
1239 }
1240 
1241 template <typename LHS_t, typename RHS_t, unsigned Opcode,
1242           unsigned WrapFlags = 0, bool Commutable = false>
1243 struct OverflowingBinaryOp_match {
1244   LHS_t L;
1245   RHS_t R;
1246 
1247   OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
1248       : L(LHS), R(RHS) {}
1249 
1250   template <typename OpTy> bool match(OpTy *V) {
1251     if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
1252       if (Op->getOpcode() != Opcode)
1253         return false;
1254       if ((WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap) &&
1255           !Op->hasNoUnsignedWrap())
1256         return false;
1257       if ((WrapFlags & OverflowingBinaryOperator::NoSignedWrap) &&
1258           !Op->hasNoSignedWrap())
1259         return false;
1260       return (L.match(Op->getOperand(0)) && R.match(Op->getOperand(1))) ||
1261              (Commutable && L.match(Op->getOperand(1)) &&
1262               R.match(Op->getOperand(0)));
1263     }
1264     return false;
1265   }
1266 };
1267 
1268 template <typename LHS, typename RHS>
1269 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1270                                  OverflowingBinaryOperator::NoSignedWrap>
1271 m_NSWAdd(const LHS &L, const RHS &R) {
1272   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1273                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1274                                                                             R);
1275 }
1276 template <typename LHS, typename RHS>
1277 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1278                                  OverflowingBinaryOperator::NoSignedWrap>
1279 m_NSWSub(const LHS &L, const RHS &R) {
1280   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1281                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1282                                                                             R);
1283 }
1284 template <typename LHS, typename RHS>
1285 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1286                                  OverflowingBinaryOperator::NoSignedWrap>
1287 m_NSWMul(const LHS &L, const RHS &R) {
1288   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1289                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1290                                                                             R);
1291 }
1292 template <typename LHS, typename RHS>
1293 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1294                                  OverflowingBinaryOperator::NoSignedWrap>
1295 m_NSWShl(const LHS &L, const RHS &R) {
1296   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1297                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1298                                                                             R);
1299 }
1300 
1301 template <typename LHS, typename RHS>
1302 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1303                                  OverflowingBinaryOperator::NoUnsignedWrap>
1304 m_NUWAdd(const LHS &L, const RHS &R) {
1305   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1306                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1307       L, R);
1308 }
1309 
1310 template <typename LHS, typename RHS>
1311 inline OverflowingBinaryOp_match<
1312     LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true>
1313 m_c_NUWAdd(const LHS &L, const RHS &R) {
1314   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1315                                    OverflowingBinaryOperator::NoUnsignedWrap,
1316                                    true>(L, R);
1317 }
1318 
1319 template <typename LHS, typename RHS>
1320 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1321                                  OverflowingBinaryOperator::NoUnsignedWrap>
1322 m_NUWSub(const LHS &L, const RHS &R) {
1323   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1324                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1325       L, R);
1326 }
1327 template <typename LHS, typename RHS>
1328 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1329                                  OverflowingBinaryOperator::NoUnsignedWrap>
1330 m_NUWMul(const LHS &L, const RHS &R) {
1331   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1332                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1333       L, R);
1334 }
1335 template <typename LHS, typename RHS>
1336 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1337                                  OverflowingBinaryOperator::NoUnsignedWrap>
1338 m_NUWShl(const LHS &L, const RHS &R) {
1339   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1340                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1341       L, R);
1342 }
1343 
1344 template <typename LHS_t, typename RHS_t, bool Commutable = false>
1345 struct SpecificBinaryOp_match
1346     : public BinaryOp_match<LHS_t, RHS_t, 0, Commutable> {
1347   unsigned Opcode;
1348 
1349   SpecificBinaryOp_match(unsigned Opcode, const LHS_t &LHS, const RHS_t &RHS)
1350       : BinaryOp_match<LHS_t, RHS_t, 0, Commutable>(LHS, RHS), Opcode(Opcode) {}
1351 
1352   template <typename OpTy> bool match(OpTy *V) {
1353     return BinaryOp_match<LHS_t, RHS_t, 0, Commutable>::match(Opcode, V);
1354   }
1355 };
1356 
1357 /// Matches a specific opcode.
1358 template <typename LHS, typename RHS>
1359 inline SpecificBinaryOp_match<LHS, RHS> m_BinOp(unsigned Opcode, const LHS &L,
1360                                                 const RHS &R) {
1361   return SpecificBinaryOp_match<LHS, RHS>(Opcode, L, R);
1362 }
1363 
1364 template <typename LHS, typename RHS, bool Commutable = false>
1365 struct DisjointOr_match {
1366   LHS L;
1367   RHS R;
1368 
1369   DisjointOr_match(const LHS &L, const RHS &R) : L(L), R(R) {}
1370 
1371   template <typename OpTy> bool match(OpTy *V) {
1372     if (auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1373       assert(PDI->getOpcode() == Instruction::Or && "Only or can be disjoint");
1374       if (!PDI->isDisjoint())
1375         return false;
1376       return (L.match(PDI->getOperand(0)) && R.match(PDI->getOperand(1))) ||
1377              (Commutable && L.match(PDI->getOperand(1)) &&
1378               R.match(PDI->getOperand(0)));
1379     }
1380     return false;
1381   }
1382 };
1383 
1384 template <typename LHS, typename RHS>
1385 inline DisjointOr_match<LHS, RHS> m_DisjointOr(const LHS &L, const RHS &R) {
1386   return DisjointOr_match<LHS, RHS>(L, R);
1387 }
1388 
1389 template <typename LHS, typename RHS>
1390 inline DisjointOr_match<LHS, RHS, true> m_c_DisjointOr(const LHS &L,
1391                                                        const RHS &R) {
1392   return DisjointOr_match<LHS, RHS, true>(L, R);
1393 }
1394 
1395 /// Match either "add" or "or disjoint".
1396 template <typename LHS, typename RHS>
1397 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Add>,
1398                         DisjointOr_match<LHS, RHS>>
1399 m_AddLike(const LHS &L, const RHS &R) {
1400   return m_CombineOr(m_Add(L, R), m_DisjointOr(L, R));
1401 }
1402 
1403 /// Match either "add nsw" or "or disjoint"
1404 template <typename LHS, typename RHS>
1405 inline match_combine_or<
1406     OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1407                               OverflowingBinaryOperator::NoSignedWrap>,
1408     DisjointOr_match<LHS, RHS>>
1409 m_NSWAddLike(const LHS &L, const RHS &R) {
1410   return m_CombineOr(m_NSWAdd(L, R), m_DisjointOr(L, R));
1411 }
1412 
1413 /// Match either "add nuw" or "or disjoint"
1414 template <typename LHS, typename RHS>
1415 inline match_combine_or<
1416     OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1417                               OverflowingBinaryOperator::NoUnsignedWrap>,
1418     DisjointOr_match<LHS, RHS>>
1419 m_NUWAddLike(const LHS &L, const RHS &R) {
1420   return m_CombineOr(m_NUWAdd(L, R), m_DisjointOr(L, R));
1421 }
1422 
1423 //===----------------------------------------------------------------------===//
1424 // Class that matches a group of binary opcodes.
1425 //
1426 template <typename LHS_t, typename RHS_t, typename Predicate,
1427           bool Commutable = false>
1428 struct BinOpPred_match : Predicate {
1429   LHS_t L;
1430   RHS_t R;
1431 
1432   BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1433 
1434   template <typename OpTy> bool match(OpTy *V) {
1435     if (auto *I = dyn_cast<Instruction>(V))
1436       return this->isOpType(I->getOpcode()) &&
1437              ((L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
1438               (Commutable && L.match(I->getOperand(1)) &&
1439                R.match(I->getOperand(0))));
1440     return false;
1441   }
1442 };
1443 
1444 struct is_shift_op {
1445   bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1446 };
1447 
1448 struct is_right_shift_op {
1449   bool isOpType(unsigned Opcode) {
1450     return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1451   }
1452 };
1453 
1454 struct is_logical_shift_op {
1455   bool isOpType(unsigned Opcode) {
1456     return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1457   }
1458 };
1459 
1460 struct is_bitwiselogic_op {
1461   bool isOpType(unsigned Opcode) {
1462     return Instruction::isBitwiseLogicOp(Opcode);
1463   }
1464 };
1465 
1466 struct is_idiv_op {
1467   bool isOpType(unsigned Opcode) {
1468     return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1469   }
1470 };
1471 
1472 struct is_irem_op {
1473   bool isOpType(unsigned Opcode) {
1474     return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1475   }
1476 };
1477 
1478 /// Matches shift operations.
1479 template <typename LHS, typename RHS>
1480 inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1481                                                       const RHS &R) {
1482   return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1483 }
1484 
1485 /// Matches logical shift operations.
1486 template <typename LHS, typename RHS>
1487 inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1488                                                           const RHS &R) {
1489   return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1490 }
1491 
1492 /// Matches logical shift operations.
1493 template <typename LHS, typename RHS>
1494 inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
1495 m_LogicalShift(const LHS &L, const RHS &R) {
1496   return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1497 }
1498 
1499 /// Matches bitwise logic operations.
1500 template <typename LHS, typename RHS>
1501 inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
1502 m_BitwiseLogic(const LHS &L, const RHS &R) {
1503   return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1504 }
1505 
1506 /// Matches bitwise logic operations in either order.
1507 template <typename LHS, typename RHS>
1508 inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op, true>
1509 m_c_BitwiseLogic(const LHS &L, const RHS &R) {
1510   return BinOpPred_match<LHS, RHS, is_bitwiselogic_op, true>(L, R);
1511 }
1512 
1513 /// Matches integer division operations.
1514 template <typename LHS, typename RHS>
1515 inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1516                                                     const RHS &R) {
1517   return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1518 }
1519 
1520 /// Matches integer remainder operations.
1521 template <typename LHS, typename RHS>
1522 inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1523                                                     const RHS &R) {
1524   return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1525 }
1526 
1527 //===----------------------------------------------------------------------===//
1528 // Class that matches exact binary ops.
1529 //
1530 template <typename SubPattern_t> struct Exact_match {
1531   SubPattern_t SubPattern;
1532 
1533   Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1534 
1535   template <typename OpTy> bool match(OpTy *V) {
1536     if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1537       return PEO->isExact() && SubPattern.match(V);
1538     return false;
1539   }
1540 };
1541 
1542 template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1543   return SubPattern;
1544 }
1545 
1546 //===----------------------------------------------------------------------===//
1547 // Matchers for CmpInst classes
1548 //
1549 
1550 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1551           bool Commutable = false>
1552 struct CmpClass_match {
1553   PredicateTy *Predicate;
1554   LHS_t L;
1555   RHS_t R;
1556 
1557   // The evaluation order is always stable, regardless of Commutability.
1558   // The LHS is always matched first.
1559   CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1560       : Predicate(&Pred), L(LHS), R(RHS) {}
1561   CmpClass_match(const LHS_t &LHS, const RHS_t &RHS)
1562       : Predicate(nullptr), L(LHS), R(RHS) {}
1563 
1564   template <typename OpTy> bool match(OpTy *V) {
1565     if (auto *I = dyn_cast<Class>(V)) {
1566       if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
1567         if (Predicate)
1568           *Predicate = I->getPredicate();
1569         return true;
1570       } else if (Commutable && L.match(I->getOperand(1)) &&
1571                  R.match(I->getOperand(0))) {
1572         if (Predicate)
1573           *Predicate = I->getSwappedPredicate();
1574         return true;
1575       }
1576     }
1577     return false;
1578   }
1579 };
1580 
1581 template <typename LHS, typename RHS>
1582 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1583 m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1584   return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1585 }
1586 
1587 template <typename LHS, typename RHS>
1588 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1589 m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1590   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1591 }
1592 
1593 template <typename LHS, typename RHS>
1594 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1595 m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1596   return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1597 }
1598 
1599 template <typename LHS, typename RHS>
1600 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1601 m_Cmp(const LHS &L, const RHS &R) {
1602   return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(L, R);
1603 }
1604 
1605 template <typename LHS, typename RHS>
1606 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1607 m_ICmp(const LHS &L, const RHS &R) {
1608   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(L, R);
1609 }
1610 
1611 template <typename LHS, typename RHS>
1612 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1613 m_FCmp(const LHS &L, const RHS &R) {
1614   return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(L, R);
1615 }
1616 
1617 // Same as CmpClass, but instead of saving Pred as out output variable, match a
1618 // specific input pred for equality.
1619 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy>
1620 struct SpecificCmpClass_match {
1621   const PredicateTy Predicate;
1622   LHS_t L;
1623   RHS_t R;
1624 
1625   SpecificCmpClass_match(PredicateTy Pred, const LHS_t &LHS, const RHS_t &RHS)
1626       : Predicate(Pred), L(LHS), R(RHS) {}
1627 
1628   template <typename OpTy> bool match(OpTy *V) {
1629     if (auto *I = dyn_cast<Class>(V))
1630       return I->getPredicate() == Predicate && L.match(I->getOperand(0)) &&
1631              R.match(I->getOperand(1));
1632     return false;
1633   }
1634 };
1635 
1636 template <typename LHS, typename RHS>
1637 inline SpecificCmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1638 m_SpecificCmp(CmpInst::Predicate MatchPred, const LHS &L, const RHS &R) {
1639   return SpecificCmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(
1640       MatchPred, L, R);
1641 }
1642 
1643 template <typename LHS, typename RHS>
1644 inline SpecificCmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1645 m_SpecificICmp(ICmpInst::Predicate MatchPred, const LHS &L, const RHS &R) {
1646   return SpecificCmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(
1647       MatchPred, L, R);
1648 }
1649 
1650 template <typename LHS, typename RHS>
1651 inline SpecificCmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1652 m_SpecificFCmp(FCmpInst::Predicate MatchPred, const LHS &L, const RHS &R) {
1653   return SpecificCmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(
1654       MatchPred, L, R);
1655 }
1656 
1657 //===----------------------------------------------------------------------===//
1658 // Matchers for instructions with a given opcode and number of operands.
1659 //
1660 
1661 /// Matches instructions with Opcode and three operands.
1662 template <typename T0, unsigned Opcode> struct OneOps_match {
1663   T0 Op1;
1664 
1665   OneOps_match(const T0 &Op1) : Op1(Op1) {}
1666 
1667   template <typename OpTy> bool match(OpTy *V) {
1668     if (V->getValueID() == Value::InstructionVal + Opcode) {
1669       auto *I = cast<Instruction>(V);
1670       return Op1.match(I->getOperand(0));
1671     }
1672     return false;
1673   }
1674 };
1675 
1676 /// Matches instructions with Opcode and three operands.
1677 template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1678   T0 Op1;
1679   T1 Op2;
1680 
1681   TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1682 
1683   template <typename OpTy> bool match(OpTy *V) {
1684     if (V->getValueID() == Value::InstructionVal + Opcode) {
1685       auto *I = cast<Instruction>(V);
1686       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1687     }
1688     return false;
1689   }
1690 };
1691 
1692 /// Matches instructions with Opcode and three operands.
1693 template <typename T0, typename T1, typename T2, unsigned Opcode>
1694 struct ThreeOps_match {
1695   T0 Op1;
1696   T1 Op2;
1697   T2 Op3;
1698 
1699   ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1700       : Op1(Op1), Op2(Op2), Op3(Op3) {}
1701 
1702   template <typename OpTy> bool match(OpTy *V) {
1703     if (V->getValueID() == Value::InstructionVal + Opcode) {
1704       auto *I = cast<Instruction>(V);
1705       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1706              Op3.match(I->getOperand(2));
1707     }
1708     return false;
1709   }
1710 };
1711 
1712 /// Matches instructions with Opcode and any number of operands
1713 template <unsigned Opcode, typename... OperandTypes> struct AnyOps_match {
1714   std::tuple<OperandTypes...> Operands;
1715 
1716   AnyOps_match(const OperandTypes &...Ops) : Operands(Ops...) {}
1717 
1718   // Operand matching works by recursively calling match_operands, matching the
1719   // operands left to right. The first version is called for each operand but
1720   // the last, for which the second version is called. The second version of
1721   // match_operands is also used to match each individual operand.
1722   template <int Idx, int Last>
1723   std::enable_if_t<Idx != Last, bool> match_operands(const Instruction *I) {
1724     return match_operands<Idx, Idx>(I) && match_operands<Idx + 1, Last>(I);
1725   }
1726 
1727   template <int Idx, int Last>
1728   std::enable_if_t<Idx == Last, bool> match_operands(const Instruction *I) {
1729     return std::get<Idx>(Operands).match(I->getOperand(Idx));
1730   }
1731 
1732   template <typename OpTy> bool match(OpTy *V) {
1733     if (V->getValueID() == Value::InstructionVal + Opcode) {
1734       auto *I = cast<Instruction>(V);
1735       return I->getNumOperands() == sizeof...(OperandTypes) &&
1736              match_operands<0, sizeof...(OperandTypes) - 1>(I);
1737     }
1738     return false;
1739   }
1740 };
1741 
1742 /// Matches SelectInst.
1743 template <typename Cond, typename LHS, typename RHS>
1744 inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
1745 m_Select(const Cond &C, const LHS &L, const RHS &R) {
1746   return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1747 }
1748 
1749 /// This matches a select of two constants, e.g.:
1750 /// m_SelectCst<-1, 0>(m_Value(V))
1751 template <int64_t L, int64_t R, typename Cond>
1752 inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1753                       Instruction::Select>
1754 m_SelectCst(const Cond &C) {
1755   return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1756 }
1757 
1758 /// Matches FreezeInst.
1759 template <typename OpTy>
1760 inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) {
1761   return OneOps_match<OpTy, Instruction::Freeze>(Op);
1762 }
1763 
1764 /// Matches InsertElementInst.
1765 template <typename Val_t, typename Elt_t, typename Idx_t>
1766 inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>
1767 m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1768   return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1769       Val, Elt, Idx);
1770 }
1771 
1772 /// Matches ExtractElementInst.
1773 template <typename Val_t, typename Idx_t>
1774 inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
1775 m_ExtractElt(const Val_t &Val, const Idx_t &Idx) {
1776   return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1777 }
1778 
1779 /// Matches shuffle.
1780 template <typename T0, typename T1, typename T2> struct Shuffle_match {
1781   T0 Op1;
1782   T1 Op2;
1783   T2 Mask;
1784 
1785   Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask)
1786       : Op1(Op1), Op2(Op2), Mask(Mask) {}
1787 
1788   template <typename OpTy> bool match(OpTy *V) {
1789     if (auto *I = dyn_cast<ShuffleVectorInst>(V)) {
1790       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1791              Mask.match(I->getShuffleMask());
1792     }
1793     return false;
1794   }
1795 };
1796 
1797 struct m_Mask {
1798   ArrayRef<int> &MaskRef;
1799   m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1800   bool match(ArrayRef<int> Mask) {
1801     MaskRef = Mask;
1802     return true;
1803   }
1804 };
1805 
1806 struct m_ZeroMask {
1807   bool match(ArrayRef<int> Mask) {
1808     return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; });
1809   }
1810 };
1811 
1812 struct m_SpecificMask {
1813   ArrayRef<int> &MaskRef;
1814   m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1815   bool match(ArrayRef<int> Mask) { return MaskRef == Mask; }
1816 };
1817 
1818 struct m_SplatOrPoisonMask {
1819   int &SplatIndex;
1820   m_SplatOrPoisonMask(int &SplatIndex) : SplatIndex(SplatIndex) {}
1821   bool match(ArrayRef<int> Mask) {
1822     const auto *First = find_if(Mask, [](int Elem) { return Elem != -1; });
1823     if (First == Mask.end())
1824       return false;
1825     SplatIndex = *First;
1826     return all_of(Mask,
1827                   [First](int Elem) { return Elem == *First || Elem == -1; });
1828   }
1829 };
1830 
1831 template <typename PointerOpTy, typename OffsetOpTy> struct PtrAdd_match {
1832   PointerOpTy PointerOp;
1833   OffsetOpTy OffsetOp;
1834 
1835   PtrAdd_match(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
1836       : PointerOp(PointerOp), OffsetOp(OffsetOp) {}
1837 
1838   template <typename OpTy> bool match(OpTy *V) {
1839     auto *GEP = dyn_cast<GEPOperator>(V);
1840     return GEP && GEP->getSourceElementType()->isIntegerTy(8) &&
1841            PointerOp.match(GEP->getPointerOperand()) &&
1842            OffsetOp.match(GEP->idx_begin()->get());
1843   }
1844 };
1845 
1846 /// Matches ShuffleVectorInst independently of mask value.
1847 template <typename V1_t, typename V2_t>
1848 inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>
1849 m_Shuffle(const V1_t &v1, const V2_t &v2) {
1850   return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2);
1851 }
1852 
1853 template <typename V1_t, typename V2_t, typename Mask_t>
1854 inline Shuffle_match<V1_t, V2_t, Mask_t>
1855 m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) {
1856   return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask);
1857 }
1858 
1859 /// Matches LoadInst.
1860 template <typename OpTy>
1861 inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1862   return OneOps_match<OpTy, Instruction::Load>(Op);
1863 }
1864 
1865 /// Matches StoreInst.
1866 template <typename ValueOpTy, typename PointerOpTy>
1867 inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
1868 m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1869   return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1870                                                                   PointerOp);
1871 }
1872 
1873 /// Matches GetElementPtrInst.
1874 template <typename... OperandTypes>
1875 inline auto m_GEP(const OperandTypes &...Ops) {
1876   return AnyOps_match<Instruction::GetElementPtr, OperandTypes...>(Ops...);
1877 }
1878 
1879 /// Matches GEP with i8 source element type
1880 template <typename PointerOpTy, typename OffsetOpTy>
1881 inline PtrAdd_match<PointerOpTy, OffsetOpTy>
1882 m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp) {
1883   return PtrAdd_match<PointerOpTy, OffsetOpTy>(PointerOp, OffsetOp);
1884 }
1885 
1886 //===----------------------------------------------------------------------===//
1887 // Matchers for CastInst classes
1888 //
1889 
1890 template <typename Op_t, unsigned Opcode> struct CastOperator_match {
1891   Op_t Op;
1892 
1893   CastOperator_match(const Op_t &OpMatch) : Op(OpMatch) {}
1894 
1895   template <typename OpTy> bool match(OpTy *V) {
1896     if (auto *O = dyn_cast<Operator>(V))
1897       return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1898     return false;
1899   }
1900 };
1901 
1902 template <typename Op_t, typename Class> struct CastInst_match {
1903   Op_t Op;
1904 
1905   CastInst_match(const Op_t &OpMatch) : Op(OpMatch) {}
1906 
1907   template <typename OpTy> bool match(OpTy *V) {
1908     if (auto *I = dyn_cast<Class>(V))
1909       return Op.match(I->getOperand(0));
1910     return false;
1911   }
1912 };
1913 
1914 template <typename Op_t> struct PtrToIntSameSize_match {
1915   const DataLayout &DL;
1916   Op_t Op;
1917 
1918   PtrToIntSameSize_match(const DataLayout &DL, const Op_t &OpMatch)
1919       : DL(DL), Op(OpMatch) {}
1920 
1921   template <typename OpTy> bool match(OpTy *V) {
1922     if (auto *O = dyn_cast<Operator>(V))
1923       return O->getOpcode() == Instruction::PtrToInt &&
1924              DL.getTypeSizeInBits(O->getType()) ==
1925                  DL.getTypeSizeInBits(O->getOperand(0)->getType()) &&
1926              Op.match(O->getOperand(0));
1927     return false;
1928   }
1929 };
1930 
1931 template <typename Op_t> struct NNegZExt_match {
1932   Op_t Op;
1933 
1934   NNegZExt_match(const Op_t &OpMatch) : Op(OpMatch) {}
1935 
1936   template <typename OpTy> bool match(OpTy *V) {
1937     if (auto *I = dyn_cast<ZExtInst>(V))
1938       return I->hasNonNeg() && Op.match(I->getOperand(0));
1939     return false;
1940   }
1941 };
1942 
1943 template <typename Op_t, unsigned WrapFlags = 0> struct NoWrapTrunc_match {
1944   Op_t Op;
1945 
1946   NoWrapTrunc_match(const Op_t &OpMatch) : Op(OpMatch) {}
1947 
1948   template <typename OpTy> bool match(OpTy *V) {
1949     if (auto *I = dyn_cast<TruncInst>(V))
1950       return (I->getNoWrapKind() & WrapFlags) == WrapFlags &&
1951              Op.match(I->getOperand(0));
1952     return false;
1953   }
1954 };
1955 
1956 /// Matches BitCast.
1957 template <typename OpTy>
1958 inline CastOperator_match<OpTy, Instruction::BitCast>
1959 m_BitCast(const OpTy &Op) {
1960   return CastOperator_match<OpTy, Instruction::BitCast>(Op);
1961 }
1962 
1963 template <typename Op_t> struct ElementWiseBitCast_match {
1964   Op_t Op;
1965 
1966   ElementWiseBitCast_match(const Op_t &OpMatch) : Op(OpMatch) {}
1967 
1968   template <typename OpTy> bool match(OpTy *V) {
1969     auto *I = dyn_cast<BitCastInst>(V);
1970     if (!I)
1971       return false;
1972     Type *SrcType = I->getSrcTy();
1973     Type *DstType = I->getType();
1974     // Make sure the bitcast doesn't change between scalar and vector and
1975     // doesn't change the number of vector elements.
1976     if (SrcType->isVectorTy() != DstType->isVectorTy())
1977       return false;
1978     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcType);
1979         SrcVecTy && SrcVecTy->getElementCount() !=
1980                         cast<VectorType>(DstType)->getElementCount())
1981       return false;
1982     return Op.match(I->getOperand(0));
1983   }
1984 };
1985 
1986 template <typename OpTy>
1987 inline ElementWiseBitCast_match<OpTy> m_ElementWiseBitCast(const OpTy &Op) {
1988   return ElementWiseBitCast_match<OpTy>(Op);
1989 }
1990 
1991 /// Matches PtrToInt.
1992 template <typename OpTy>
1993 inline CastOperator_match<OpTy, Instruction::PtrToInt>
1994 m_PtrToInt(const OpTy &Op) {
1995   return CastOperator_match<OpTy, Instruction::PtrToInt>(Op);
1996 }
1997 
1998 template <typename OpTy>
1999 inline PtrToIntSameSize_match<OpTy> m_PtrToIntSameSize(const DataLayout &DL,
2000                                                        const OpTy &Op) {
2001   return PtrToIntSameSize_match<OpTy>(DL, Op);
2002 }
2003 
2004 /// Matches IntToPtr.
2005 template <typename OpTy>
2006 inline CastOperator_match<OpTy, Instruction::IntToPtr>
2007 m_IntToPtr(const OpTy &Op) {
2008   return CastOperator_match<OpTy, Instruction::IntToPtr>(Op);
2009 }
2010 
2011 /// Matches Trunc.
2012 template <typename OpTy>
2013 inline CastInst_match<OpTy, TruncInst> m_Trunc(const OpTy &Op) {
2014   return CastInst_match<OpTy, TruncInst>(Op);
2015 }
2016 
2017 /// Matches trunc nuw.
2018 template <typename OpTy>
2019 inline NoWrapTrunc_match<OpTy, TruncInst::NoUnsignedWrap>
2020 m_NUWTrunc(const OpTy &Op) {
2021   return NoWrapTrunc_match<OpTy, TruncInst::NoUnsignedWrap>(Op);
2022 }
2023 
2024 /// Matches trunc nsw.
2025 template <typename OpTy>
2026 inline NoWrapTrunc_match<OpTy, TruncInst::NoSignedWrap>
2027 m_NSWTrunc(const OpTy &Op) {
2028   return NoWrapTrunc_match<OpTy, TruncInst::NoSignedWrap>(Op);
2029 }
2030 
2031 template <typename OpTy>
2032 inline match_combine_or<CastInst_match<OpTy, TruncInst>, OpTy>
2033 m_TruncOrSelf(const OpTy &Op) {
2034   return m_CombineOr(m_Trunc(Op), Op);
2035 }
2036 
2037 /// Matches SExt.
2038 template <typename OpTy>
2039 inline CastInst_match<OpTy, SExtInst> m_SExt(const OpTy &Op) {
2040   return CastInst_match<OpTy, SExtInst>(Op);
2041 }
2042 
2043 /// Matches ZExt.
2044 template <typename OpTy>
2045 inline CastInst_match<OpTy, ZExtInst> m_ZExt(const OpTy &Op) {
2046   return CastInst_match<OpTy, ZExtInst>(Op);
2047 }
2048 
2049 template <typename OpTy>
2050 inline NNegZExt_match<OpTy> m_NNegZExt(const OpTy &Op) {
2051   return NNegZExt_match<OpTy>(Op);
2052 }
2053 
2054 template <typename OpTy>
2055 inline match_combine_or<CastInst_match<OpTy, ZExtInst>, OpTy>
2056 m_ZExtOrSelf(const OpTy &Op) {
2057   return m_CombineOr(m_ZExt(Op), Op);
2058 }
2059 
2060 template <typename OpTy>
2061 inline match_combine_or<CastInst_match<OpTy, SExtInst>, OpTy>
2062 m_SExtOrSelf(const OpTy &Op) {
2063   return m_CombineOr(m_SExt(Op), Op);
2064 }
2065 
2066 /// Match either "sext" or "zext nneg".
2067 template <typename OpTy>
2068 inline match_combine_or<CastInst_match<OpTy, SExtInst>, NNegZExt_match<OpTy>>
2069 m_SExtLike(const OpTy &Op) {
2070   return m_CombineOr(m_SExt(Op), m_NNegZExt(Op));
2071 }
2072 
2073 template <typename OpTy>
2074 inline match_combine_or<CastInst_match<OpTy, ZExtInst>,
2075                         CastInst_match<OpTy, SExtInst>>
2076 m_ZExtOrSExt(const OpTy &Op) {
2077   return m_CombineOr(m_ZExt(Op), m_SExt(Op));
2078 }
2079 
2080 template <typename OpTy>
2081 inline match_combine_or<match_combine_or<CastInst_match<OpTy, ZExtInst>,
2082                                          CastInst_match<OpTy, SExtInst>>,
2083                         OpTy>
2084 m_ZExtOrSExtOrSelf(const OpTy &Op) {
2085   return m_CombineOr(m_ZExtOrSExt(Op), Op);
2086 }
2087 
2088 template <typename OpTy>
2089 inline CastInst_match<OpTy, UIToFPInst> m_UIToFP(const OpTy &Op) {
2090   return CastInst_match<OpTy, UIToFPInst>(Op);
2091 }
2092 
2093 template <typename OpTy>
2094 inline CastInst_match<OpTy, SIToFPInst> m_SIToFP(const OpTy &Op) {
2095   return CastInst_match<OpTy, SIToFPInst>(Op);
2096 }
2097 
2098 template <typename OpTy>
2099 inline CastInst_match<OpTy, FPToUIInst> m_FPToUI(const OpTy &Op) {
2100   return CastInst_match<OpTy, FPToUIInst>(Op);
2101 }
2102 
2103 template <typename OpTy>
2104 inline CastInst_match<OpTy, FPToSIInst> m_FPToSI(const OpTy &Op) {
2105   return CastInst_match<OpTy, FPToSIInst>(Op);
2106 }
2107 
2108 template <typename OpTy>
2109 inline CastInst_match<OpTy, FPTruncInst> m_FPTrunc(const OpTy &Op) {
2110   return CastInst_match<OpTy, FPTruncInst>(Op);
2111 }
2112 
2113 template <typename OpTy>
2114 inline CastInst_match<OpTy, FPExtInst> m_FPExt(const OpTy &Op) {
2115   return CastInst_match<OpTy, FPExtInst>(Op);
2116 }
2117 
2118 //===----------------------------------------------------------------------===//
2119 // Matchers for control flow.
2120 //
2121 
2122 struct br_match {
2123   BasicBlock *&Succ;
2124 
2125   br_match(BasicBlock *&Succ) : Succ(Succ) {}
2126 
2127   template <typename OpTy> bool match(OpTy *V) {
2128     if (auto *BI = dyn_cast<BranchInst>(V))
2129       if (BI->isUnconditional()) {
2130         Succ = BI->getSuccessor(0);
2131         return true;
2132       }
2133     return false;
2134   }
2135 };
2136 
2137 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
2138 
2139 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
2140 struct brc_match {
2141   Cond_t Cond;
2142   TrueBlock_t T;
2143   FalseBlock_t F;
2144 
2145   brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
2146       : Cond(C), T(t), F(f) {}
2147 
2148   template <typename OpTy> bool match(OpTy *V) {
2149     if (auto *BI = dyn_cast<BranchInst>(V))
2150       if (BI->isConditional() && Cond.match(BI->getCondition()))
2151         return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
2152     return false;
2153   }
2154 };
2155 
2156 template <typename Cond_t>
2157 inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
2158 m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
2159   return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
2160       C, m_BasicBlock(T), m_BasicBlock(F));
2161 }
2162 
2163 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
2164 inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
2165 m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
2166   return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
2167 }
2168 
2169 //===----------------------------------------------------------------------===//
2170 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
2171 //
2172 
2173 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
2174           bool Commutable = false>
2175 struct MaxMin_match {
2176   using PredType = Pred_t;
2177   LHS_t L;
2178   RHS_t R;
2179 
2180   // The evaluation order is always stable, regardless of Commutability.
2181   // The LHS is always matched first.
2182   MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
2183 
2184   template <typename OpTy> bool match(OpTy *V) {
2185     if (auto *II = dyn_cast<IntrinsicInst>(V)) {
2186       Intrinsic::ID IID = II->getIntrinsicID();
2187       if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) ||
2188           (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) ||
2189           (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) ||
2190           (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) {
2191         Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
2192         return (L.match(LHS) && R.match(RHS)) ||
2193                (Commutable && L.match(RHS) && R.match(LHS));
2194       }
2195     }
2196     // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
2197     auto *SI = dyn_cast<SelectInst>(V);
2198     if (!SI)
2199       return false;
2200     auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
2201     if (!Cmp)
2202       return false;
2203     // At this point we have a select conditioned on a comparison.  Check that
2204     // it is the values returned by the select that are being compared.
2205     auto *TrueVal = SI->getTrueValue();
2206     auto *FalseVal = SI->getFalseValue();
2207     auto *LHS = Cmp->getOperand(0);
2208     auto *RHS = Cmp->getOperand(1);
2209     if ((TrueVal != LHS || FalseVal != RHS) &&
2210         (TrueVal != RHS || FalseVal != LHS))
2211       return false;
2212     typename CmpInst_t::Predicate Pred =
2213         LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
2214     // Does "(x pred y) ? x : y" represent the desired max/min operation?
2215     if (!Pred_t::match(Pred))
2216       return false;
2217     // It does!  Bind the operands.
2218     return (L.match(LHS) && R.match(RHS)) ||
2219            (Commutable && L.match(RHS) && R.match(LHS));
2220   }
2221 };
2222 
2223 /// Helper class for identifying signed max predicates.
2224 struct smax_pred_ty {
2225   static bool match(ICmpInst::Predicate Pred) {
2226     return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
2227   }
2228 };
2229 
2230 /// Helper class for identifying signed min predicates.
2231 struct smin_pred_ty {
2232   static bool match(ICmpInst::Predicate Pred) {
2233     return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
2234   }
2235 };
2236 
2237 /// Helper class for identifying unsigned max predicates.
2238 struct umax_pred_ty {
2239   static bool match(ICmpInst::Predicate Pred) {
2240     return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
2241   }
2242 };
2243 
2244 /// Helper class for identifying unsigned min predicates.
2245 struct umin_pred_ty {
2246   static bool match(ICmpInst::Predicate Pred) {
2247     return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
2248   }
2249 };
2250 
2251 /// Helper class for identifying ordered max predicates.
2252 struct ofmax_pred_ty {
2253   static bool match(FCmpInst::Predicate Pred) {
2254     return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
2255   }
2256 };
2257 
2258 /// Helper class for identifying ordered min predicates.
2259 struct ofmin_pred_ty {
2260   static bool match(FCmpInst::Predicate Pred) {
2261     return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
2262   }
2263 };
2264 
2265 /// Helper class for identifying unordered max predicates.
2266 struct ufmax_pred_ty {
2267   static bool match(FCmpInst::Predicate Pred) {
2268     return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
2269   }
2270 };
2271 
2272 /// Helper class for identifying unordered min predicates.
2273 struct ufmin_pred_ty {
2274   static bool match(FCmpInst::Predicate Pred) {
2275     return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
2276   }
2277 };
2278 
2279 template <typename LHS, typename RHS>
2280 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
2281                                                              const RHS &R) {
2282   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
2283 }
2284 
2285 template <typename LHS, typename RHS>
2286 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
2287                                                              const RHS &R) {
2288   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
2289 }
2290 
2291 template <typename LHS, typename RHS>
2292 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
2293                                                              const RHS &R) {
2294   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
2295 }
2296 
2297 template <typename LHS, typename RHS>
2298 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
2299                                                              const RHS &R) {
2300   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
2301 }
2302 
2303 template <typename LHS, typename RHS>
2304 inline match_combine_or<
2305     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
2306                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>,
2307     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
2308                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>>
2309 m_MaxOrMin(const LHS &L, const RHS &R) {
2310   return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)),
2311                      m_CombineOr(m_UMax(L, R), m_UMin(L, R)));
2312 }
2313 
2314 /// Match an 'ordered' floating point maximum function.
2315 /// Floating point has one special value 'NaN'. Therefore, there is no total
2316 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2317 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
2318 /// semantics. In the presence of 'NaN' we have to preserve the original
2319 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
2320 ///
2321 ///                         max(L, R)  iff L and R are not NaN
2322 ///  m_OrdFMax(L, R) =      R          iff L or R are NaN
2323 template <typename LHS, typename RHS>
2324 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
2325                                                                  const RHS &R) {
2326   return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
2327 }
2328 
2329 /// Match an 'ordered' floating point minimum function.
2330 /// Floating point has one special value 'NaN'. Therefore, there is no total
2331 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2332 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
2333 /// semantics. In the presence of 'NaN' we have to preserve the original
2334 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
2335 ///
2336 ///                         min(L, R)  iff L and R are not NaN
2337 ///  m_OrdFMin(L, R) =      R          iff L or R are NaN
2338 template <typename LHS, typename RHS>
2339 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
2340                                                                  const RHS &R) {
2341   return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
2342 }
2343 
2344 /// Match an 'unordered' floating point maximum function.
2345 /// Floating point has one special value 'NaN'. Therefore, there is no total
2346 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2347 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
2348 /// semantics. In the presence of 'NaN' we have to preserve the original
2349 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
2350 ///
2351 ///                         max(L, R)  iff L and R are not NaN
2352 ///  m_UnordFMax(L, R) =    L          iff L or R are NaN
2353 template <typename LHS, typename RHS>
2354 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
2355 m_UnordFMax(const LHS &L, const RHS &R) {
2356   return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
2357 }
2358 
2359 /// Match an 'unordered' floating point minimum function.
2360 /// Floating point has one special value 'NaN'. Therefore, there is no total
2361 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2362 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
2363 /// semantics. In the presence of 'NaN' we have to preserve the original
2364 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
2365 ///
2366 ///                          min(L, R)  iff L and R are not NaN
2367 ///  m_UnordFMin(L, R) =     L          iff L or R are NaN
2368 template <typename LHS, typename RHS>
2369 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
2370 m_UnordFMin(const LHS &L, const RHS &R) {
2371   return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
2372 }
2373 
2374 /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
2375 /// NOTE: we first match the 'Not' (by matching '-1'),
2376 /// and only then match the inner matcher!
2377 template <typename ValTy>
2378 inline BinaryOp_match<cst_pred_ty<is_all_ones>, ValTy, Instruction::Xor, true>
2379 m_Not(const ValTy &V) {
2380   return m_c_Xor(m_AllOnes(), V);
2381 }
2382 
2383 template <typename ValTy>
2384 inline BinaryOp_match<cst_pred_ty<is_all_ones, false>, ValTy, Instruction::Xor,
2385                       true>
2386 m_NotForbidPoison(const ValTy &V) {
2387   return m_c_Xor(m_AllOnesForbidPoison(), V);
2388 }
2389 
2390 //===----------------------------------------------------------------------===//
2391 // Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b
2392 // Note that S might be matched to other instructions than AddInst.
2393 //
2394 
2395 template <typename LHS_t, typename RHS_t, typename Sum_t>
2396 struct UAddWithOverflow_match {
2397   LHS_t L;
2398   RHS_t R;
2399   Sum_t S;
2400 
2401   UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
2402       : L(L), R(R), S(S) {}
2403 
2404   template <typename OpTy> bool match(OpTy *V) {
2405     Value *ICmpLHS, *ICmpRHS;
2406     ICmpInst::Predicate Pred;
2407     if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
2408       return false;
2409 
2410     Value *AddLHS, *AddRHS;
2411     auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
2412 
2413     // (a + b) u< a, (a + b) u< b
2414     if (Pred == ICmpInst::ICMP_ULT)
2415       if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
2416         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2417 
2418     // a >u (a + b), b >u (a + b)
2419     if (Pred == ICmpInst::ICMP_UGT)
2420       if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
2421         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2422 
2423     Value *Op1;
2424     auto XorExpr = m_OneUse(m_Not(m_Value(Op1)));
2425     // (~a) <u b
2426     if (Pred == ICmpInst::ICMP_ULT) {
2427       if (XorExpr.match(ICmpLHS))
2428         return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS);
2429     }
2430     //  b > u (~a)
2431     if (Pred == ICmpInst::ICMP_UGT) {
2432       if (XorExpr.match(ICmpRHS))
2433         return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS);
2434     }
2435 
2436     // Match special-case for increment-by-1.
2437     if (Pred == ICmpInst::ICMP_EQ) {
2438       // (a + 1) == 0
2439       // (1 + a) == 0
2440       if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
2441           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2442         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2443       // 0 == (a + 1)
2444       // 0 == (1 + a)
2445       if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
2446           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2447         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2448     }
2449 
2450     return false;
2451   }
2452 };
2453 
2454 /// Match an icmp instruction checking for unsigned overflow on addition.
2455 ///
2456 /// S is matched to the addition whose result is being checked for overflow, and
2457 /// L and R are matched to the LHS and RHS of S.
2458 template <typename LHS_t, typename RHS_t, typename Sum_t>
2459 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
2460 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
2461   return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
2462 }
2463 
2464 template <typename Opnd_t> struct Argument_match {
2465   unsigned OpI;
2466   Opnd_t Val;
2467 
2468   Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
2469 
2470   template <typename OpTy> bool match(OpTy *V) {
2471     // FIXME: Should likely be switched to use `CallBase`.
2472     if (const auto *CI = dyn_cast<CallInst>(V))
2473       return Val.match(CI->getArgOperand(OpI));
2474     return false;
2475   }
2476 };
2477 
2478 /// Match an argument.
2479 template <unsigned OpI, typename Opnd_t>
2480 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
2481   return Argument_match<Opnd_t>(OpI, Op);
2482 }
2483 
2484 /// Intrinsic matchers.
2485 struct IntrinsicID_match {
2486   unsigned ID;
2487 
2488   IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
2489 
2490   template <typename OpTy> bool match(OpTy *V) {
2491     if (const auto *CI = dyn_cast<CallInst>(V))
2492       if (const auto *F = CI->getCalledFunction())
2493         return F->getIntrinsicID() == ID;
2494     return false;
2495   }
2496 };
2497 
2498 /// Intrinsic matches are combinations of ID matchers, and argument
2499 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
2500 /// them with lower arity matchers. Here's some convenient typedefs for up to
2501 /// several arguments, and more can be added as needed
2502 template <typename T0 = void, typename T1 = void, typename T2 = void,
2503           typename T3 = void, typename T4 = void, typename T5 = void,
2504           typename T6 = void, typename T7 = void, typename T8 = void,
2505           typename T9 = void, typename T10 = void>
2506 struct m_Intrinsic_Ty;
2507 template <typename T0> struct m_Intrinsic_Ty<T0> {
2508   using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
2509 };
2510 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
2511   using Ty =
2512       match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
2513 };
2514 template <typename T0, typename T1, typename T2>
2515 struct m_Intrinsic_Ty<T0, T1, T2> {
2516   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
2517                                Argument_match<T2>>;
2518 };
2519 template <typename T0, typename T1, typename T2, typename T3>
2520 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
2521   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
2522                                Argument_match<T3>>;
2523 };
2524 
2525 template <typename T0, typename T1, typename T2, typename T3, typename T4>
2526 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> {
2527   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty,
2528                                Argument_match<T4>>;
2529 };
2530 
2531 template <typename T0, typename T1, typename T2, typename T3, typename T4,
2532           typename T5>
2533 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> {
2534   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty,
2535                                Argument_match<T5>>;
2536 };
2537 
2538 /// Match intrinsic calls like this:
2539 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
2540 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
2541   return IntrinsicID_match(IntrID);
2542 }
2543 
2544 /// Matches MaskedLoad Intrinsic.
2545 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2546 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2547 m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2548              const Opnd3 &Op3) {
2549   return m_Intrinsic<Intrinsic::masked_load>(Op0, Op1, Op2, Op3);
2550 }
2551 
2552 /// Matches MaskedGather Intrinsic.
2553 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2554 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2555 m_MaskedGather(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2556                const Opnd3 &Op3) {
2557   return m_Intrinsic<Intrinsic::masked_gather>(Op0, Op1, Op2, Op3);
2558 }
2559 
2560 template <Intrinsic::ID IntrID, typename T0>
2561 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
2562   return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
2563 }
2564 
2565 template <Intrinsic::ID IntrID, typename T0, typename T1>
2566 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
2567                                                        const T1 &Op1) {
2568   return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
2569 }
2570 
2571 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
2572 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
2573 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
2574   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
2575 }
2576 
2577 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2578           typename T3>
2579 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
2580 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
2581   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
2582 }
2583 
2584 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2585           typename T3, typename T4>
2586 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty
2587 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2588             const T4 &Op4) {
2589   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3),
2590                       m_Argument<4>(Op4));
2591 }
2592 
2593 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2594           typename T3, typename T4, typename T5>
2595 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty
2596 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2597             const T4 &Op4, const T5 &Op5) {
2598   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4),
2599                       m_Argument<5>(Op5));
2600 }
2601 
2602 // Helper intrinsic matching specializations.
2603 template <typename Opnd0>
2604 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
2605   return m_Intrinsic<Intrinsic::bitreverse>(Op0);
2606 }
2607 
2608 template <typename Opnd0>
2609 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
2610   return m_Intrinsic<Intrinsic::bswap>(Op0);
2611 }
2612 
2613 template <typename Opnd0>
2614 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
2615   return m_Intrinsic<Intrinsic::fabs>(Op0);
2616 }
2617 
2618 template <typename Opnd0>
2619 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
2620   return m_Intrinsic<Intrinsic::canonicalize>(Op0);
2621 }
2622 
2623 template <typename Opnd0, typename Opnd1>
2624 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
2625                                                         const Opnd1 &Op1) {
2626   return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
2627 }
2628 
2629 template <typename Opnd0, typename Opnd1>
2630 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
2631                                                         const Opnd1 &Op1) {
2632   return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
2633 }
2634 
2635 template <typename Opnd0, typename Opnd1, typename Opnd2>
2636 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2637 m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2638   return m_Intrinsic<Intrinsic::fshl>(Op0, Op1, Op2);
2639 }
2640 
2641 template <typename Opnd0, typename Opnd1, typename Opnd2>
2642 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2643 m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2644   return m_Intrinsic<Intrinsic::fshr>(Op0, Op1, Op2);
2645 }
2646 
2647 template <typename Opnd0>
2648 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_Sqrt(const Opnd0 &Op0) {
2649   return m_Intrinsic<Intrinsic::sqrt>(Op0);
2650 }
2651 
2652 template <typename Opnd0, typename Opnd1>
2653 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_CopySign(const Opnd0 &Op0,
2654                                                             const Opnd1 &Op1) {
2655   return m_Intrinsic<Intrinsic::copysign>(Op0, Op1);
2656 }
2657 
2658 template <typename Opnd0>
2659 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_VecReverse(const Opnd0 &Op0) {
2660   return m_Intrinsic<Intrinsic::vector_reverse>(Op0);
2661 }
2662 
2663 //===----------------------------------------------------------------------===//
2664 // Matchers for two-operands operators with the operators in either order
2665 //
2666 
2667 /// Matches a BinaryOperator with LHS and RHS in either order.
2668 template <typename LHS, typename RHS>
2669 inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
2670   return AnyBinaryOp_match<LHS, RHS, true>(L, R);
2671 }
2672 
2673 /// Matches an ICmp with a predicate over LHS and RHS in either order.
2674 /// Swaps the predicate if operands are commuted.
2675 template <typename LHS, typename RHS>
2676 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2677 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
2678   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
2679                                                                        R);
2680 }
2681 
2682 template <typename LHS, typename RHS>
2683 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2684 m_c_ICmp(const LHS &L, const RHS &R) {
2685   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(L, R);
2686 }
2687 
2688 /// Matches a specific opcode with LHS and RHS in either order.
2689 template <typename LHS, typename RHS>
2690 inline SpecificBinaryOp_match<LHS, RHS, true>
2691 m_c_BinOp(unsigned Opcode, const LHS &L, const RHS &R) {
2692   return SpecificBinaryOp_match<LHS, RHS, true>(Opcode, L, R);
2693 }
2694 
2695 /// Matches a Add with LHS and RHS in either order.
2696 template <typename LHS, typename RHS>
2697 inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
2698                                                                 const RHS &R) {
2699   return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
2700 }
2701 
2702 /// Matches a Mul with LHS and RHS in either order.
2703 template <typename LHS, typename RHS>
2704 inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
2705                                                                 const RHS &R) {
2706   return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
2707 }
2708 
2709 /// Matches an And with LHS and RHS in either order.
2710 template <typename LHS, typename RHS>
2711 inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
2712                                                                 const RHS &R) {
2713   return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
2714 }
2715 
2716 /// Matches an Or with LHS and RHS in either order.
2717 template <typename LHS, typename RHS>
2718 inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
2719                                                               const RHS &R) {
2720   return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2721 }
2722 
2723 /// Matches an Xor with LHS and RHS in either order.
2724 template <typename LHS, typename RHS>
2725 inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
2726                                                                 const RHS &R) {
2727   return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
2728 }
2729 
2730 /// Matches a 'Neg' as 'sub 0, V'.
2731 template <typename ValTy>
2732 inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
2733 m_Neg(const ValTy &V) {
2734   return m_Sub(m_ZeroInt(), V);
2735 }
2736 
2737 /// Matches a 'Neg' as 'sub nsw 0, V'.
2738 template <typename ValTy>
2739 inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy,
2740                                  Instruction::Sub,
2741                                  OverflowingBinaryOperator::NoSignedWrap>
2742 m_NSWNeg(const ValTy &V) {
2743   return m_NSWSub(m_ZeroInt(), V);
2744 }
2745 
2746 /// Matches an SMin with LHS and RHS in either order.
2747 template <typename LHS, typename RHS>
2748 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
2749 m_c_SMin(const LHS &L, const RHS &R) {
2750   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
2751 }
2752 /// Matches an SMax with LHS and RHS in either order.
2753 template <typename LHS, typename RHS>
2754 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
2755 m_c_SMax(const LHS &L, const RHS &R) {
2756   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
2757 }
2758 /// Matches a UMin with LHS and RHS in either order.
2759 template <typename LHS, typename RHS>
2760 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
2761 m_c_UMin(const LHS &L, const RHS &R) {
2762   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
2763 }
2764 /// Matches a UMax with LHS and RHS in either order.
2765 template <typename LHS, typename RHS>
2766 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
2767 m_c_UMax(const LHS &L, const RHS &R) {
2768   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
2769 }
2770 
2771 template <typename LHS, typename RHS>
2772 inline match_combine_or<
2773     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>,
2774                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>,
2775     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>,
2776                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>>
2777 m_c_MaxOrMin(const LHS &L, const RHS &R) {
2778   return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)),
2779                      m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R)));
2780 }
2781 
2782 template <Intrinsic::ID IntrID, typename T0, typename T1>
2783 inline match_combine_or<typename m_Intrinsic_Ty<T0, T1>::Ty,
2784                         typename m_Intrinsic_Ty<T1, T0>::Ty>
2785 m_c_Intrinsic(const T0 &Op0, const T1 &Op1) {
2786   return m_CombineOr(m_Intrinsic<IntrID>(Op0, Op1),
2787                      m_Intrinsic<IntrID>(Op1, Op0));
2788 }
2789 
2790 /// Matches FAdd with LHS and RHS in either order.
2791 template <typename LHS, typename RHS>
2792 inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
2793 m_c_FAdd(const LHS &L, const RHS &R) {
2794   return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
2795 }
2796 
2797 /// Matches FMul with LHS and RHS in either order.
2798 template <typename LHS, typename RHS>
2799 inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
2800 m_c_FMul(const LHS &L, const RHS &R) {
2801   return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
2802 }
2803 
2804 template <typename Opnd_t> struct Signum_match {
2805   Opnd_t Val;
2806   Signum_match(const Opnd_t &V) : Val(V) {}
2807 
2808   template <typename OpTy> bool match(OpTy *V) {
2809     unsigned TypeSize = V->getType()->getScalarSizeInBits();
2810     if (TypeSize == 0)
2811       return false;
2812 
2813     unsigned ShiftWidth = TypeSize - 1;
2814     Value *OpL = nullptr, *OpR = nullptr;
2815 
2816     // This is the representation of signum we match:
2817     //
2818     //  signum(x) == (x >> 63) | (-x >>u 63)
2819     //
2820     // An i1 value is its own signum, so it's correct to match
2821     //
2822     //  signum(x) == (x >> 0)  | (-x >>u 0)
2823     //
2824     // for i1 values.
2825 
2826     auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
2827     auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
2828     auto Signum = m_Or(LHS, RHS);
2829 
2830     return Signum.match(V) && OpL == OpR && Val.match(OpL);
2831   }
2832 };
2833 
2834 /// Matches a signum pattern.
2835 ///
2836 /// signum(x) =
2837 ///      x >  0  ->  1
2838 ///      x == 0  ->  0
2839 ///      x <  0  -> -1
2840 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
2841   return Signum_match<Val_t>(V);
2842 }
2843 
2844 template <int Ind, typename Opnd_t> struct ExtractValue_match {
2845   Opnd_t Val;
2846   ExtractValue_match(const Opnd_t &V) : Val(V) {}
2847 
2848   template <typename OpTy> bool match(OpTy *V) {
2849     if (auto *I = dyn_cast<ExtractValueInst>(V)) {
2850       // If Ind is -1, don't inspect indices
2851       if (Ind != -1 &&
2852           !(I->getNumIndices() == 1 && I->getIndices()[0] == (unsigned)Ind))
2853         return false;
2854       return Val.match(I->getAggregateOperand());
2855     }
2856     return false;
2857   }
2858 };
2859 
2860 /// Match a single index ExtractValue instruction.
2861 /// For example m_ExtractValue<1>(...)
2862 template <int Ind, typename Val_t>
2863 inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) {
2864   return ExtractValue_match<Ind, Val_t>(V);
2865 }
2866 
2867 /// Match an ExtractValue instruction with any index.
2868 /// For example m_ExtractValue(...)
2869 template <typename Val_t>
2870 inline ExtractValue_match<-1, Val_t> m_ExtractValue(const Val_t &V) {
2871   return ExtractValue_match<-1, Val_t>(V);
2872 }
2873 
2874 /// Matcher for a single index InsertValue instruction.
2875 template <int Ind, typename T0, typename T1> struct InsertValue_match {
2876   T0 Op0;
2877   T1 Op1;
2878 
2879   InsertValue_match(const T0 &Op0, const T1 &Op1) : Op0(Op0), Op1(Op1) {}
2880 
2881   template <typename OpTy> bool match(OpTy *V) {
2882     if (auto *I = dyn_cast<InsertValueInst>(V)) {
2883       return Op0.match(I->getOperand(0)) && Op1.match(I->getOperand(1)) &&
2884              I->getNumIndices() == 1 && Ind == I->getIndices()[0];
2885     }
2886     return false;
2887   }
2888 };
2889 
2890 /// Matches a single index InsertValue instruction.
2891 template <int Ind, typename Val_t, typename Elt_t>
2892 inline InsertValue_match<Ind, Val_t, Elt_t> m_InsertValue(const Val_t &Val,
2893                                                           const Elt_t &Elt) {
2894   return InsertValue_match<Ind, Val_t, Elt_t>(Val, Elt);
2895 }
2896 
2897 /// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or
2898 /// the constant expression
2899 ///  `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>`
2900 /// under the right conditions determined by DataLayout.
2901 struct VScaleVal_match {
2902   template <typename ITy> bool match(ITy *V) {
2903     if (m_Intrinsic<Intrinsic::vscale>().match(V))
2904       return true;
2905 
2906     Value *Ptr;
2907     if (m_PtrToInt(m_Value(Ptr)).match(V)) {
2908       if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2909         auto *DerefTy =
2910             dyn_cast<ScalableVectorType>(GEP->getSourceElementType());
2911         if (GEP->getNumIndices() == 1 && DerefTy &&
2912             DerefTy->getElementType()->isIntegerTy(8) &&
2913             m_Zero().match(GEP->getPointerOperand()) &&
2914             m_SpecificInt(1).match(GEP->idx_begin()->get()))
2915           return true;
2916       }
2917     }
2918 
2919     return false;
2920   }
2921 };
2922 
2923 inline VScaleVal_match m_VScale() {
2924   return VScaleVal_match();
2925 }
2926 
2927 template <typename LHS, typename RHS, unsigned Opcode, bool Commutable = false>
2928 struct LogicalOp_match {
2929   LHS L;
2930   RHS R;
2931 
2932   LogicalOp_match(const LHS &L, const RHS &R) : L(L), R(R) {}
2933 
2934   template <typename T> bool match(T *V) {
2935     auto *I = dyn_cast<Instruction>(V);
2936     if (!I || !I->getType()->isIntOrIntVectorTy(1))
2937       return false;
2938 
2939     if (I->getOpcode() == Opcode) {
2940       auto *Op0 = I->getOperand(0);
2941       auto *Op1 = I->getOperand(1);
2942       return (L.match(Op0) && R.match(Op1)) ||
2943              (Commutable && L.match(Op1) && R.match(Op0));
2944     }
2945 
2946     if (auto *Select = dyn_cast<SelectInst>(I)) {
2947       auto *Cond = Select->getCondition();
2948       auto *TVal = Select->getTrueValue();
2949       auto *FVal = Select->getFalseValue();
2950 
2951       // Don't match a scalar select of bool vectors.
2952       // Transforms expect a single type for operands if this matches.
2953       if (Cond->getType() != Select->getType())
2954         return false;
2955 
2956       if (Opcode == Instruction::And) {
2957         auto *C = dyn_cast<Constant>(FVal);
2958         if (C && C->isNullValue())
2959           return (L.match(Cond) && R.match(TVal)) ||
2960                  (Commutable && L.match(TVal) && R.match(Cond));
2961       } else {
2962         assert(Opcode == Instruction::Or);
2963         auto *C = dyn_cast<Constant>(TVal);
2964         if (C && C->isOneValue())
2965           return (L.match(Cond) && R.match(FVal)) ||
2966                  (Commutable && L.match(FVal) && R.match(Cond));
2967       }
2968     }
2969 
2970     return false;
2971   }
2972 };
2973 
2974 /// Matches L && R either in the form of L & R or L ? R : false.
2975 /// Note that the latter form is poison-blocking.
2976 template <typename LHS, typename RHS>
2977 inline LogicalOp_match<LHS, RHS, Instruction::And> m_LogicalAnd(const LHS &L,
2978                                                                 const RHS &R) {
2979   return LogicalOp_match<LHS, RHS, Instruction::And>(L, R);
2980 }
2981 
2982 /// Matches L && R where L and R are arbitrary values.
2983 inline auto m_LogicalAnd() { return m_LogicalAnd(m_Value(), m_Value()); }
2984 
2985 /// Matches L && R with LHS and RHS in either order.
2986 template <typename LHS, typename RHS>
2987 inline LogicalOp_match<LHS, RHS, Instruction::And, true>
2988 m_c_LogicalAnd(const LHS &L, const RHS &R) {
2989   return LogicalOp_match<LHS, RHS, Instruction::And, true>(L, R);
2990 }
2991 
2992 /// Matches L || R either in the form of L | R or L ? true : R.
2993 /// Note that the latter form is poison-blocking.
2994 template <typename LHS, typename RHS>
2995 inline LogicalOp_match<LHS, RHS, Instruction::Or> m_LogicalOr(const LHS &L,
2996                                                               const RHS &R) {
2997   return LogicalOp_match<LHS, RHS, Instruction::Or>(L, R);
2998 }
2999 
3000 /// Matches L || R where L and R are arbitrary values.
3001 inline auto m_LogicalOr() { return m_LogicalOr(m_Value(), m_Value()); }
3002 
3003 /// Matches L || R with LHS and RHS in either order.
3004 template <typename LHS, typename RHS>
3005 inline LogicalOp_match<LHS, RHS, Instruction::Or, true>
3006 m_c_LogicalOr(const LHS &L, const RHS &R) {
3007   return LogicalOp_match<LHS, RHS, Instruction::Or, true>(L, R);
3008 }
3009 
3010 /// Matches either L && R or L || R,
3011 /// either one being in the either binary or logical form.
3012 /// Note that the latter form is poison-blocking.
3013 template <typename LHS, typename RHS, bool Commutable = false>
3014 inline auto m_LogicalOp(const LHS &L, const RHS &R) {
3015   return m_CombineOr(
3016       LogicalOp_match<LHS, RHS, Instruction::And, Commutable>(L, R),
3017       LogicalOp_match<LHS, RHS, Instruction::Or, Commutable>(L, R));
3018 }
3019 
3020 /// Matches either L && R or L || R where L and R are arbitrary values.
3021 inline auto m_LogicalOp() { return m_LogicalOp(m_Value(), m_Value()); }
3022 
3023 /// Matches either L && R or L || R with LHS and RHS in either order.
3024 template <typename LHS, typename RHS>
3025 inline auto m_c_LogicalOp(const LHS &L, const RHS &R) {
3026   return m_LogicalOp<LHS, RHS, /*Commutable=*/true>(L, R);
3027 }
3028 
3029 } // end namespace PatternMatch
3030 } // end namespace llvm
3031 
3032 #endif // LLVM_IR_PATTERNMATCH_H
3033