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