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 Class> struct class_match {
matchclass_match72 template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
73 };
74
75 /// Match an arbitrary value and ignore it.
m_Value()76 inline class_match<Value> m_Value() { return class_match<Value>(); }
77
78 /// Match an arbitrary unary operation and ignore it.
m_UnOp()79 inline class_match<UnaryOperator> m_UnOp() {
80 return class_match<UnaryOperator>();
81 }
82
83 /// Match an arbitrary binary operation and ignore it.
m_BinOp()84 inline class_match<BinaryOperator> m_BinOp() {
85 return class_match<BinaryOperator>();
86 }
87
88 /// Matches any compare instruction and ignore it.
m_Cmp()89 inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
90
91 /// Match an arbitrary ConstantInt and ignore it.
m_ConstantInt()92 inline class_match<ConstantInt> m_ConstantInt() {
93 return class_match<ConstantInt>();
94 }
95
96 /// Match an arbitrary undef constant.
m_Undef()97 inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
98
99 /// Match an arbitrary poison constant.
m_Poison()100 inline class_match<PoisonValue> m_Poison() { return class_match<PoisonValue>(); }
101
102 /// Match an arbitrary Constant and ignore it.
m_Constant()103 inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
104
105 /// Match an arbitrary basic block value and ignore it.
m_BasicBlock()106 inline class_match<BasicBlock> m_BasicBlock() {
107 return class_match<BasicBlock>();
108 }
109
110 /// Inverting matcher
111 template <typename Ty> struct match_unless {
112 Ty M;
113
match_unlessmatch_unless114 match_unless(const Ty &Matcher) : M(Matcher) {}
115
matchmatch_unless116 template <typename ITy> bool match(ITy *V) { return !M.match(V); }
117 };
118
119 /// Match if the inner matcher does *NOT* match.
m_Unless(const Ty & M)120 template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) {
121 return match_unless<Ty>(M);
122 }
123
124 /// Matching combinators
125 template <typename LTy, typename RTy> struct match_combine_or {
126 LTy L;
127 RTy R;
128
match_combine_ormatch_combine_or129 match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
130
matchmatch_combine_or131 template <typename ITy> bool match(ITy *V) {
132 if (L.match(V))
133 return true;
134 if (R.match(V))
135 return true;
136 return false;
137 }
138 };
139
140 template <typename LTy, typename RTy> struct match_combine_and {
141 LTy L;
142 RTy R;
143
match_combine_andmatch_combine_and144 match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
145
matchmatch_combine_and146 template <typename ITy> bool match(ITy *V) {
147 if (L.match(V))
148 if (R.match(V))
149 return true;
150 return false;
151 }
152 };
153
154 /// Combine two pattern matchers matching L || R
155 template <typename LTy, typename RTy>
m_CombineOr(const LTy & L,const RTy & R)156 inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
157 return match_combine_or<LTy, RTy>(L, R);
158 }
159
160 /// Combine two pattern matchers matching L && R
161 template <typename LTy, typename RTy>
m_CombineAnd(const LTy & L,const RTy & R)162 inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
163 return match_combine_and<LTy, RTy>(L, R);
164 }
165
166 struct apint_match {
167 const APInt *&Res;
168 bool AllowUndef;
169
apint_matchapint_match170 apint_match(const APInt *&Res, bool AllowUndef)
171 : Res(Res), AllowUndef(AllowUndef) {}
172
matchapint_match173 template <typename ITy> bool match(ITy *V) {
174 if (auto *CI = dyn_cast<ConstantInt>(V)) {
175 Res = &CI->getValue();
176 return true;
177 }
178 if (V->getType()->isVectorTy())
179 if (const auto *C = dyn_cast<Constant>(V))
180 if (auto *CI = dyn_cast_or_null<ConstantInt>(
181 C->getSplatValue(AllowUndef))) {
182 Res = &CI->getValue();
183 return true;
184 }
185 return false;
186 }
187 };
188 // Either constexpr if or renaming ConstantFP::getValueAPF to
189 // ConstantFP::getValue is needed to do it via single template
190 // function for both apint/apfloat.
191 struct apfloat_match {
192 const APFloat *&Res;
193 bool AllowUndef;
194
apfloat_matchapfloat_match195 apfloat_match(const APFloat *&Res, bool AllowUndef)
196 : Res(Res), AllowUndef(AllowUndef) {}
197
matchapfloat_match198 template <typename ITy> bool match(ITy *V) {
199 if (auto *CI = dyn_cast<ConstantFP>(V)) {
200 Res = &CI->getValueAPF();
201 return true;
202 }
203 if (V->getType()->isVectorTy())
204 if (const auto *C = dyn_cast<Constant>(V))
205 if (auto *CI = dyn_cast_or_null<ConstantFP>(
206 C->getSplatValue(AllowUndef))) {
207 Res = &CI->getValueAPF();
208 return true;
209 }
210 return false;
211 }
212 };
213
214 /// Match a ConstantInt or splatted ConstantVector, binding the
215 /// specified pointer to the contained APInt.
m_APInt(const APInt * & Res)216 inline apint_match m_APInt(const APInt *&Res) {
217 // Forbid undefs by default to maintain previous behavior.
218 return apint_match(Res, /* AllowUndef */ false);
219 }
220
221 /// Match APInt while allowing undefs in splat vector constants.
m_APIntAllowUndef(const APInt * & Res)222 inline apint_match m_APIntAllowUndef(const APInt *&Res) {
223 return apint_match(Res, /* AllowUndef */ true);
224 }
225
226 /// Match APInt while forbidding undefs in splat vector constants.
m_APIntForbidUndef(const APInt * & Res)227 inline apint_match m_APIntForbidUndef(const APInt *&Res) {
228 return apint_match(Res, /* AllowUndef */ false);
229 }
230
231 /// Match a ConstantFP or splatted ConstantVector, binding the
232 /// specified pointer to the contained APFloat.
m_APFloat(const APFloat * & Res)233 inline apfloat_match m_APFloat(const APFloat *&Res) {
234 // Forbid undefs by default to maintain previous behavior.
235 return apfloat_match(Res, /* AllowUndef */ false);
236 }
237
238 /// Match APFloat while allowing undefs in splat vector constants.
m_APFloatAllowUndef(const APFloat * & Res)239 inline apfloat_match m_APFloatAllowUndef(const APFloat *&Res) {
240 return apfloat_match(Res, /* AllowUndef */ true);
241 }
242
243 /// Match APFloat while forbidding undefs in splat vector constants.
m_APFloatForbidUndef(const APFloat * & Res)244 inline apfloat_match m_APFloatForbidUndef(const APFloat *&Res) {
245 return apfloat_match(Res, /* AllowUndef */ false);
246 }
247
248 template <int64_t Val> struct constantint_match {
matchconstantint_match249 template <typename ITy> bool match(ITy *V) {
250 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
251 const APInt &CIV = CI->getValue();
252 if (Val >= 0)
253 return CIV == static_cast<uint64_t>(Val);
254 // If Val is negative, and CI is shorter than it, truncate to the right
255 // number of bits. If it is larger, then we have to sign extend. Just
256 // compare their negated values.
257 return -CIV == -Val;
258 }
259 return false;
260 }
261 };
262
263 /// Match a ConstantInt with a specific value.
m_ConstantInt()264 template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
265 return constantint_match<Val>();
266 }
267
268 /// This helper class is used to match constant scalars, vector splats,
269 /// and fixed width vectors that satisfy a specified predicate.
270 /// For fixed width vector constants, undefined elements are ignored.
271 template <typename Predicate, typename ConstantVal>
272 struct cstval_pred_ty : public Predicate {
matchcstval_pred_ty273 template <typename ITy> bool match(ITy *V) {
274 if (const auto *CV = dyn_cast<ConstantVal>(V))
275 return this->isValue(CV->getValue());
276 if (const auto *VTy = dyn_cast<VectorType>(V->getType())) {
277 if (const auto *C = dyn_cast<Constant>(V)) {
278 if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue()))
279 return this->isValue(CV->getValue());
280
281 // Number of elements of a scalable vector unknown at compile time
282 auto *FVTy = dyn_cast<FixedVectorType>(VTy);
283 if (!FVTy)
284 return false;
285
286 // Non-splat vector constant: check each element for a match.
287 unsigned NumElts = FVTy->getNumElements();
288 assert(NumElts != 0 && "Constant vector with no elements?");
289 bool HasNonUndefElements = false;
290 for (unsigned i = 0; i != NumElts; ++i) {
291 Constant *Elt = C->getAggregateElement(i);
292 if (!Elt)
293 return false;
294 if (isa<UndefValue>(Elt))
295 continue;
296 auto *CV = dyn_cast<ConstantVal>(Elt);
297 if (!CV || !this->isValue(CV->getValue()))
298 return false;
299 HasNonUndefElements = true;
300 }
301 return HasNonUndefElements;
302 }
303 }
304 return false;
305 }
306 };
307
308 /// specialization of cstval_pred_ty for ConstantInt
309 template <typename Predicate>
310 using cst_pred_ty = cstval_pred_ty<Predicate, ConstantInt>;
311
312 /// specialization of cstval_pred_ty for ConstantFP
313 template <typename Predicate>
314 using cstfp_pred_ty = cstval_pred_ty<Predicate, ConstantFP>;
315
316 /// This helper class is used to match scalar and vector constants that
317 /// satisfy a specified predicate, and bind them to an APInt.
318 template <typename Predicate> struct api_pred_ty : public Predicate {
319 const APInt *&Res;
320
api_pred_tyapi_pred_ty321 api_pred_ty(const APInt *&R) : Res(R) {}
322
matchapi_pred_ty323 template <typename ITy> bool match(ITy *V) {
324 if (const auto *CI = dyn_cast<ConstantInt>(V))
325 if (this->isValue(CI->getValue())) {
326 Res = &CI->getValue();
327 return true;
328 }
329 if (V->getType()->isVectorTy())
330 if (const auto *C = dyn_cast<Constant>(V))
331 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
332 if (this->isValue(CI->getValue())) {
333 Res = &CI->getValue();
334 return true;
335 }
336
337 return false;
338 }
339 };
340
341 /// This helper class is used to match scalar and vector constants that
342 /// satisfy a specified predicate, and bind them to an APFloat.
343 /// Undefs are allowed in splat vector constants.
344 template <typename Predicate> struct apf_pred_ty : public Predicate {
345 const APFloat *&Res;
346
apf_pred_tyapf_pred_ty347 apf_pred_ty(const APFloat *&R) : Res(R) {}
348
matchapf_pred_ty349 template <typename ITy> bool match(ITy *V) {
350 if (const auto *CI = dyn_cast<ConstantFP>(V))
351 if (this->isValue(CI->getValue())) {
352 Res = &CI->getValue();
353 return true;
354 }
355 if (V->getType()->isVectorTy())
356 if (const auto *C = dyn_cast<Constant>(V))
357 if (auto *CI = dyn_cast_or_null<ConstantFP>(
358 C->getSplatValue(/* AllowUndef */ true)))
359 if (this->isValue(CI->getValue())) {
360 Res = &CI->getValue();
361 return true;
362 }
363
364 return false;
365 }
366 };
367
368 ///////////////////////////////////////////////////////////////////////////////
369 //
370 // Encapsulate constant value queries for use in templated predicate matchers.
371 // This allows checking if constants match using compound predicates and works
372 // with vector constants, possibly with relaxed constraints. For example, ignore
373 // undef values.
374 //
375 ///////////////////////////////////////////////////////////////////////////////
376
377 struct is_any_apint {
isValueis_any_apint378 bool isValue(const APInt &C) { return true; }
379 };
380 /// Match an integer or vector with any integral constant.
381 /// For vectors, this includes constants with undefined elements.
m_AnyIntegralConstant()382 inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() {
383 return cst_pred_ty<is_any_apint>();
384 }
385
386 struct is_all_ones {
isValueis_all_ones387 bool isValue(const APInt &C) { return C.isAllOnesValue(); }
388 };
389 /// Match an integer or vector with all bits set.
390 /// For vectors, this includes constants with undefined elements.
m_AllOnes()391 inline cst_pred_ty<is_all_ones> m_AllOnes() {
392 return cst_pred_ty<is_all_ones>();
393 }
394
395 struct is_maxsignedvalue {
isValueis_maxsignedvalue396 bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
397 };
398 /// Match an integer or vector with values having all bits except for the high
399 /// bit set (0x7f...).
400 /// For vectors, this includes constants with undefined elements.
m_MaxSignedValue()401 inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
402 return cst_pred_ty<is_maxsignedvalue>();
403 }
m_MaxSignedValue(const APInt * & V)404 inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
405 return V;
406 }
407
408 struct is_negative {
isValueis_negative409 bool isValue(const APInt &C) { return C.isNegative(); }
410 };
411 /// Match an integer or vector of negative values.
412 /// For vectors, this includes constants with undefined elements.
m_Negative()413 inline cst_pred_ty<is_negative> m_Negative() {
414 return cst_pred_ty<is_negative>();
415 }
m_Negative(const APInt * & V)416 inline api_pred_ty<is_negative> m_Negative(const APInt *&V) {
417 return V;
418 }
419
420 struct is_nonnegative {
isValueis_nonnegative421 bool isValue(const APInt &C) { return C.isNonNegative(); }
422 };
423 /// Match an integer or vector of non-negative values.
424 /// For vectors, this includes constants with undefined elements.
m_NonNegative()425 inline cst_pred_ty<is_nonnegative> m_NonNegative() {
426 return cst_pred_ty<is_nonnegative>();
427 }
m_NonNegative(const APInt * & V)428 inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) {
429 return V;
430 }
431
432 struct is_strictlypositive {
isValueis_strictlypositive433 bool isValue(const APInt &C) { return C.isStrictlyPositive(); }
434 };
435 /// Match an integer or vector of strictly positive values.
436 /// For vectors, this includes constants with undefined elements.
m_StrictlyPositive()437 inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() {
438 return cst_pred_ty<is_strictlypositive>();
439 }
m_StrictlyPositive(const APInt * & V)440 inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) {
441 return V;
442 }
443
444 struct is_nonpositive {
isValueis_nonpositive445 bool isValue(const APInt &C) { return C.isNonPositive(); }
446 };
447 /// Match an integer or vector of non-positive values.
448 /// For vectors, this includes constants with undefined elements.
m_NonPositive()449 inline cst_pred_ty<is_nonpositive> m_NonPositive() {
450 return cst_pred_ty<is_nonpositive>();
451 }
m_NonPositive(const APInt * & V)452 inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; }
453
454 struct is_one {
isValueis_one455 bool isValue(const APInt &C) { return C.isOneValue(); }
456 };
457 /// Match an integer 1 or a vector with all elements equal to 1.
458 /// For vectors, this includes constants with undefined elements.
m_One()459 inline cst_pred_ty<is_one> m_One() {
460 return cst_pred_ty<is_one>();
461 }
462
463 struct is_zero_int {
isValueis_zero_int464 bool isValue(const APInt &C) { return C.isNullValue(); }
465 };
466 /// Match an integer 0 or a vector with all elements equal to 0.
467 /// For vectors, this includes constants with undefined elements.
m_ZeroInt()468 inline cst_pred_ty<is_zero_int> m_ZeroInt() {
469 return cst_pred_ty<is_zero_int>();
470 }
471
472 struct is_zero {
matchis_zero473 template <typename ITy> bool match(ITy *V) {
474 auto *C = dyn_cast<Constant>(V);
475 // FIXME: this should be able to do something for scalable vectors
476 return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
477 }
478 };
479 /// Match any null constant or a vector with all elements equal to 0.
480 /// For vectors, this includes constants with undefined elements.
m_Zero()481 inline is_zero m_Zero() {
482 return is_zero();
483 }
484
485 struct is_power2 {
isValueis_power2486 bool isValue(const APInt &C) { return C.isPowerOf2(); }
487 };
488 /// Match an integer or vector power-of-2.
489 /// For vectors, this includes constants with undefined elements.
m_Power2()490 inline cst_pred_ty<is_power2> m_Power2() {
491 return cst_pred_ty<is_power2>();
492 }
m_Power2(const APInt * & V)493 inline api_pred_ty<is_power2> m_Power2(const APInt *&V) {
494 return V;
495 }
496
497 struct is_negated_power2 {
isValueis_negated_power2498 bool isValue(const APInt &C) { return (-C).isPowerOf2(); }
499 };
500 /// Match a integer or vector negated power-of-2.
501 /// For vectors, this includes constants with undefined elements.
m_NegatedPower2()502 inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
503 return cst_pred_ty<is_negated_power2>();
504 }
m_NegatedPower2(const APInt * & V)505 inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
506 return V;
507 }
508
509 struct is_power2_or_zero {
isValueis_power2_or_zero510 bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
511 };
512 /// Match an integer or vector of 0 or power-of-2 values.
513 /// For vectors, this includes constants with undefined elements.
m_Power2OrZero()514 inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
515 return cst_pred_ty<is_power2_or_zero>();
516 }
m_Power2OrZero(const APInt * & V)517 inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
518 return V;
519 }
520
521 struct is_sign_mask {
isValueis_sign_mask522 bool isValue(const APInt &C) { return C.isSignMask(); }
523 };
524 /// Match an integer or vector with only the sign bit(s) set.
525 /// For vectors, this includes constants with undefined elements.
m_SignMask()526 inline cst_pred_ty<is_sign_mask> m_SignMask() {
527 return cst_pred_ty<is_sign_mask>();
528 }
529
530 struct is_lowbit_mask {
isValueis_lowbit_mask531 bool isValue(const APInt &C) { return C.isMask(); }
532 };
533 /// Match an integer or vector with only the low bit(s) set.
534 /// For vectors, this includes constants with undefined elements.
m_LowBitMask()535 inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
536 return cst_pred_ty<is_lowbit_mask>();
537 }
538
539 struct icmp_pred_with_threshold {
540 ICmpInst::Predicate Pred;
541 const APInt *Thr;
isValueicmp_pred_with_threshold542 bool isValue(const APInt &C) {
543 switch (Pred) {
544 case ICmpInst::Predicate::ICMP_EQ:
545 return C.eq(*Thr);
546 case ICmpInst::Predicate::ICMP_NE:
547 return C.ne(*Thr);
548 case ICmpInst::Predicate::ICMP_UGT:
549 return C.ugt(*Thr);
550 case ICmpInst::Predicate::ICMP_UGE:
551 return C.uge(*Thr);
552 case ICmpInst::Predicate::ICMP_ULT:
553 return C.ult(*Thr);
554 case ICmpInst::Predicate::ICMP_ULE:
555 return C.ule(*Thr);
556 case ICmpInst::Predicate::ICMP_SGT:
557 return C.sgt(*Thr);
558 case ICmpInst::Predicate::ICMP_SGE:
559 return C.sge(*Thr);
560 case ICmpInst::Predicate::ICMP_SLT:
561 return C.slt(*Thr);
562 case ICmpInst::Predicate::ICMP_SLE:
563 return C.sle(*Thr);
564 default:
565 llvm_unreachable("Unhandled ICmp predicate");
566 }
567 }
568 };
569 /// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
570 /// to Threshold. For vectors, this includes constants with undefined elements.
571 inline cst_pred_ty<icmp_pred_with_threshold>
m_SpecificInt_ICMP(ICmpInst::Predicate Predicate,const APInt & Threshold)572 m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
573 cst_pred_ty<icmp_pred_with_threshold> P;
574 P.Pred = Predicate;
575 P.Thr = &Threshold;
576 return P;
577 }
578
579 struct is_nan {
isValueis_nan580 bool isValue(const APFloat &C) { return C.isNaN(); }
581 };
582 /// Match an arbitrary NaN constant. This includes quiet and signalling nans.
583 /// For vectors, this includes constants with undefined elements.
m_NaN()584 inline cstfp_pred_ty<is_nan> m_NaN() {
585 return cstfp_pred_ty<is_nan>();
586 }
587
588 struct is_nonnan {
isValueis_nonnan589 bool isValue(const APFloat &C) { return !C.isNaN(); }
590 };
591 /// Match a non-NaN FP constant.
592 /// For vectors, this includes constants with undefined elements.
m_NonNaN()593 inline cstfp_pred_ty<is_nonnan> m_NonNaN() {
594 return cstfp_pred_ty<is_nonnan>();
595 }
596
597 struct is_inf {
isValueis_inf598 bool isValue(const APFloat &C) { return C.isInfinity(); }
599 };
600 /// Match a positive or negative infinity FP constant.
601 /// For vectors, this includes constants with undefined elements.
m_Inf()602 inline cstfp_pred_ty<is_inf> m_Inf() {
603 return cstfp_pred_ty<is_inf>();
604 }
605
606 struct is_noninf {
isValueis_noninf607 bool isValue(const APFloat &C) { return !C.isInfinity(); }
608 };
609 /// Match a non-infinity FP constant, i.e. finite or NaN.
610 /// For vectors, this includes constants with undefined elements.
m_NonInf()611 inline cstfp_pred_ty<is_noninf> m_NonInf() {
612 return cstfp_pred_ty<is_noninf>();
613 }
614
615 struct is_finite {
isValueis_finite616 bool isValue(const APFloat &C) { return C.isFinite(); }
617 };
618 /// Match a finite FP constant, i.e. not infinity or NaN.
619 /// For vectors, this includes constants with undefined elements.
m_Finite()620 inline cstfp_pred_ty<is_finite> m_Finite() {
621 return cstfp_pred_ty<is_finite>();
622 }
m_Finite(const APFloat * & V)623 inline apf_pred_ty<is_finite> m_Finite(const APFloat *&V) { return V; }
624
625 struct is_finitenonzero {
isValueis_finitenonzero626 bool isValue(const APFloat &C) { return C.isFiniteNonZero(); }
627 };
628 /// Match a finite non-zero FP constant.
629 /// For vectors, this includes constants with undefined elements.
m_FiniteNonZero()630 inline cstfp_pred_ty<is_finitenonzero> m_FiniteNonZero() {
631 return cstfp_pred_ty<is_finitenonzero>();
632 }
m_FiniteNonZero(const APFloat * & V)633 inline apf_pred_ty<is_finitenonzero> m_FiniteNonZero(const APFloat *&V) {
634 return V;
635 }
636
637 struct is_any_zero_fp {
isValueis_any_zero_fp638 bool isValue(const APFloat &C) { return C.isZero(); }
639 };
640 /// Match a floating-point negative zero or positive zero.
641 /// For vectors, this includes constants with undefined elements.
m_AnyZeroFP()642 inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
643 return cstfp_pred_ty<is_any_zero_fp>();
644 }
645
646 struct is_pos_zero_fp {
isValueis_pos_zero_fp647 bool isValue(const APFloat &C) { return C.isPosZero(); }
648 };
649 /// Match a floating-point positive zero.
650 /// For vectors, this includes constants with undefined elements.
m_PosZeroFP()651 inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
652 return cstfp_pred_ty<is_pos_zero_fp>();
653 }
654
655 struct is_neg_zero_fp {
isValueis_neg_zero_fp656 bool isValue(const APFloat &C) { return C.isNegZero(); }
657 };
658 /// Match a floating-point negative zero.
659 /// For vectors, this includes constants with undefined elements.
m_NegZeroFP()660 inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
661 return cstfp_pred_ty<is_neg_zero_fp>();
662 }
663
664 struct is_non_zero_fp {
isValueis_non_zero_fp665 bool isValue(const APFloat &C) { return C.isNonZero(); }
666 };
667 /// Match a floating-point non-zero.
668 /// For vectors, this includes constants with undefined elements.
m_NonZeroFP()669 inline cstfp_pred_ty<is_non_zero_fp> m_NonZeroFP() {
670 return cstfp_pred_ty<is_non_zero_fp>();
671 }
672
673 ///////////////////////////////////////////////////////////////////////////////
674
675 template <typename Class> struct bind_ty {
676 Class *&VR;
677
bind_tybind_ty678 bind_ty(Class *&V) : VR(V) {}
679
matchbind_ty680 template <typename ITy> bool match(ITy *V) {
681 if (auto *CV = dyn_cast<Class>(V)) {
682 VR = CV;
683 return true;
684 }
685 return false;
686 }
687 };
688
689 /// Match a value, capturing it if we match.
m_Value(Value * & V)690 inline bind_ty<Value> m_Value(Value *&V) { return V; }
m_Value(const Value * & V)691 inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
692
693 /// Match an instruction, capturing it if we match.
m_Instruction(Instruction * & I)694 inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
695 /// Match a unary operator, capturing it if we match.
m_UnOp(UnaryOperator * & I)696 inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; }
697 /// Match a binary operator, capturing it if we match.
m_BinOp(BinaryOperator * & I)698 inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
699 /// Match a with overflow intrinsic, capturing it if we match.
m_WithOverflowInst(WithOverflowInst * & I)700 inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) { return I; }
701
702 /// Match a ConstantInt, capturing the value if we match.
m_ConstantInt(ConstantInt * & CI)703 inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
704
705 /// Match a Constant, capturing the value if we match.
m_Constant(Constant * & C)706 inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
707
708 /// Match a ConstantFP, capturing the value if we match.
m_ConstantFP(ConstantFP * & C)709 inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
710
711 /// Match a basic block value, capturing it if we match.
m_BasicBlock(BasicBlock * & V)712 inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
m_BasicBlock(const BasicBlock * & V)713 inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
714 return V;
715 }
716
717 /// Match a specified Value*.
718 struct specificval_ty {
719 const Value *Val;
720
specificval_tyspecificval_ty721 specificval_ty(const Value *V) : Val(V) {}
722
matchspecificval_ty723 template <typename ITy> bool match(ITy *V) { return V == Val; }
724 };
725
726 /// Match if we have a specific specified value.
m_Specific(const Value * V)727 inline specificval_ty m_Specific(const Value *V) { return V; }
728
729 /// Stores a reference to the Value *, not the Value * itself,
730 /// thus can be used in commutative matchers.
731 template <typename Class> struct deferredval_ty {
732 Class *const &Val;
733
deferredval_tydeferredval_ty734 deferredval_ty(Class *const &V) : Val(V) {}
735
matchdeferredval_ty736 template <typename ITy> bool match(ITy *const V) { return V == Val; }
737 };
738
739 /// A commutative-friendly version of m_Specific().
m_Deferred(Value * const & V)740 inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
m_Deferred(const Value * const & V)741 inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
742 return V;
743 }
744
745 /// Match a specified floating point value or vector of all elements of
746 /// that value.
747 struct specific_fpval {
748 double Val;
749
specific_fpvalspecific_fpval750 specific_fpval(double V) : Val(V) {}
751
matchspecific_fpval752 template <typename ITy> bool match(ITy *V) {
753 if (const auto *CFP = dyn_cast<ConstantFP>(V))
754 return CFP->isExactlyValue(Val);
755 if (V->getType()->isVectorTy())
756 if (const auto *C = dyn_cast<Constant>(V))
757 if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
758 return CFP->isExactlyValue(Val);
759 return false;
760 }
761 };
762
763 /// Match a specific floating point value or vector with all elements
764 /// equal to the value.
m_SpecificFP(double V)765 inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
766
767 /// Match a float 1.0 or vector with all elements equal to 1.0.
m_FPOne()768 inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
769
770 struct bind_const_intval_ty {
771 uint64_t &VR;
772
bind_const_intval_tybind_const_intval_ty773 bind_const_intval_ty(uint64_t &V) : VR(V) {}
774
matchbind_const_intval_ty775 template <typename ITy> bool match(ITy *V) {
776 if (const auto *CV = dyn_cast<ConstantInt>(V))
777 if (CV->getValue().ule(UINT64_MAX)) {
778 VR = CV->getZExtValue();
779 return true;
780 }
781 return false;
782 }
783 };
784
785 /// Match a specified integer value or vector of all elements of that
786 /// value.
787 template <bool AllowUndefs>
788 struct specific_intval {
789 APInt Val;
790
specific_intvalspecific_intval791 specific_intval(APInt V) : Val(std::move(V)) {}
792
matchspecific_intval793 template <typename ITy> bool match(ITy *V) {
794 const auto *CI = dyn_cast<ConstantInt>(V);
795 if (!CI && V->getType()->isVectorTy())
796 if (const auto *C = dyn_cast<Constant>(V))
797 CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndefs));
798
799 return CI && APInt::isSameValue(CI->getValue(), Val);
800 }
801 };
802
803 /// Match a specific integer value or vector with all elements equal to
804 /// the value.
m_SpecificInt(APInt V)805 inline specific_intval<false> m_SpecificInt(APInt V) {
806 return specific_intval<false>(std::move(V));
807 }
808
m_SpecificInt(uint64_t V)809 inline specific_intval<false> m_SpecificInt(uint64_t V) {
810 return m_SpecificInt(APInt(64, V));
811 }
812
m_SpecificIntAllowUndef(APInt V)813 inline specific_intval<true> m_SpecificIntAllowUndef(APInt V) {
814 return specific_intval<true>(std::move(V));
815 }
816
m_SpecificIntAllowUndef(uint64_t V)817 inline specific_intval<true> m_SpecificIntAllowUndef(uint64_t V) {
818 return m_SpecificIntAllowUndef(APInt(64, V));
819 }
820
821 /// Match a ConstantInt and bind to its value. This does not match
822 /// ConstantInts wider than 64-bits.
m_ConstantInt(uint64_t & V)823 inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
824
825 /// Match a specified basic block value.
826 struct specific_bbval {
827 BasicBlock *Val;
828
specific_bbvalspecific_bbval829 specific_bbval(BasicBlock *Val) : Val(Val) {}
830
matchspecific_bbval831 template <typename ITy> bool match(ITy *V) {
832 const auto *BB = dyn_cast<BasicBlock>(V);
833 return BB && BB == Val;
834 }
835 };
836
837 /// Match a specific basic block value.
m_SpecificBB(BasicBlock * BB)838 inline specific_bbval m_SpecificBB(BasicBlock *BB) {
839 return specific_bbval(BB);
840 }
841
842 /// A commutative-friendly version of m_Specific().
m_Deferred(BasicBlock * const & BB)843 inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
844 return BB;
845 }
846 inline deferredval_ty<const BasicBlock>
m_Deferred(const BasicBlock * const & BB)847 m_Deferred(const BasicBlock *const &BB) {
848 return BB;
849 }
850
851 //===----------------------------------------------------------------------===//
852 // Matcher for any binary operator.
853 //
854 template <typename LHS_t, typename RHS_t, bool Commutable = false>
855 struct AnyBinaryOp_match {
856 LHS_t L;
857 RHS_t R;
858
859 // The evaluation order is always stable, regardless of Commutability.
860 // The LHS is always matched first.
AnyBinaryOp_matchAnyBinaryOp_match861 AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
862
matchAnyBinaryOp_match863 template <typename OpTy> bool match(OpTy *V) {
864 if (auto *I = dyn_cast<BinaryOperator>(V))
865 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
866 (Commutable && L.match(I->getOperand(1)) &&
867 R.match(I->getOperand(0)));
868 return false;
869 }
870 };
871
872 template <typename LHS, typename RHS>
m_BinOp(const LHS & L,const RHS & R)873 inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
874 return AnyBinaryOp_match<LHS, RHS>(L, R);
875 }
876
877 //===----------------------------------------------------------------------===//
878 // Matcher for any unary operator.
879 // TODO fuse unary, binary matcher into n-ary matcher
880 //
881 template <typename OP_t> struct AnyUnaryOp_match {
882 OP_t X;
883
AnyUnaryOp_matchAnyUnaryOp_match884 AnyUnaryOp_match(const OP_t &X) : X(X) {}
885
matchAnyUnaryOp_match886 template <typename OpTy> bool match(OpTy *V) {
887 if (auto *I = dyn_cast<UnaryOperator>(V))
888 return X.match(I->getOperand(0));
889 return false;
890 }
891 };
892
m_UnOp(const OP_t & X)893 template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) {
894 return AnyUnaryOp_match<OP_t>(X);
895 }
896
897 //===----------------------------------------------------------------------===//
898 // Matchers for specific binary operators.
899 //
900
901 template <typename LHS_t, typename RHS_t, unsigned Opcode,
902 bool Commutable = false>
903 struct BinaryOp_match {
904 LHS_t L;
905 RHS_t R;
906
907 // The evaluation order is always stable, regardless of Commutability.
908 // The LHS is always matched first.
BinaryOp_matchBinaryOp_match909 BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
910
matchBinaryOp_match911 template <typename OpTy> bool match(OpTy *V) {
912 if (V->getValueID() == Value::InstructionVal + Opcode) {
913 auto *I = cast<BinaryOperator>(V);
914 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
915 (Commutable && L.match(I->getOperand(1)) &&
916 R.match(I->getOperand(0)));
917 }
918 if (auto *CE = dyn_cast<ConstantExpr>(V))
919 return CE->getOpcode() == Opcode &&
920 ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) ||
921 (Commutable && L.match(CE->getOperand(1)) &&
922 R.match(CE->getOperand(0))));
923 return false;
924 }
925 };
926
927 template <typename LHS, typename RHS>
m_Add(const LHS & L,const RHS & R)928 inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
929 const RHS &R) {
930 return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
931 }
932
933 template <typename LHS, typename RHS>
m_FAdd(const LHS & L,const RHS & R)934 inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
935 const RHS &R) {
936 return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
937 }
938
939 template <typename LHS, typename RHS>
m_Sub(const LHS & L,const RHS & R)940 inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
941 const RHS &R) {
942 return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
943 }
944
945 template <typename LHS, typename RHS>
m_FSub(const LHS & L,const RHS & R)946 inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
947 const RHS &R) {
948 return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
949 }
950
951 template <typename Op_t> struct FNeg_match {
952 Op_t X;
953
FNeg_matchFNeg_match954 FNeg_match(const Op_t &Op) : X(Op) {}
matchFNeg_match955 template <typename OpTy> bool match(OpTy *V) {
956 auto *FPMO = dyn_cast<FPMathOperator>(V);
957 if (!FPMO) return false;
958
959 if (FPMO->getOpcode() == Instruction::FNeg)
960 return X.match(FPMO->getOperand(0));
961
962 if (FPMO->getOpcode() == Instruction::FSub) {
963 if (FPMO->hasNoSignedZeros()) {
964 // With 'nsz', any zero goes.
965 if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
966 return false;
967 } else {
968 // Without 'nsz', we need fsub -0.0, X exactly.
969 if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
970 return false;
971 }
972
973 return X.match(FPMO->getOperand(1));
974 }
975
976 return false;
977 }
978 };
979
980 /// Match 'fneg X' as 'fsub -0.0, X'.
981 template <typename OpTy>
982 inline FNeg_match<OpTy>
m_FNeg(const OpTy & X)983 m_FNeg(const OpTy &X) {
984 return FNeg_match<OpTy>(X);
985 }
986
987 /// Match 'fneg X' as 'fsub +-0.0, X'.
988 template <typename RHS>
989 inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
m_FNegNSZ(const RHS & X)990 m_FNegNSZ(const RHS &X) {
991 return m_FSub(m_AnyZeroFP(), X);
992 }
993
994 template <typename LHS, typename RHS>
m_Mul(const LHS & L,const RHS & R)995 inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
996 const RHS &R) {
997 return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
998 }
999
1000 template <typename LHS, typename RHS>
m_FMul(const LHS & L,const RHS & R)1001 inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
1002 const RHS &R) {
1003 return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
1004 }
1005
1006 template <typename LHS, typename RHS>
m_UDiv(const LHS & L,const RHS & R)1007 inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
1008 const RHS &R) {
1009 return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
1010 }
1011
1012 template <typename LHS, typename RHS>
m_SDiv(const LHS & L,const RHS & R)1013 inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
1014 const RHS &R) {
1015 return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
1016 }
1017
1018 template <typename LHS, typename RHS>
m_FDiv(const LHS & L,const RHS & R)1019 inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
1020 const RHS &R) {
1021 return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
1022 }
1023
1024 template <typename LHS, typename RHS>
m_URem(const LHS & L,const RHS & R)1025 inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
1026 const RHS &R) {
1027 return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
1028 }
1029
1030 template <typename LHS, typename RHS>
m_SRem(const LHS & L,const RHS & R)1031 inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
1032 const RHS &R) {
1033 return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
1034 }
1035
1036 template <typename LHS, typename RHS>
m_FRem(const LHS & L,const RHS & R)1037 inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
1038 const RHS &R) {
1039 return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
1040 }
1041
1042 template <typename LHS, typename RHS>
m_And(const LHS & L,const RHS & R)1043 inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
1044 const RHS &R) {
1045 return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
1046 }
1047
1048 template <typename LHS, typename RHS>
m_Or(const LHS & L,const RHS & R)1049 inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
1050 const RHS &R) {
1051 return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
1052 }
1053
1054 template <typename LHS, typename RHS>
m_Xor(const LHS & L,const RHS & R)1055 inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
1056 const RHS &R) {
1057 return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
1058 }
1059
1060 template <typename LHS, typename RHS>
m_Shl(const LHS & L,const RHS & R)1061 inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
1062 const RHS &R) {
1063 return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
1064 }
1065
1066 template <typename LHS, typename RHS>
m_LShr(const LHS & L,const RHS & R)1067 inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
1068 const RHS &R) {
1069 return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
1070 }
1071
1072 template <typename LHS, typename RHS>
m_AShr(const LHS & L,const RHS & R)1073 inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
1074 const RHS &R) {
1075 return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
1076 }
1077
1078 template <typename LHS_t, typename RHS_t, unsigned Opcode,
1079 unsigned WrapFlags = 0>
1080 struct OverflowingBinaryOp_match {
1081 LHS_t L;
1082 RHS_t R;
1083
OverflowingBinaryOp_matchOverflowingBinaryOp_match1084 OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
1085 : L(LHS), R(RHS) {}
1086
matchOverflowingBinaryOp_match1087 template <typename OpTy> bool match(OpTy *V) {
1088 if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
1089 if (Op->getOpcode() != Opcode)
1090 return false;
1091 if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap &&
1092 !Op->hasNoUnsignedWrap())
1093 return false;
1094 if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap &&
1095 !Op->hasNoSignedWrap())
1096 return false;
1097 return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
1098 }
1099 return false;
1100 }
1101 };
1102
1103 template <typename LHS, typename RHS>
1104 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1105 OverflowingBinaryOperator::NoSignedWrap>
m_NSWAdd(const LHS & L,const RHS & R)1106 m_NSWAdd(const LHS &L, const RHS &R) {
1107 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1108 OverflowingBinaryOperator::NoSignedWrap>(
1109 L, R);
1110 }
1111 template <typename LHS, typename RHS>
1112 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1113 OverflowingBinaryOperator::NoSignedWrap>
m_NSWSub(const LHS & L,const RHS & R)1114 m_NSWSub(const LHS &L, const RHS &R) {
1115 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1116 OverflowingBinaryOperator::NoSignedWrap>(
1117 L, R);
1118 }
1119 template <typename LHS, typename RHS>
1120 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1121 OverflowingBinaryOperator::NoSignedWrap>
m_NSWMul(const LHS & L,const RHS & R)1122 m_NSWMul(const LHS &L, const RHS &R) {
1123 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1124 OverflowingBinaryOperator::NoSignedWrap>(
1125 L, R);
1126 }
1127 template <typename LHS, typename RHS>
1128 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1129 OverflowingBinaryOperator::NoSignedWrap>
m_NSWShl(const LHS & L,const RHS & R)1130 m_NSWShl(const LHS &L, const RHS &R) {
1131 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1132 OverflowingBinaryOperator::NoSignedWrap>(
1133 L, R);
1134 }
1135
1136 template <typename LHS, typename RHS>
1137 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1138 OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWAdd(const LHS & L,const RHS & R)1139 m_NUWAdd(const LHS &L, const RHS &R) {
1140 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1141 OverflowingBinaryOperator::NoUnsignedWrap>(
1142 L, R);
1143 }
1144 template <typename LHS, typename RHS>
1145 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1146 OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWSub(const LHS & L,const RHS & R)1147 m_NUWSub(const LHS &L, const RHS &R) {
1148 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1149 OverflowingBinaryOperator::NoUnsignedWrap>(
1150 L, R);
1151 }
1152 template <typename LHS, typename RHS>
1153 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1154 OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWMul(const LHS & L,const RHS & R)1155 m_NUWMul(const LHS &L, const RHS &R) {
1156 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1157 OverflowingBinaryOperator::NoUnsignedWrap>(
1158 L, R);
1159 }
1160 template <typename LHS, typename RHS>
1161 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1162 OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWShl(const LHS & L,const RHS & R)1163 m_NUWShl(const LHS &L, const RHS &R) {
1164 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1165 OverflowingBinaryOperator::NoUnsignedWrap>(
1166 L, R);
1167 }
1168
1169 //===----------------------------------------------------------------------===//
1170 // Class that matches a group of binary opcodes.
1171 //
1172 template <typename LHS_t, typename RHS_t, typename Predicate>
1173 struct BinOpPred_match : Predicate {
1174 LHS_t L;
1175 RHS_t R;
1176
BinOpPred_matchBinOpPred_match1177 BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1178
matchBinOpPred_match1179 template <typename OpTy> bool match(OpTy *V) {
1180 if (auto *I = dyn_cast<Instruction>(V))
1181 return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
1182 R.match(I->getOperand(1));
1183 if (auto *CE = dyn_cast<ConstantExpr>(V))
1184 return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) &&
1185 R.match(CE->getOperand(1));
1186 return false;
1187 }
1188 };
1189
1190 struct is_shift_op {
isOpTypeis_shift_op1191 bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1192 };
1193
1194 struct is_right_shift_op {
isOpTypeis_right_shift_op1195 bool isOpType(unsigned Opcode) {
1196 return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1197 }
1198 };
1199
1200 struct is_logical_shift_op {
isOpTypeis_logical_shift_op1201 bool isOpType(unsigned Opcode) {
1202 return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1203 }
1204 };
1205
1206 struct is_bitwiselogic_op {
isOpTypeis_bitwiselogic_op1207 bool isOpType(unsigned Opcode) {
1208 return Instruction::isBitwiseLogicOp(Opcode);
1209 }
1210 };
1211
1212 struct is_idiv_op {
isOpTypeis_idiv_op1213 bool isOpType(unsigned Opcode) {
1214 return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1215 }
1216 };
1217
1218 struct is_irem_op {
isOpTypeis_irem_op1219 bool isOpType(unsigned Opcode) {
1220 return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1221 }
1222 };
1223
1224 /// Matches shift operations.
1225 template <typename LHS, typename RHS>
m_Shift(const LHS & L,const RHS & R)1226 inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1227 const RHS &R) {
1228 return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1229 }
1230
1231 /// Matches logical shift operations.
1232 template <typename LHS, typename RHS>
m_Shr(const LHS & L,const RHS & R)1233 inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1234 const RHS &R) {
1235 return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1236 }
1237
1238 /// Matches logical shift operations.
1239 template <typename LHS, typename RHS>
1240 inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
m_LogicalShift(const LHS & L,const RHS & R)1241 m_LogicalShift(const LHS &L, const RHS &R) {
1242 return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1243 }
1244
1245 /// Matches bitwise logic operations.
1246 template <typename LHS, typename RHS>
1247 inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
m_BitwiseLogic(const LHS & L,const RHS & R)1248 m_BitwiseLogic(const LHS &L, const RHS &R) {
1249 return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1250 }
1251
1252 /// Matches integer division operations.
1253 template <typename LHS, typename RHS>
m_IDiv(const LHS & L,const RHS & R)1254 inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1255 const RHS &R) {
1256 return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1257 }
1258
1259 /// Matches integer remainder operations.
1260 template <typename LHS, typename RHS>
m_IRem(const LHS & L,const RHS & R)1261 inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1262 const RHS &R) {
1263 return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1264 }
1265
1266 //===----------------------------------------------------------------------===//
1267 // Class that matches exact binary ops.
1268 //
1269 template <typename SubPattern_t> struct Exact_match {
1270 SubPattern_t SubPattern;
1271
Exact_matchExact_match1272 Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1273
matchExact_match1274 template <typename OpTy> bool match(OpTy *V) {
1275 if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1276 return PEO->isExact() && SubPattern.match(V);
1277 return false;
1278 }
1279 };
1280
m_Exact(const T & SubPattern)1281 template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1282 return SubPattern;
1283 }
1284
1285 //===----------------------------------------------------------------------===//
1286 // Matchers for CmpInst classes
1287 //
1288
1289 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1290 bool Commutable = false>
1291 struct CmpClass_match {
1292 PredicateTy &Predicate;
1293 LHS_t L;
1294 RHS_t R;
1295
1296 // The evaluation order is always stable, regardless of Commutability.
1297 // The LHS is always matched first.
CmpClass_matchCmpClass_match1298 CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1299 : Predicate(Pred), L(LHS), R(RHS) {}
1300
matchCmpClass_match1301 template <typename OpTy> bool match(OpTy *V) {
1302 if (auto *I = dyn_cast<Class>(V)) {
1303 if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
1304 Predicate = I->getPredicate();
1305 return true;
1306 } else if (Commutable && L.match(I->getOperand(1)) &&
1307 R.match(I->getOperand(0))) {
1308 Predicate = I->getSwappedPredicate();
1309 return true;
1310 }
1311 }
1312 return false;
1313 }
1314 };
1315
1316 template <typename LHS, typename RHS>
1317 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
m_Cmp(CmpInst::Predicate & Pred,const LHS & L,const RHS & R)1318 m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1319 return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1320 }
1321
1322 template <typename LHS, typename RHS>
1323 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
m_ICmp(ICmpInst::Predicate & Pred,const LHS & L,const RHS & R)1324 m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1325 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1326 }
1327
1328 template <typename LHS, typename RHS>
1329 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
m_FCmp(FCmpInst::Predicate & Pred,const LHS & L,const RHS & R)1330 m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1331 return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1332 }
1333
1334 //===----------------------------------------------------------------------===//
1335 // Matchers for instructions with a given opcode and number of operands.
1336 //
1337
1338 /// Matches instructions with Opcode and three operands.
1339 template <typename T0, unsigned Opcode> struct OneOps_match {
1340 T0 Op1;
1341
OneOps_matchOneOps_match1342 OneOps_match(const T0 &Op1) : Op1(Op1) {}
1343
matchOneOps_match1344 template <typename OpTy> bool match(OpTy *V) {
1345 if (V->getValueID() == Value::InstructionVal + Opcode) {
1346 auto *I = cast<Instruction>(V);
1347 return Op1.match(I->getOperand(0));
1348 }
1349 return false;
1350 }
1351 };
1352
1353 /// Matches instructions with Opcode and three operands.
1354 template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1355 T0 Op1;
1356 T1 Op2;
1357
TwoOps_matchTwoOps_match1358 TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1359
matchTwoOps_match1360 template <typename OpTy> bool match(OpTy *V) {
1361 if (V->getValueID() == Value::InstructionVal + Opcode) {
1362 auto *I = cast<Instruction>(V);
1363 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1364 }
1365 return false;
1366 }
1367 };
1368
1369 /// Matches instructions with Opcode and three operands.
1370 template <typename T0, typename T1, typename T2, unsigned Opcode>
1371 struct ThreeOps_match {
1372 T0 Op1;
1373 T1 Op2;
1374 T2 Op3;
1375
ThreeOps_matchThreeOps_match1376 ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1377 : Op1(Op1), Op2(Op2), Op3(Op3) {}
1378
matchThreeOps_match1379 template <typename OpTy> bool match(OpTy *V) {
1380 if (V->getValueID() == Value::InstructionVal + Opcode) {
1381 auto *I = cast<Instruction>(V);
1382 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1383 Op3.match(I->getOperand(2));
1384 }
1385 return false;
1386 }
1387 };
1388
1389 /// Matches SelectInst.
1390 template <typename Cond, typename LHS, typename RHS>
1391 inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
m_Select(const Cond & C,const LHS & L,const RHS & R)1392 m_Select(const Cond &C, const LHS &L, const RHS &R) {
1393 return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1394 }
1395
1396 /// This matches a select of two constants, e.g.:
1397 /// m_SelectCst<-1, 0>(m_Value(V))
1398 template <int64_t L, int64_t R, typename Cond>
1399 inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1400 Instruction::Select>
m_SelectCst(const Cond & C)1401 m_SelectCst(const Cond &C) {
1402 return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1403 }
1404
1405 /// Matches FreezeInst.
1406 template <typename OpTy>
m_Freeze(const OpTy & Op)1407 inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) {
1408 return OneOps_match<OpTy, Instruction::Freeze>(Op);
1409 }
1410
1411 /// Matches InsertElementInst.
1412 template <typename Val_t, typename Elt_t, typename Idx_t>
1413 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)1414 m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1415 return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1416 Val, Elt, Idx);
1417 }
1418
1419 /// Matches ExtractElementInst.
1420 template <typename Val_t, typename Idx_t>
1421 inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
m_ExtractElt(const Val_t & Val,const Idx_t & Idx)1422 m_ExtractElt(const Val_t &Val, const Idx_t &Idx) {
1423 return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1424 }
1425
1426 /// Matches shuffle.
1427 template <typename T0, typename T1, typename T2> struct Shuffle_match {
1428 T0 Op1;
1429 T1 Op2;
1430 T2 Mask;
1431
Shuffle_matchShuffle_match1432 Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask)
1433 : Op1(Op1), Op2(Op2), Mask(Mask) {}
1434
matchShuffle_match1435 template <typename OpTy> bool match(OpTy *V) {
1436 if (auto *I = dyn_cast<ShuffleVectorInst>(V)) {
1437 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1438 Mask.match(I->getShuffleMask());
1439 }
1440 return false;
1441 }
1442 };
1443
1444 struct m_Mask {
1445 ArrayRef<int> &MaskRef;
m_Maskm_Mask1446 m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
matchm_Mask1447 bool match(ArrayRef<int> Mask) {
1448 MaskRef = Mask;
1449 return true;
1450 }
1451 };
1452
1453 struct m_ZeroMask {
matchm_ZeroMask1454 bool match(ArrayRef<int> Mask) {
1455 return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; });
1456 }
1457 };
1458
1459 struct m_SpecificMask {
1460 ArrayRef<int> &MaskRef;
m_SpecificMaskm_SpecificMask1461 m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
matchm_SpecificMask1462 bool match(ArrayRef<int> Mask) { return MaskRef == Mask; }
1463 };
1464
1465 struct m_SplatOrUndefMask {
1466 int &SplatIndex;
m_SplatOrUndefMaskm_SplatOrUndefMask1467 m_SplatOrUndefMask(int &SplatIndex) : SplatIndex(SplatIndex) {}
matchm_SplatOrUndefMask1468 bool match(ArrayRef<int> Mask) {
1469 auto First = find_if(Mask, [](int Elem) { return Elem != -1; });
1470 if (First == Mask.end())
1471 return false;
1472 SplatIndex = *First;
1473 return all_of(Mask,
1474 [First](int Elem) { return Elem == *First || Elem == -1; });
1475 }
1476 };
1477
1478 /// Matches ShuffleVectorInst independently of mask value.
1479 template <typename V1_t, typename V2_t>
1480 inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>
m_Shuffle(const V1_t & v1,const V2_t & v2)1481 m_Shuffle(const V1_t &v1, const V2_t &v2) {
1482 return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2);
1483 }
1484
1485 template <typename V1_t, typename V2_t, typename Mask_t>
1486 inline Shuffle_match<V1_t, V2_t, Mask_t>
m_Shuffle(const V1_t & v1,const V2_t & v2,const Mask_t & mask)1487 m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) {
1488 return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask);
1489 }
1490
1491 /// Matches LoadInst.
1492 template <typename OpTy>
m_Load(const OpTy & Op)1493 inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1494 return OneOps_match<OpTy, Instruction::Load>(Op);
1495 }
1496
1497 /// Matches StoreInst.
1498 template <typename ValueOpTy, typename PointerOpTy>
1499 inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
m_Store(const ValueOpTy & ValueOp,const PointerOpTy & PointerOp)1500 m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1501 return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1502 PointerOp);
1503 }
1504
1505 //===----------------------------------------------------------------------===//
1506 // Matchers for CastInst classes
1507 //
1508
1509 template <typename Op_t, unsigned Opcode> struct CastClass_match {
1510 Op_t Op;
1511
CastClass_matchCastClass_match1512 CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1513
matchCastClass_match1514 template <typename OpTy> bool match(OpTy *V) {
1515 if (auto *O = dyn_cast<Operator>(V))
1516 return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1517 return false;
1518 }
1519 };
1520
1521 /// Matches BitCast.
1522 template <typename OpTy>
m_BitCast(const OpTy & Op)1523 inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
1524 return CastClass_match<OpTy, Instruction::BitCast>(Op);
1525 }
1526
1527 /// Matches PtrToInt.
1528 template <typename OpTy>
m_PtrToInt(const OpTy & Op)1529 inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
1530 return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
1531 }
1532
1533 /// Matches IntToPtr.
1534 template <typename OpTy>
m_IntToPtr(const OpTy & Op)1535 inline CastClass_match<OpTy, Instruction::IntToPtr> m_IntToPtr(const OpTy &Op) {
1536 return CastClass_match<OpTy, Instruction::IntToPtr>(Op);
1537 }
1538
1539 /// Matches Trunc.
1540 template <typename OpTy>
m_Trunc(const OpTy & Op)1541 inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1542 return CastClass_match<OpTy, Instruction::Trunc>(Op);
1543 }
1544
1545 template <typename OpTy>
1546 inline match_combine_or<CastClass_match<OpTy, Instruction::Trunc>, OpTy>
m_TruncOrSelf(const OpTy & Op)1547 m_TruncOrSelf(const OpTy &Op) {
1548 return m_CombineOr(m_Trunc(Op), Op);
1549 }
1550
1551 /// Matches SExt.
1552 template <typename OpTy>
m_SExt(const OpTy & Op)1553 inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
1554 return CastClass_match<OpTy, Instruction::SExt>(Op);
1555 }
1556
1557 /// Matches ZExt.
1558 template <typename OpTy>
m_ZExt(const OpTy & Op)1559 inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
1560 return CastClass_match<OpTy, Instruction::ZExt>(Op);
1561 }
1562
1563 template <typename OpTy>
1564 inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, OpTy>
m_ZExtOrSelf(const OpTy & Op)1565 m_ZExtOrSelf(const OpTy &Op) {
1566 return m_CombineOr(m_ZExt(Op), Op);
1567 }
1568
1569 template <typename OpTy>
1570 inline match_combine_or<CastClass_match<OpTy, Instruction::SExt>, OpTy>
m_SExtOrSelf(const OpTy & Op)1571 m_SExtOrSelf(const OpTy &Op) {
1572 return m_CombineOr(m_SExt(Op), Op);
1573 }
1574
1575 template <typename OpTy>
1576 inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1577 CastClass_match<OpTy, Instruction::SExt>>
m_ZExtOrSExt(const OpTy & Op)1578 m_ZExtOrSExt(const OpTy &Op) {
1579 return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1580 }
1581
1582 template <typename OpTy>
1583 inline match_combine_or<
1584 match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1585 CastClass_match<OpTy, Instruction::SExt>>,
1586 OpTy>
m_ZExtOrSExtOrSelf(const OpTy & Op)1587 m_ZExtOrSExtOrSelf(const OpTy &Op) {
1588 return m_CombineOr(m_ZExtOrSExt(Op), Op);
1589 }
1590
1591 template <typename OpTy>
m_UIToFP(const OpTy & Op)1592 inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
1593 return CastClass_match<OpTy, Instruction::UIToFP>(Op);
1594 }
1595
1596 template <typename OpTy>
m_SIToFP(const OpTy & Op)1597 inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
1598 return CastClass_match<OpTy, Instruction::SIToFP>(Op);
1599 }
1600
1601 template <typename OpTy>
m_FPToUI(const OpTy & Op)1602 inline CastClass_match<OpTy, Instruction::FPToUI> m_FPToUI(const OpTy &Op) {
1603 return CastClass_match<OpTy, Instruction::FPToUI>(Op);
1604 }
1605
1606 template <typename OpTy>
m_FPToSI(const OpTy & Op)1607 inline CastClass_match<OpTy, Instruction::FPToSI> m_FPToSI(const OpTy &Op) {
1608 return CastClass_match<OpTy, Instruction::FPToSI>(Op);
1609 }
1610
1611 template <typename OpTy>
m_FPTrunc(const OpTy & Op)1612 inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
1613 return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
1614 }
1615
1616 template <typename OpTy>
m_FPExt(const OpTy & Op)1617 inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
1618 return CastClass_match<OpTy, Instruction::FPExt>(Op);
1619 }
1620
1621 //===----------------------------------------------------------------------===//
1622 // Matchers for control flow.
1623 //
1624
1625 struct br_match {
1626 BasicBlock *&Succ;
1627
br_matchbr_match1628 br_match(BasicBlock *&Succ) : Succ(Succ) {}
1629
matchbr_match1630 template <typename OpTy> bool match(OpTy *V) {
1631 if (auto *BI = dyn_cast<BranchInst>(V))
1632 if (BI->isUnconditional()) {
1633 Succ = BI->getSuccessor(0);
1634 return true;
1635 }
1636 return false;
1637 }
1638 };
1639
m_UnconditionalBr(BasicBlock * & Succ)1640 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1641
1642 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1643 struct brc_match {
1644 Cond_t Cond;
1645 TrueBlock_t T;
1646 FalseBlock_t F;
1647
brc_matchbrc_match1648 brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
1649 : Cond(C), T(t), F(f) {}
1650
matchbrc_match1651 template <typename OpTy> bool match(OpTy *V) {
1652 if (auto *BI = dyn_cast<BranchInst>(V))
1653 if (BI->isConditional() && Cond.match(BI->getCondition()))
1654 return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
1655 return false;
1656 }
1657 };
1658
1659 template <typename Cond_t>
1660 inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
m_Br(const Cond_t & C,BasicBlock * & T,BasicBlock * & F)1661 m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1662 return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
1663 C, m_BasicBlock(T), m_BasicBlock(F));
1664 }
1665
1666 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1667 inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
m_Br(const Cond_t & C,const TrueBlock_t & T,const FalseBlock_t & F)1668 m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
1669 return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
1670 }
1671
1672 //===----------------------------------------------------------------------===//
1673 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1674 //
1675
1676 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1677 bool Commutable = false>
1678 struct MaxMin_match {
1679 LHS_t L;
1680 RHS_t R;
1681
1682 // The evaluation order is always stable, regardless of Commutability.
1683 // The LHS is always matched first.
MaxMin_matchMaxMin_match1684 MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1685
matchMaxMin_match1686 template <typename OpTy> bool match(OpTy *V) {
1687 if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1688 Intrinsic::ID IID = II->getIntrinsicID();
1689 if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) ||
1690 (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) ||
1691 (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) ||
1692 (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) {
1693 Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1694 return (L.match(LHS) && R.match(RHS)) ||
1695 (Commutable && L.match(RHS) && R.match(LHS));
1696 }
1697 }
1698 // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1699 auto *SI = dyn_cast<SelectInst>(V);
1700 if (!SI)
1701 return false;
1702 auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1703 if (!Cmp)
1704 return false;
1705 // At this point we have a select conditioned on a comparison. Check that
1706 // it is the values returned by the select that are being compared.
1707 Value *TrueVal = SI->getTrueValue();
1708 Value *FalseVal = SI->getFalseValue();
1709 Value *LHS = Cmp->getOperand(0);
1710 Value *RHS = Cmp->getOperand(1);
1711 if ((TrueVal != LHS || FalseVal != RHS) &&
1712 (TrueVal != RHS || FalseVal != LHS))
1713 return false;
1714 typename CmpInst_t::Predicate Pred =
1715 LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1716 // Does "(x pred y) ? x : y" represent the desired max/min operation?
1717 if (!Pred_t::match(Pred))
1718 return false;
1719 // It does! Bind the operands.
1720 return (L.match(LHS) && R.match(RHS)) ||
1721 (Commutable && L.match(RHS) && R.match(LHS));
1722 }
1723 };
1724
1725 /// Helper class for identifying signed max predicates.
1726 struct smax_pred_ty {
matchsmax_pred_ty1727 static bool match(ICmpInst::Predicate Pred) {
1728 return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1729 }
1730 };
1731
1732 /// Helper class for identifying signed min predicates.
1733 struct smin_pred_ty {
matchsmin_pred_ty1734 static bool match(ICmpInst::Predicate Pred) {
1735 return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1736 }
1737 };
1738
1739 /// Helper class for identifying unsigned max predicates.
1740 struct umax_pred_ty {
matchumax_pred_ty1741 static bool match(ICmpInst::Predicate Pred) {
1742 return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1743 }
1744 };
1745
1746 /// Helper class for identifying unsigned min predicates.
1747 struct umin_pred_ty {
matchumin_pred_ty1748 static bool match(ICmpInst::Predicate Pred) {
1749 return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1750 }
1751 };
1752
1753 /// Helper class for identifying ordered max predicates.
1754 struct ofmax_pred_ty {
matchofmax_pred_ty1755 static bool match(FCmpInst::Predicate Pred) {
1756 return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1757 }
1758 };
1759
1760 /// Helper class for identifying ordered min predicates.
1761 struct ofmin_pred_ty {
matchofmin_pred_ty1762 static bool match(FCmpInst::Predicate Pred) {
1763 return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1764 }
1765 };
1766
1767 /// Helper class for identifying unordered max predicates.
1768 struct ufmax_pred_ty {
matchufmax_pred_ty1769 static bool match(FCmpInst::Predicate Pred) {
1770 return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1771 }
1772 };
1773
1774 /// Helper class for identifying unordered min predicates.
1775 struct ufmin_pred_ty {
matchufmin_pred_ty1776 static bool match(FCmpInst::Predicate Pred) {
1777 return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1778 }
1779 };
1780
1781 template <typename LHS, typename RHS>
m_SMax(const LHS & L,const RHS & R)1782 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1783 const RHS &R) {
1784 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1785 }
1786
1787 template <typename LHS, typename RHS>
m_SMin(const LHS & L,const RHS & R)1788 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1789 const RHS &R) {
1790 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1791 }
1792
1793 template <typename LHS, typename RHS>
m_UMax(const LHS & L,const RHS & R)1794 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1795 const RHS &R) {
1796 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1797 }
1798
1799 template <typename LHS, typename RHS>
m_UMin(const LHS & L,const RHS & R)1800 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1801 const RHS &R) {
1802 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1803 }
1804
1805 template <typename LHS, typename RHS>
1806 inline match_combine_or<
1807 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
1808 MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>,
1809 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
1810 MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>>
m_MaxOrMin(const LHS & L,const RHS & R)1811 m_MaxOrMin(const LHS &L, const RHS &R) {
1812 return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)),
1813 m_CombineOr(m_UMax(L, R), m_UMin(L, R)));
1814 }
1815
1816 /// Match an 'ordered' floating point maximum function.
1817 /// Floating point has one special value 'NaN'. Therefore, there is no total
1818 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1819 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1820 /// semantics. In the presence of 'NaN' we have to preserve the original
1821 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1822 ///
1823 /// max(L, R) iff L and R are not NaN
1824 /// m_OrdFMax(L, R) = R iff L or R are NaN
1825 template <typename LHS, typename RHS>
m_OrdFMax(const LHS & L,const RHS & R)1826 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1827 const RHS &R) {
1828 return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1829 }
1830
1831 /// Match an 'ordered' floating point minimum function.
1832 /// Floating point has one special value 'NaN'. Therefore, there is no total
1833 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1834 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1835 /// semantics. In the presence of 'NaN' we have to preserve the original
1836 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1837 ///
1838 /// min(L, R) iff L and R are not NaN
1839 /// m_OrdFMin(L, R) = R iff L or R are NaN
1840 template <typename LHS, typename RHS>
m_OrdFMin(const LHS & L,const RHS & R)1841 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1842 const RHS &R) {
1843 return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1844 }
1845
1846 /// Match an 'unordered' floating point maximum function.
1847 /// Floating point has one special value 'NaN'. Therefore, there is no total
1848 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1849 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1850 /// semantics. In the presence of 'NaN' we have to preserve the original
1851 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1852 ///
1853 /// max(L, R) iff L and R are not NaN
1854 /// m_UnordFMax(L, R) = L iff L or R are NaN
1855 template <typename LHS, typename RHS>
1856 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
m_UnordFMax(const LHS & L,const RHS & R)1857 m_UnordFMax(const LHS &L, const RHS &R) {
1858 return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1859 }
1860
1861 /// Match an 'unordered' floating point minimum function.
1862 /// Floating point has one special value 'NaN'. Therefore, there is no total
1863 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1864 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1865 /// semantics. In the presence of 'NaN' we have to preserve the original
1866 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1867 ///
1868 /// min(L, R) iff L and R are not NaN
1869 /// m_UnordFMin(L, R) = L iff L or R are NaN
1870 template <typename LHS, typename RHS>
1871 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
m_UnordFMin(const LHS & L,const RHS & R)1872 m_UnordFMin(const LHS &L, const RHS &R) {
1873 return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1874 }
1875
1876 //===----------------------------------------------------------------------===//
1877 // Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b
1878 // Note that S might be matched to other instructions than AddInst.
1879 //
1880
1881 template <typename LHS_t, typename RHS_t, typename Sum_t>
1882 struct UAddWithOverflow_match {
1883 LHS_t L;
1884 RHS_t R;
1885 Sum_t S;
1886
UAddWithOverflow_matchUAddWithOverflow_match1887 UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1888 : L(L), R(R), S(S) {}
1889
matchUAddWithOverflow_match1890 template <typename OpTy> bool match(OpTy *V) {
1891 Value *ICmpLHS, *ICmpRHS;
1892 ICmpInst::Predicate Pred;
1893 if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1894 return false;
1895
1896 Value *AddLHS, *AddRHS;
1897 auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1898
1899 // (a + b) u< a, (a + b) u< b
1900 if (Pred == ICmpInst::ICMP_ULT)
1901 if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1902 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1903
1904 // a >u (a + b), b >u (a + b)
1905 if (Pred == ICmpInst::ICMP_UGT)
1906 if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1907 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1908
1909 Value *Op1;
1910 auto XorExpr = m_OneUse(m_Xor(m_Value(Op1), m_AllOnes()));
1911 // (a ^ -1) <u b
1912 if (Pred == ICmpInst::ICMP_ULT) {
1913 if (XorExpr.match(ICmpLHS))
1914 return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS);
1915 }
1916 // b > u (a ^ -1)
1917 if (Pred == ICmpInst::ICMP_UGT) {
1918 if (XorExpr.match(ICmpRHS))
1919 return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS);
1920 }
1921
1922 // Match special-case for increment-by-1.
1923 if (Pred == ICmpInst::ICMP_EQ) {
1924 // (a + 1) == 0
1925 // (1 + a) == 0
1926 if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
1927 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1928 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1929 // 0 == (a + 1)
1930 // 0 == (1 + a)
1931 if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
1932 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1933 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1934 }
1935
1936 return false;
1937 }
1938 };
1939
1940 /// Match an icmp instruction checking for unsigned overflow on addition.
1941 ///
1942 /// S is matched to the addition whose result is being checked for overflow, and
1943 /// L and R are matched to the LHS and RHS of S.
1944 template <typename LHS_t, typename RHS_t, typename Sum_t>
1945 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
m_UAddWithOverflow(const LHS_t & L,const RHS_t & R,const Sum_t & S)1946 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1947 return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1948 }
1949
1950 template <typename Opnd_t> struct Argument_match {
1951 unsigned OpI;
1952 Opnd_t Val;
1953
Argument_matchArgument_match1954 Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1955
matchArgument_match1956 template <typename OpTy> bool match(OpTy *V) {
1957 // FIXME: Should likely be switched to use `CallBase`.
1958 if (const auto *CI = dyn_cast<CallInst>(V))
1959 return Val.match(CI->getArgOperand(OpI));
1960 return false;
1961 }
1962 };
1963
1964 /// Match an argument.
1965 template <unsigned OpI, typename Opnd_t>
m_Argument(const Opnd_t & Op)1966 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1967 return Argument_match<Opnd_t>(OpI, Op);
1968 }
1969
1970 /// Intrinsic matchers.
1971 struct IntrinsicID_match {
1972 unsigned ID;
1973
IntrinsicID_matchIntrinsicID_match1974 IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1975
matchIntrinsicID_match1976 template <typename OpTy> bool match(OpTy *V) {
1977 if (const auto *CI = dyn_cast<CallInst>(V))
1978 if (const auto *F = CI->getCalledFunction())
1979 return F->getIntrinsicID() == ID;
1980 return false;
1981 }
1982 };
1983
1984 /// Intrinsic matches are combinations of ID matchers, and argument
1985 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
1986 /// them with lower arity matchers. Here's some convenient typedefs for up to
1987 /// several arguments, and more can be added as needed
1988 template <typename T0 = void, typename T1 = void, typename T2 = void,
1989 typename T3 = void, typename T4 = void, typename T5 = void,
1990 typename T6 = void, typename T7 = void, typename T8 = void,
1991 typename T9 = void, typename T10 = void>
1992 struct m_Intrinsic_Ty;
1993 template <typename T0> struct m_Intrinsic_Ty<T0> {
1994 using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1995 };
1996 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1997 using Ty =
1998 match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1999 };
2000 template <typename T0, typename T1, typename T2>
2001 struct m_Intrinsic_Ty<T0, T1, T2> {
2002 using Ty =
2003 match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
2004 Argument_match<T2>>;
2005 };
2006 template <typename T0, typename T1, typename T2, typename T3>
2007 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
2008 using Ty =
2009 match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
2010 Argument_match<T3>>;
2011 };
2012
2013 template <typename T0, typename T1, typename T2, typename T3, typename T4>
2014 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> {
2015 using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty,
2016 Argument_match<T4>>;
2017 };
2018
2019 template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5>
2020 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> {
2021 using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty,
2022 Argument_match<T5>>;
2023 };
2024
2025 /// Match intrinsic calls like this:
2026 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
2027 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
2028 return IntrinsicID_match(IntrID);
2029 }
2030
2031 template <Intrinsic::ID IntrID, typename T0>
2032 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
2033 return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
2034 }
2035
2036 template <Intrinsic::ID IntrID, typename T0, typename T1>
2037 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
2038 const T1 &Op1) {
2039 return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
2040 }
2041
2042 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
2043 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
2044 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
2045 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
2046 }
2047
2048 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2049 typename T3>
2050 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
2051 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
2052 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
2053 }
2054
2055 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2056 typename T3, typename T4>
2057 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty
2058 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2059 const T4 &Op4) {
2060 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3),
2061 m_Argument<4>(Op4));
2062 }
2063
2064 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2065 typename T3, typename T4, typename T5>
2066 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty
2067 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2068 const T4 &Op4, const T5 &Op5) {
2069 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4),
2070 m_Argument<5>(Op5));
2071 }
2072
2073 // Helper intrinsic matching specializations.
2074 template <typename Opnd0>
2075 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
2076 return m_Intrinsic<Intrinsic::bitreverse>(Op0);
2077 }
2078
2079 template <typename Opnd0>
2080 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
2081 return m_Intrinsic<Intrinsic::bswap>(Op0);
2082 }
2083
2084 template <typename Opnd0>
2085 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
2086 return m_Intrinsic<Intrinsic::fabs>(Op0);
2087 }
2088
2089 template <typename Opnd0>
2090 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
2091 return m_Intrinsic<Intrinsic::canonicalize>(Op0);
2092 }
2093
2094 template <typename Opnd0, typename Opnd1>
2095 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
2096 const Opnd1 &Op1) {
2097 return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
2098 }
2099
2100 template <typename Opnd0, typename Opnd1>
2101 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
2102 const Opnd1 &Op1) {
2103 return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
2104 }
2105
2106 template <typename Opnd0, typename Opnd1, typename Opnd2>
2107 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2108 m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2109 return m_Intrinsic<Intrinsic::fshl>(Op0, Op1, Op2);
2110 }
2111
2112 template <typename Opnd0, typename Opnd1, typename Opnd2>
2113 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2114 m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2115 return m_Intrinsic<Intrinsic::fshr>(Op0, Op1, Op2);
2116 }
2117
2118 //===----------------------------------------------------------------------===//
2119 // Matchers for two-operands operators with the operators in either order
2120 //
2121
2122 /// Matches a BinaryOperator with LHS and RHS in either order.
2123 template <typename LHS, typename RHS>
2124 inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
2125 return AnyBinaryOp_match<LHS, RHS, true>(L, R);
2126 }
2127
2128 /// Matches an ICmp with a predicate over LHS and RHS in either order.
2129 /// Swaps the predicate if operands are commuted.
2130 template <typename LHS, typename RHS>
2131 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2132 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
2133 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
2134 R);
2135 }
2136
2137 /// Matches a Add with LHS and RHS in either order.
2138 template <typename LHS, typename RHS>
2139 inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
2140 const RHS &R) {
2141 return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
2142 }
2143
2144 /// Matches a Mul with LHS and RHS in either order.
2145 template <typename LHS, typename RHS>
2146 inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
2147 const RHS &R) {
2148 return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
2149 }
2150
2151 /// Matches an And with LHS and RHS in either order.
2152 template <typename LHS, typename RHS>
2153 inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
2154 const RHS &R) {
2155 return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
2156 }
2157
2158 /// Matches an Or with LHS and RHS in either order.
2159 template <typename LHS, typename RHS>
2160 inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
2161 const RHS &R) {
2162 return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2163 }
2164
2165 /// Matches an Xor with LHS and RHS in either order.
2166 template <typename LHS, typename RHS>
2167 inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
2168 const RHS &R) {
2169 return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
2170 }
2171
2172 /// Matches a 'Neg' as 'sub 0, V'.
2173 template <typename ValTy>
2174 inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
2175 m_Neg(const ValTy &V) {
2176 return m_Sub(m_ZeroInt(), V);
2177 }
2178
2179 /// Matches a 'Neg' as 'sub nsw 0, V'.
2180 template <typename ValTy>
2181 inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy,
2182 Instruction::Sub,
2183 OverflowingBinaryOperator::NoSignedWrap>
2184 m_NSWNeg(const ValTy &V) {
2185 return m_NSWSub(m_ZeroInt(), V);
2186 }
2187
2188 /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
2189 template <typename ValTy>
2190 inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true>
2191 m_Not(const ValTy &V) {
2192 return m_c_Xor(V, m_AllOnes());
2193 }
2194
2195 /// Matches an SMin with LHS and RHS in either order.
2196 template <typename LHS, typename RHS>
2197 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
2198 m_c_SMin(const LHS &L, const RHS &R) {
2199 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
2200 }
2201 /// Matches an SMax with LHS and RHS in either order.
2202 template <typename LHS, typename RHS>
2203 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
2204 m_c_SMax(const LHS &L, const RHS &R) {
2205 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
2206 }
2207 /// Matches a UMin with LHS and RHS in either order.
2208 template <typename LHS, typename RHS>
2209 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
2210 m_c_UMin(const LHS &L, const RHS &R) {
2211 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
2212 }
2213 /// Matches a UMax with LHS and RHS in either order.
2214 template <typename LHS, typename RHS>
2215 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
2216 m_c_UMax(const LHS &L, const RHS &R) {
2217 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
2218 }
2219
2220 template <typename LHS, typename RHS>
2221 inline match_combine_or<
2222 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>,
2223 MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>,
2224 match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>,
2225 MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>>
2226 m_c_MaxOrMin(const LHS &L, const RHS &R) {
2227 return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)),
2228 m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R)));
2229 }
2230
2231 /// Matches FAdd with LHS and RHS in either order.
2232 template <typename LHS, typename RHS>
2233 inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
2234 m_c_FAdd(const LHS &L, const RHS &R) {
2235 return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
2236 }
2237
2238 /// Matches FMul with LHS and RHS in either order.
2239 template <typename LHS, typename RHS>
2240 inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
2241 m_c_FMul(const LHS &L, const RHS &R) {
2242 return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
2243 }
2244
2245 template <typename Opnd_t> struct Signum_match {
2246 Opnd_t Val;
2247 Signum_match(const Opnd_t &V) : Val(V) {}
2248
2249 template <typename OpTy> bool match(OpTy *V) {
2250 unsigned TypeSize = V->getType()->getScalarSizeInBits();
2251 if (TypeSize == 0)
2252 return false;
2253
2254 unsigned ShiftWidth = TypeSize - 1;
2255 Value *OpL = nullptr, *OpR = nullptr;
2256
2257 // This is the representation of signum we match:
2258 //
2259 // signum(x) == (x >> 63) | (-x >>u 63)
2260 //
2261 // An i1 value is its own signum, so it's correct to match
2262 //
2263 // signum(x) == (x >> 0) | (-x >>u 0)
2264 //
2265 // for i1 values.
2266
2267 auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
2268 auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
2269 auto Signum = m_Or(LHS, RHS);
2270
2271 return Signum.match(V) && OpL == OpR && Val.match(OpL);
2272 }
2273 };
2274
2275 /// Matches a signum pattern.
2276 ///
2277 /// signum(x) =
2278 /// x > 0 -> 1
2279 /// x == 0 -> 0
2280 /// x < 0 -> -1
2281 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
2282 return Signum_match<Val_t>(V);
2283 }
2284
2285 template <int Ind, typename Opnd_t> struct ExtractValue_match {
2286 Opnd_t Val;
2287 ExtractValue_match(const Opnd_t &V) : Val(V) {}
2288
2289 template <typename OpTy> bool match(OpTy *V) {
2290 if (auto *I = dyn_cast<ExtractValueInst>(V))
2291 return I->getNumIndices() == 1 && I->getIndices()[0] == Ind &&
2292 Val.match(I->getAggregateOperand());
2293 return false;
2294 }
2295 };
2296
2297 /// Match a single index ExtractValue instruction.
2298 /// For example m_ExtractValue<1>(...)
2299 template <int Ind, typename Val_t>
2300 inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) {
2301 return ExtractValue_match<Ind, Val_t>(V);
2302 }
2303
2304 /// Matcher for a single index InsertValue instruction.
2305 template <int Ind, typename T0, typename T1> struct InsertValue_match {
2306 T0 Op0;
2307 T1 Op1;
2308
2309 InsertValue_match(const T0 &Op0, const T1 &Op1) : Op0(Op0), Op1(Op1) {}
2310
2311 template <typename OpTy> bool match(OpTy *V) {
2312 if (auto *I = dyn_cast<InsertValueInst>(V)) {
2313 return Op0.match(I->getOperand(0)) && Op1.match(I->getOperand(1)) &&
2314 I->getNumIndices() == 1 && Ind == I->getIndices()[0];
2315 }
2316 return false;
2317 }
2318 };
2319
2320 /// Matches a single index InsertValue instruction.
2321 template <int Ind, typename Val_t, typename Elt_t>
2322 inline InsertValue_match<Ind, Val_t, Elt_t> m_InsertValue(const Val_t &Val,
2323 const Elt_t &Elt) {
2324 return InsertValue_match<Ind, Val_t, Elt_t>(Val, Elt);
2325 }
2326
2327 /// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or
2328 /// the constant expression
2329 /// `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>`
2330 /// under the right conditions determined by DataLayout.
2331 struct VScaleVal_match {
2332 private:
2333 template <typename Base, typename Offset>
2334 inline BinaryOp_match<Base, Offset, Instruction::GetElementPtr>
2335 m_OffsetGep(const Base &B, const Offset &O) {
2336 return BinaryOp_match<Base, Offset, Instruction::GetElementPtr>(B, O);
2337 }
2338
2339 public:
2340 const DataLayout &DL;
2341 VScaleVal_match(const DataLayout &DL) : DL(DL) {}
2342
2343 template <typename ITy> bool match(ITy *V) {
2344 if (m_Intrinsic<Intrinsic::vscale>().match(V))
2345 return true;
2346
2347 if (m_PtrToInt(m_OffsetGep(m_Zero(), m_SpecificInt(1))).match(V)) {
2348 Type *PtrTy = cast<Operator>(V)->getOperand(0)->getType();
2349 auto *DerefTy = PtrTy->getPointerElementType();
2350 if (isa<ScalableVectorType>(DerefTy) &&
2351 DL.getTypeAllocSizeInBits(DerefTy).getKnownMinSize() == 8)
2352 return true;
2353 }
2354
2355 return false;
2356 }
2357 };
2358
2359 inline VScaleVal_match m_VScale(const DataLayout &DL) {
2360 return VScaleVal_match(DL);
2361 }
2362
2363 } // end namespace PatternMatch
2364 } // end namespace llvm
2365
2366 #endif // LLVM_IR_PATTERNMATCH_H
2367