]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/PatternMatch.h
Merge ^/head r318380 through r318559.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / IR / PatternMatch.h
1 //===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides a simple and efficient mechanism for performing general
11 // tree-based pattern matches on the LLVM IR.  The power of these routines is
12 // that it allows you to write concise patterns that are expressive and easy to
13 // understand.  The other major advantage of this is that it allows you to
14 // trivially capture/bind elements in the pattern to variables.  For example,
15 // you can do something like this:
16 //
17 //  Value *Exp = ...
18 //  Value *X, *Y;  ConstantInt *C1, *C2;      // (X & C1) | (Y & C2)
19 //  if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
20 //                      m_And(m_Value(Y), m_ConstantInt(C2))))) {
21 //    ... Pattern is matched and variables are bound ...
22 //  }
23 //
24 // This is primarily useful to things like the instruction combiner, but can
25 // also be useful for static analysis tools or code generators.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #ifndef LLVM_IR_PATTERNMATCH_H
30 #define LLVM_IR_PATTERNMATCH_H
31
32 #include "llvm/ADT/APFloat.h"
33 #include "llvm/ADT/APInt.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
44 #include <cstdint>
45
46 namespace llvm {
47 namespace PatternMatch {
48
49 template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50   return const_cast<Pattern &>(P).match(V);
51 }
52
53 template <typename SubPattern_t> struct OneUse_match {
54   SubPattern_t SubPattern;
55
56   OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
57
58   template <typename OpTy> bool match(OpTy *V) {
59     return V->hasOneUse() && SubPattern.match(V);
60   }
61 };
62
63 template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
64   return SubPattern;
65 }
66
67 template <typename Class> struct class_match {
68   template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
69 };
70
71 /// \brief Match an arbitrary value and ignore it.
72 inline class_match<Value> m_Value() { return class_match<Value>(); }
73
74 /// \brief Match an arbitrary binary operation and ignore it.
75 inline class_match<BinaryOperator> m_BinOp() {
76   return class_match<BinaryOperator>();
77 }
78
79 /// \brief Matches any compare instruction and ignore it.
80 inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
81
82 /// \brief Match an arbitrary ConstantInt and ignore it.
83 inline class_match<ConstantInt> m_ConstantInt() {
84   return class_match<ConstantInt>();
85 }
86
87 /// \brief Match an arbitrary undef constant.
88 inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
89
90 /// \brief Match an arbitrary Constant and ignore it.
91 inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
92
93 /// Matching combinators
94 template <typename LTy, typename RTy> struct match_combine_or {
95   LTy L;
96   RTy R;
97
98   match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
99
100   template <typename ITy> bool match(ITy *V) {
101     if (L.match(V))
102       return true;
103     if (R.match(V))
104       return true;
105     return false;
106   }
107 };
108
109 template <typename LTy, typename RTy> struct match_combine_and {
110   LTy L;
111   RTy R;
112
113   match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
114
115   template <typename ITy> bool match(ITy *V) {
116     if (L.match(V))
117       if (R.match(V))
118         return true;
119     return false;
120   }
121 };
122
123 /// Combine two pattern matchers matching L || R
124 template <typename LTy, typename RTy>
125 inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
126   return match_combine_or<LTy, RTy>(L, R);
127 }
128
129 /// Combine two pattern matchers matching L && R
130 template <typename LTy, typename RTy>
131 inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
132   return match_combine_and<LTy, RTy>(L, R);
133 }
134
135 struct match_zero {
136   template <typename ITy> bool match(ITy *V) {
137     if (const auto *C = dyn_cast<Constant>(V))
138       return C->isNullValue();
139     return false;
140   }
141 };
142
143 /// \brief Match an arbitrary zero/null constant.  This includes
144 /// zero_initializer for vectors and ConstantPointerNull for pointers.
145 inline match_zero m_Zero() { return match_zero(); }
146
147 struct match_neg_zero {
148   template <typename ITy> bool match(ITy *V) {
149     if (const auto *C = dyn_cast<Constant>(V))
150       return C->isNegativeZeroValue();
151     return false;
152   }
153 };
154
155 /// \brief Match an arbitrary zero/null constant.  This includes
156 /// zero_initializer for vectors and ConstantPointerNull for pointers. For
157 /// floating point constants, this will match negative zero but not positive
158 /// zero
159 inline match_neg_zero m_NegZero() { return match_neg_zero(); }
160
161 /// \brief - Match an arbitrary zero/null constant.  This includes
162 /// zero_initializer for vectors and ConstantPointerNull for pointers. For
163 /// floating point constants, this will match negative zero and positive zero
164 inline match_combine_or<match_zero, match_neg_zero> m_AnyZero() {
165   return m_CombineOr(m_Zero(), m_NegZero());
166 }
167
168 struct match_nan {
169   template <typename ITy> bool match(ITy *V) {
170     if (const auto *C = dyn_cast<ConstantFP>(V)) {
171       const APFloat &APF = C->getValueAPF();
172       return APF.isNaN();
173     }
174     return false;
175   }
176 };
177
178 /// Match an arbitrary NaN constant. This includes quiet and signalling nans.
179 inline match_nan m_NaN() { return match_nan(); }
180
181 struct apint_match {
182   const APInt *&Res;
183
184   apint_match(const APInt *&R) : Res(R) {}
185
186   template <typename ITy> bool match(ITy *V) {
187     if (auto *CI = dyn_cast<ConstantInt>(V)) {
188       Res = &CI->getValue();
189       return true;
190     }
191     if (V->getType()->isVectorTy())
192       if (const auto *C = dyn_cast<Constant>(V))
193         if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
194           Res = &CI->getValue();
195           return true;
196         }
197     return false;
198   }
199 };
200
201 /// \brief Match a ConstantInt or splatted ConstantVector, binding the
202 /// specified pointer to the contained APInt.
203 inline apint_match m_APInt(const APInt *&Res) { return Res; }
204
205 template <int64_t Val> struct constantint_match {
206   template <typename ITy> bool match(ITy *V) {
207     if (const auto *CI = dyn_cast<ConstantInt>(V)) {
208       const APInt &CIV = CI->getValue();
209       if (Val >= 0)
210         return CIV == static_cast<uint64_t>(Val);
211       // If Val is negative, and CI is shorter than it, truncate to the right
212       // number of bits.  If it is larger, then we have to sign extend.  Just
213       // compare their negated values.
214       return -CIV == -Val;
215     }
216     return false;
217   }
218 };
219
220 /// \brief Match a ConstantInt with a specific value.
221 template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
222   return constantint_match<Val>();
223 }
224
225 /// \brief This helper class is used to match scalar and vector constants that
226 /// satisfy a specified predicate.
227 template <typename Predicate> struct cst_pred_ty : public Predicate {
228   template <typename ITy> bool match(ITy *V) {
229     if (const auto *CI = dyn_cast<ConstantInt>(V))
230       return this->isValue(CI->getValue());
231     if (V->getType()->isVectorTy())
232       if (const auto *C = dyn_cast<Constant>(V))
233         if (const auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
234           return this->isValue(CI->getValue());
235     return false;
236   }
237 };
238
239 /// \brief This helper class is used to match scalar and vector constants that
240 /// satisfy a specified predicate, and bind them to an APInt.
241 template <typename Predicate> struct api_pred_ty : public Predicate {
242   const APInt *&Res;
243
244   api_pred_ty(const APInt *&R) : Res(R) {}
245
246   template <typename ITy> bool match(ITy *V) {
247     if (const auto *CI = dyn_cast<ConstantInt>(V))
248       if (this->isValue(CI->getValue())) {
249         Res = &CI->getValue();
250         return true;
251       }
252     if (V->getType()->isVectorTy())
253       if (const auto *C = dyn_cast<Constant>(V))
254         if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
255           if (this->isValue(CI->getValue())) {
256             Res = &CI->getValue();
257             return true;
258           }
259
260     return false;
261   }
262 };
263
264 struct is_one {
265   bool isValue(const APInt &C) { return C == 1; }
266 };
267
268 /// \brief Match an integer 1 or a vector with all elements equal to 1.
269 inline cst_pred_ty<is_one> m_One() { return cst_pred_ty<is_one>(); }
270 inline api_pred_ty<is_one> m_One(const APInt *&V) { return V; }
271
272 struct is_all_ones {
273   bool isValue(const APInt &C) { return C.isAllOnesValue(); }
274 };
275
276 /// \brief Match an integer or vector with all bits set to true.
277 inline cst_pred_ty<is_all_ones> m_AllOnes() {
278   return cst_pred_ty<is_all_ones>();
279 }
280 inline api_pred_ty<is_all_ones> m_AllOnes(const APInt *&V) { return V; }
281
282 struct is_sign_mask {
283   bool isValue(const APInt &C) { return C.isSignMask(); }
284 };
285
286 /// \brief Match an integer or vector with only the sign bit(s) set.
287 inline cst_pred_ty<is_sign_mask> m_SignMask() {
288   return cst_pred_ty<is_sign_mask>();
289 }
290 inline api_pred_ty<is_sign_mask> m_SignMask(const APInt *&V) { return V; }
291
292 struct is_power2 {
293   bool isValue(const APInt &C) { return C.isPowerOf2(); }
294 };
295
296 /// \brief Match an integer or vector power of 2.
297 inline cst_pred_ty<is_power2> m_Power2() { return cst_pred_ty<is_power2>(); }
298 inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { return V; }
299
300 struct is_maxsignedvalue {
301   bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
302 };
303
304 inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() { return cst_pred_ty<is_maxsignedvalue>(); }
305 inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) { return V; }
306
307 template <typename Class> struct bind_ty {
308   Class *&VR;
309
310   bind_ty(Class *&V) : VR(V) {}
311
312   template <typename ITy> bool match(ITy *V) {
313     if (auto *CV = dyn_cast<Class>(V)) {
314       VR = CV;
315       return true;
316     }
317     return false;
318   }
319 };
320
321 /// \brief Match a value, capturing it if we match.
322 inline bind_ty<Value> m_Value(Value *&V) { return V; }
323 inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
324
325 /// \brief Match an instruction, capturing it if we match.
326 inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
327 /// \brief Match a binary operator, capturing it if we match.
328 inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
329
330 /// \brief Match a ConstantInt, capturing the value if we match.
331 inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
332
333 /// \brief Match a Constant, capturing the value if we match.
334 inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
335
336 /// \brief Match a ConstantFP, capturing the value if we match.
337 inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
338
339 /// \brief Match a specified Value*.
340 struct specificval_ty {
341   const Value *Val;
342
343   specificval_ty(const Value *V) : Val(V) {}
344
345   template <typename ITy> bool match(ITy *V) { return V == Val; }
346 };
347
348 /// \brief Match if we have a specific specified value.
349 inline specificval_ty m_Specific(const Value *V) { return V; }
350
351 /// \brief Match a specified floating point value or vector of all elements of
352 /// that value.
353 struct specific_fpval {
354   double Val;
355
356   specific_fpval(double V) : Val(V) {}
357
358   template <typename ITy> bool match(ITy *V) {
359     if (const auto *CFP = dyn_cast<ConstantFP>(V))
360       return CFP->isExactlyValue(Val);
361     if (V->getType()->isVectorTy())
362       if (const auto *C = dyn_cast<Constant>(V))
363         if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
364           return CFP->isExactlyValue(Val);
365     return false;
366   }
367 };
368
369 /// \brief Match a specific floating point value or vector with all elements
370 /// equal to the value.
371 inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
372
373 /// \brief Match a float 1.0 or vector with all elements equal to 1.0.
374 inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
375
376 struct bind_const_intval_ty {
377   uint64_t &VR;
378
379   bind_const_intval_ty(uint64_t &V) : VR(V) {}
380
381   template <typename ITy> bool match(ITy *V) {
382     if (const auto *CV = dyn_cast<ConstantInt>(V))
383       if (CV->getBitWidth() <= 64) {
384         VR = CV->getZExtValue();
385         return true;
386       }
387     return false;
388   }
389 };
390
391 /// \brief Match a specified integer value or vector of all elements of that
392 // value.
393 struct specific_intval {
394   uint64_t Val;
395
396   specific_intval(uint64_t V) : Val(V) {}
397
398   template <typename ITy> bool match(ITy *V) {
399     const auto *CI = dyn_cast<ConstantInt>(V);
400     if (!CI && V->getType()->isVectorTy())
401       if (const auto *C = dyn_cast<Constant>(V))
402         CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue());
403
404     if (CI && CI->getBitWidth() <= 64)
405       return CI->getZExtValue() == Val;
406
407     return false;
408   }
409 };
410
411 /// \brief Match a specific integer value or vector with all elements equal to
412 /// the value.
413 inline specific_intval m_SpecificInt(uint64_t V) { return specific_intval(V); }
414
415 /// \brief Match a ConstantInt and bind to its value.  This does not match
416 /// ConstantInts wider than 64-bits.
417 inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
418
419 //===----------------------------------------------------------------------===//
420 // Matcher for any binary operator.
421 //
422 template <typename LHS_t, typename RHS_t> struct AnyBinaryOp_match {
423   LHS_t L;
424   RHS_t R;
425
426   AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
427
428   template <typename OpTy> bool match(OpTy *V) {
429     if (auto *I = dyn_cast<BinaryOperator>(V))
430       return L.match(I->getOperand(0)) && R.match(I->getOperand(1));
431     return false;
432   }
433 };
434
435 template <typename LHS, typename RHS>
436 inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
437   return AnyBinaryOp_match<LHS, RHS>(L, R);
438 }
439
440 //===----------------------------------------------------------------------===//
441 // Matchers for specific binary operators.
442 //
443
444 template <typename LHS_t, typename RHS_t, unsigned Opcode>
445 struct BinaryOp_match {
446   LHS_t L;
447   RHS_t R;
448
449   BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
450
451   template <typename OpTy> bool match(OpTy *V) {
452     if (V->getValueID() == Value::InstructionVal + Opcode) {
453       auto *I = cast<BinaryOperator>(V);
454       return L.match(I->getOperand(0)) && R.match(I->getOperand(1));
455     }
456     if (auto *CE = dyn_cast<ConstantExpr>(V))
457       return CE->getOpcode() == Opcode && L.match(CE->getOperand(0)) &&
458              R.match(CE->getOperand(1));
459     return false;
460   }
461 };
462
463 template <typename LHS, typename RHS>
464 inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
465                                                         const RHS &R) {
466   return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
467 }
468
469 template <typename LHS, typename RHS>
470 inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
471                                                           const RHS &R) {
472   return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
473 }
474
475 template <typename LHS, typename RHS>
476 inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
477                                                         const RHS &R) {
478   return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
479 }
480
481 template <typename LHS, typename RHS>
482 inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
483                                                           const RHS &R) {
484   return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
485 }
486
487 template <typename LHS, typename RHS>
488 inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
489                                                         const RHS &R) {
490   return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
491 }
492
493 template <typename LHS, typename RHS>
494 inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
495                                                           const RHS &R) {
496   return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
497 }
498
499 template <typename LHS, typename RHS>
500 inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
501                                                           const RHS &R) {
502   return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
503 }
504
505 template <typename LHS, typename RHS>
506 inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
507                                                           const RHS &R) {
508   return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
509 }
510
511 template <typename LHS, typename RHS>
512 inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
513                                                           const RHS &R) {
514   return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
515 }
516
517 template <typename LHS, typename RHS>
518 inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
519                                                           const RHS &R) {
520   return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
521 }
522
523 template <typename LHS, typename RHS>
524 inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
525                                                           const RHS &R) {
526   return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
527 }
528
529 template <typename LHS, typename RHS>
530 inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
531                                                           const RHS &R) {
532   return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
533 }
534
535 template <typename LHS, typename RHS>
536 inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
537                                                         const RHS &R) {
538   return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
539 }
540
541 template <typename LHS, typename RHS>
542 inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
543                                                       const RHS &R) {
544   return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
545 }
546
547 template <typename LHS, typename RHS>
548 inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
549                                                         const RHS &R) {
550   return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
551 }
552
553 template <typename LHS, typename RHS>
554 inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
555                                                         const RHS &R) {
556   return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
557 }
558
559 template <typename LHS, typename RHS>
560 inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
561                                                           const RHS &R) {
562   return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
563 }
564
565 template <typename LHS, typename RHS>
566 inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
567                                                           const RHS &R) {
568   return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
569 }
570
571 template <typename LHS_t, typename RHS_t, unsigned Opcode,
572           unsigned WrapFlags = 0>
573 struct OverflowingBinaryOp_match {
574   LHS_t L;
575   RHS_t R;
576
577   OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
578       : L(LHS), R(RHS) {}
579
580   template <typename OpTy> bool match(OpTy *V) {
581     if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
582       if (Op->getOpcode() != Opcode)
583         return false;
584       if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap &&
585           !Op->hasNoUnsignedWrap())
586         return false;
587       if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap &&
588           !Op->hasNoSignedWrap())
589         return false;
590       return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
591     }
592     return false;
593   }
594 };
595
596 template <typename LHS, typename RHS>
597 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
598                                  OverflowingBinaryOperator::NoSignedWrap>
599 m_NSWAdd(const LHS &L, const RHS &R) {
600   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
601                                    OverflowingBinaryOperator::NoSignedWrap>(
602       L, R);
603 }
604 template <typename LHS, typename RHS>
605 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
606                                  OverflowingBinaryOperator::NoSignedWrap>
607 m_NSWSub(const LHS &L, const RHS &R) {
608   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
609                                    OverflowingBinaryOperator::NoSignedWrap>(
610       L, R);
611 }
612 template <typename LHS, typename RHS>
613 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
614                                  OverflowingBinaryOperator::NoSignedWrap>
615 m_NSWMul(const LHS &L, const RHS &R) {
616   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
617                                    OverflowingBinaryOperator::NoSignedWrap>(
618       L, R);
619 }
620 template <typename LHS, typename RHS>
621 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
622                                  OverflowingBinaryOperator::NoSignedWrap>
623 m_NSWShl(const LHS &L, const RHS &R) {
624   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
625                                    OverflowingBinaryOperator::NoSignedWrap>(
626       L, R);
627 }
628
629 template <typename LHS, typename RHS>
630 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
631                                  OverflowingBinaryOperator::NoUnsignedWrap>
632 m_NUWAdd(const LHS &L, const RHS &R) {
633   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
634                                    OverflowingBinaryOperator::NoUnsignedWrap>(
635       L, R);
636 }
637 template <typename LHS, typename RHS>
638 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
639                                  OverflowingBinaryOperator::NoUnsignedWrap>
640 m_NUWSub(const LHS &L, const RHS &R) {
641   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
642                                    OverflowingBinaryOperator::NoUnsignedWrap>(
643       L, R);
644 }
645 template <typename LHS, typename RHS>
646 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
647                                  OverflowingBinaryOperator::NoUnsignedWrap>
648 m_NUWMul(const LHS &L, const RHS &R) {
649   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
650                                    OverflowingBinaryOperator::NoUnsignedWrap>(
651       L, R);
652 }
653 template <typename LHS, typename RHS>
654 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
655                                  OverflowingBinaryOperator::NoUnsignedWrap>
656 m_NUWShl(const LHS &L, const RHS &R) {
657   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
658                                    OverflowingBinaryOperator::NoUnsignedWrap>(
659       L, R);
660 }
661
662 //===----------------------------------------------------------------------===//
663 // Class that matches two different binary ops.
664 //
665 template <typename LHS_t, typename RHS_t, unsigned Opc1, unsigned Opc2>
666 struct BinOp2_match {
667   LHS_t L;
668   RHS_t R;
669
670   BinOp2_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
671
672   template <typename OpTy> bool match(OpTy *V) {
673     if (V->getValueID() == Value::InstructionVal + Opc1 ||
674         V->getValueID() == Value::InstructionVal + Opc2) {
675       auto *I = cast<BinaryOperator>(V);
676       return L.match(I->getOperand(0)) && R.match(I->getOperand(1));
677     }
678     if (auto *CE = dyn_cast<ConstantExpr>(V))
679       return (CE->getOpcode() == Opc1 || CE->getOpcode() == Opc2) &&
680              L.match(CE->getOperand(0)) && R.match(CE->getOperand(1));
681     return false;
682   }
683 };
684
685 /// \brief Matches LShr or AShr.
686 template <typename LHS, typename RHS>
687 inline BinOp2_match<LHS, RHS, Instruction::LShr, Instruction::AShr>
688 m_Shr(const LHS &L, const RHS &R) {
689   return BinOp2_match<LHS, RHS, Instruction::LShr, Instruction::AShr>(L, R);
690 }
691
692 /// \brief Matches LShr or Shl.
693 template <typename LHS, typename RHS>
694 inline BinOp2_match<LHS, RHS, Instruction::LShr, Instruction::Shl>
695 m_LogicalShift(const LHS &L, const RHS &R) {
696   return BinOp2_match<LHS, RHS, Instruction::LShr, Instruction::Shl>(L, R);
697 }
698
699 /// \brief Matches UDiv and SDiv.
700 template <typename LHS, typename RHS>
701 inline BinOp2_match<LHS, RHS, Instruction::SDiv, Instruction::UDiv>
702 m_IDiv(const LHS &L, const RHS &R) {
703   return BinOp2_match<LHS, RHS, Instruction::SDiv, Instruction::UDiv>(L, R);
704 }
705
706 //===----------------------------------------------------------------------===//
707 // Class that matches exact binary ops.
708 //
709 template <typename SubPattern_t> struct Exact_match {
710   SubPattern_t SubPattern;
711
712   Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
713
714   template <typename OpTy> bool match(OpTy *V) {
715     if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
716       return PEO->isExact() && SubPattern.match(V);
717     return false;
718   }
719 };
720
721 template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
722   return SubPattern;
723 }
724
725 //===----------------------------------------------------------------------===//
726 // Matchers for CmpInst classes
727 //
728
729 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy>
730 struct CmpClass_match {
731   PredicateTy &Predicate;
732   LHS_t L;
733   RHS_t R;
734
735   CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
736       : Predicate(Pred), L(LHS), R(RHS) {}
737
738   template <typename OpTy> bool match(OpTy *V) {
739     if (auto *I = dyn_cast<Class>(V))
740       if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
741         Predicate = I->getPredicate();
742         return true;
743       }
744     return false;
745   }
746 };
747
748 template <typename LHS, typename RHS>
749 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
750 m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
751   return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
752 }
753
754 template <typename LHS, typename RHS>
755 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
756 m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
757   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
758 }
759
760 template <typename LHS, typename RHS>
761 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
762 m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
763   return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
764 }
765
766 //===----------------------------------------------------------------------===//
767 // Matchers for SelectInst classes
768 //
769
770 template <typename Cond_t, typename LHS_t, typename RHS_t>
771 struct SelectClass_match {
772   Cond_t C;
773   LHS_t L;
774   RHS_t R;
775
776   SelectClass_match(const Cond_t &Cond, const LHS_t &LHS, const RHS_t &RHS)
777       : C(Cond), L(LHS), R(RHS) {}
778
779   template <typename OpTy> bool match(OpTy *V) {
780     if (auto *I = dyn_cast<SelectInst>(V))
781       return C.match(I->getOperand(0)) && L.match(I->getOperand(1)) &&
782              R.match(I->getOperand(2));
783     return false;
784   }
785 };
786
787 template <typename Cond, typename LHS, typename RHS>
788 inline SelectClass_match<Cond, LHS, RHS> m_Select(const Cond &C, const LHS &L,
789                                                   const RHS &R) {
790   return SelectClass_match<Cond, LHS, RHS>(C, L, R);
791 }
792
793 /// \brief This matches a select of two constants, e.g.:
794 /// m_SelectCst<-1, 0>(m_Value(V))
795 template <int64_t L, int64_t R, typename Cond>
796 inline SelectClass_match<Cond, constantint_match<L>, constantint_match<R>>
797 m_SelectCst(const Cond &C) {
798   return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
799 }
800
801 //===----------------------------------------------------------------------===//
802 // Matchers for CastInst classes
803 //
804
805 template <typename Op_t, unsigned Opcode> struct CastClass_match {
806   Op_t Op;
807
808   CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
809
810   template <typename OpTy> bool match(OpTy *V) {
811     if (auto *O = dyn_cast<Operator>(V))
812       return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
813     return false;
814   }
815 };
816
817 /// \brief Matches BitCast.
818 template <typename OpTy>
819 inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
820   return CastClass_match<OpTy, Instruction::BitCast>(Op);
821 }
822
823 /// \brief Matches PtrToInt.
824 template <typename OpTy>
825 inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
826   return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
827 }
828
829 /// \brief Matches Trunc.
830 template <typename OpTy>
831 inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
832   return CastClass_match<OpTy, Instruction::Trunc>(Op);
833 }
834
835 /// \brief Matches SExt.
836 template <typename OpTy>
837 inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
838   return CastClass_match<OpTy, Instruction::SExt>(Op);
839 }
840
841 /// \brief Matches ZExt.
842 template <typename OpTy>
843 inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
844   return CastClass_match<OpTy, Instruction::ZExt>(Op);
845 }
846
847 template <typename OpTy>
848 inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
849                         CastClass_match<OpTy, Instruction::SExt>>
850 m_ZExtOrSExt(const OpTy &Op) {
851   return m_CombineOr(m_ZExt(Op), m_SExt(Op));
852 }
853
854 /// \brief Matches UIToFP.
855 template <typename OpTy>
856 inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
857   return CastClass_match<OpTy, Instruction::UIToFP>(Op);
858 }
859
860 /// \brief Matches SIToFP.
861 template <typename OpTy>
862 inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
863   return CastClass_match<OpTy, Instruction::SIToFP>(Op);
864 }
865
866 /// \brief Matches FPTrunc
867 template <typename OpTy>
868 inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
869   return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
870 }
871
872 /// \brief Matches FPExt
873 template <typename OpTy>
874 inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
875   return CastClass_match<OpTy, Instruction::FPExt>(Op);
876 }
877
878 //===----------------------------------------------------------------------===//
879 // Matchers for unary operators
880 //
881
882 template <typename LHS_t> struct not_match {
883   LHS_t L;
884
885   not_match(const LHS_t &LHS) : L(LHS) {}
886
887   template <typename OpTy> bool match(OpTy *V) {
888     if (auto *O = dyn_cast<Operator>(V))
889       if (O->getOpcode() == Instruction::Xor)
890         return matchIfNot(O->getOperand(0), O->getOperand(1));
891     return false;
892   }
893
894 private:
895   bool matchIfNot(Value *LHS, Value *RHS) {
896     return (isa<ConstantInt>(RHS) || isa<ConstantDataVector>(RHS) ||
897             // FIXME: Remove CV.
898             isa<ConstantVector>(RHS)) &&
899            cast<Constant>(RHS)->isAllOnesValue() && L.match(LHS);
900   }
901 };
902
903 template <typename LHS> inline not_match<LHS> m_Not(const LHS &L) { return L; }
904
905 template <typename LHS_t> struct neg_match {
906   LHS_t L;
907
908   neg_match(const LHS_t &LHS) : L(LHS) {}
909
910   template <typename OpTy> bool match(OpTy *V) {
911     if (auto *O = dyn_cast<Operator>(V))
912       if (O->getOpcode() == Instruction::Sub)
913         return matchIfNeg(O->getOperand(0), O->getOperand(1));
914     return false;
915   }
916
917 private:
918   bool matchIfNeg(Value *LHS, Value *RHS) {
919     return ((isa<ConstantInt>(LHS) && cast<ConstantInt>(LHS)->isZero()) ||
920             isa<ConstantAggregateZero>(LHS)) &&
921            L.match(RHS);
922   }
923 };
924
925 /// \brief Match an integer negate.
926 template <typename LHS> inline neg_match<LHS> m_Neg(const LHS &L) { return L; }
927
928 template <typename LHS_t> struct fneg_match {
929   LHS_t L;
930
931   fneg_match(const LHS_t &LHS) : L(LHS) {}
932
933   template <typename OpTy> bool match(OpTy *V) {
934     if (auto *O = dyn_cast<Operator>(V))
935       if (O->getOpcode() == Instruction::FSub)
936         return matchIfFNeg(O->getOperand(0), O->getOperand(1));
937     return false;
938   }
939
940 private:
941   bool matchIfFNeg(Value *LHS, Value *RHS) {
942     if (const auto *C = dyn_cast<ConstantFP>(LHS))
943       return C->isNegativeZeroValue() && L.match(RHS);
944     return false;
945   }
946 };
947
948 /// \brief Match a floating point negate.
949 template <typename LHS> inline fneg_match<LHS> m_FNeg(const LHS &L) {
950   return L;
951 }
952
953 //===----------------------------------------------------------------------===//
954 // Matchers for control flow.
955 //
956
957 struct br_match {
958   BasicBlock *&Succ;
959
960   br_match(BasicBlock *&Succ) : Succ(Succ) {}
961
962   template <typename OpTy> bool match(OpTy *V) {
963     if (auto *BI = dyn_cast<BranchInst>(V))
964       if (BI->isUnconditional()) {
965         Succ = BI->getSuccessor(0);
966         return true;
967       }
968     return false;
969   }
970 };
971
972 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
973
974 template <typename Cond_t> struct brc_match {
975   Cond_t Cond;
976   BasicBlock *&T, *&F;
977
978   brc_match(const Cond_t &C, BasicBlock *&t, BasicBlock *&f)
979       : Cond(C), T(t), F(f) {}
980
981   template <typename OpTy> bool match(OpTy *V) {
982     if (auto *BI = dyn_cast<BranchInst>(V))
983       if (BI->isConditional() && Cond.match(BI->getCondition())) {
984         T = BI->getSuccessor(0);
985         F = BI->getSuccessor(1);
986         return true;
987       }
988     return false;
989   }
990 };
991
992 template <typename Cond_t>
993 inline brc_match<Cond_t> m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
994   return brc_match<Cond_t>(C, T, F);
995 }
996
997 //===----------------------------------------------------------------------===//
998 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
999 //
1000
1001 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t>
1002 struct MaxMin_match {
1003   LHS_t L;
1004   RHS_t R;
1005
1006   MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1007
1008   template <typename OpTy> bool match(OpTy *V) {
1009     // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1010     auto *SI = dyn_cast<SelectInst>(V);
1011     if (!SI)
1012       return false;
1013     auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1014     if (!Cmp)
1015       return false;
1016     // At this point we have a select conditioned on a comparison.  Check that
1017     // it is the values returned by the select that are being compared.
1018     Value *TrueVal = SI->getTrueValue();
1019     Value *FalseVal = SI->getFalseValue();
1020     Value *LHS = Cmp->getOperand(0);
1021     Value *RHS = Cmp->getOperand(1);
1022     if ((TrueVal != LHS || FalseVal != RHS) &&
1023         (TrueVal != RHS || FalseVal != LHS))
1024       return false;
1025     typename CmpInst_t::Predicate Pred =
1026         LHS == TrueVal ? Cmp->getPredicate() : Cmp->getSwappedPredicate();
1027     // Does "(x pred y) ? x : y" represent the desired max/min operation?
1028     if (!Pred_t::match(Pred))
1029       return false;
1030     // It does!  Bind the operands.
1031     return L.match(LHS) && R.match(RHS);
1032   }
1033 };
1034
1035 /// \brief Helper class for identifying signed max predicates.
1036 struct smax_pred_ty {
1037   static bool match(ICmpInst::Predicate Pred) {
1038     return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1039   }
1040 };
1041
1042 /// \brief Helper class for identifying signed min predicates.
1043 struct smin_pred_ty {
1044   static bool match(ICmpInst::Predicate Pred) {
1045     return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1046   }
1047 };
1048
1049 /// \brief Helper class for identifying unsigned max predicates.
1050 struct umax_pred_ty {
1051   static bool match(ICmpInst::Predicate Pred) {
1052     return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1053   }
1054 };
1055
1056 /// \brief Helper class for identifying unsigned min predicates.
1057 struct umin_pred_ty {
1058   static bool match(ICmpInst::Predicate Pred) {
1059     return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1060   }
1061 };
1062
1063 /// \brief Helper class for identifying ordered max predicates.
1064 struct ofmax_pred_ty {
1065   static bool match(FCmpInst::Predicate Pred) {
1066     return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1067   }
1068 };
1069
1070 /// \brief Helper class for identifying ordered min predicates.
1071 struct ofmin_pred_ty {
1072   static bool match(FCmpInst::Predicate Pred) {
1073     return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1074   }
1075 };
1076
1077 /// \brief Helper class for identifying unordered max predicates.
1078 struct ufmax_pred_ty {
1079   static bool match(FCmpInst::Predicate Pred) {
1080     return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1081   }
1082 };
1083
1084 /// \brief Helper class for identifying unordered min predicates.
1085 struct ufmin_pred_ty {
1086   static bool match(FCmpInst::Predicate Pred) {
1087     return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1088   }
1089 };
1090
1091 template <typename LHS, typename RHS>
1092 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1093                                                              const RHS &R) {
1094   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1095 }
1096
1097 template <typename LHS, typename RHS>
1098 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1099                                                              const RHS &R) {
1100   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1101 }
1102
1103 template <typename LHS, typename RHS>
1104 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1105                                                              const RHS &R) {
1106   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1107 }
1108
1109 template <typename LHS, typename RHS>
1110 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1111                                                              const RHS &R) {
1112   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1113 }
1114
1115 /// \brief Match an 'ordered' floating point maximum function.
1116 /// Floating point has one special value 'NaN'. Therefore, there is no total
1117 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1118 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1119 /// semantics. In the presence of 'NaN' we have to preserve the original
1120 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1121 ///
1122 ///                         max(L, R)  iff L and R are not NaN
1123 ///  m_OrdFMax(L, R) =      R          iff L or R are NaN
1124 template <typename LHS, typename RHS>
1125 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1126                                                                  const RHS &R) {
1127   return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1128 }
1129
1130 /// \brief Match an 'ordered' floating point minimum function.
1131 /// Floating point has one special value 'NaN'. Therefore, there is no total
1132 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1133 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1134 /// semantics. In the presence of 'NaN' we have to preserve the original
1135 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1136 ///
1137 ///                         max(L, R)  iff L and R are not NaN
1138 ///  m_OrdFMin(L, R) =      R          iff L or R are NaN
1139 template <typename LHS, typename RHS>
1140 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1141                                                                  const RHS &R) {
1142   return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1143 }
1144
1145 /// \brief Match an 'unordered' floating point maximum function.
1146 /// Floating point has one special value 'NaN'. Therefore, there is no total
1147 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1148 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1149 /// semantics. In the presence of 'NaN' we have to preserve the original
1150 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1151 ///
1152 ///                         max(L, R)  iff L and R are not NaN
1153 ///  m_UnordFMin(L, R) =    L          iff L or R are NaN
1154 template <typename LHS, typename RHS>
1155 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1156 m_UnordFMax(const LHS &L, const RHS &R) {
1157   return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1158 }
1159
1160 //===----------------------------------------------------------------------===//
1161 // Matchers for overflow check patterns: e.g. (a + b) u< a
1162 //
1163
1164 template <typename LHS_t, typename RHS_t, typename Sum_t>
1165 struct UAddWithOverflow_match {
1166   LHS_t L;
1167   RHS_t R;
1168   Sum_t S;
1169
1170   UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1171       : L(L), R(R), S(S) {}
1172
1173   template <typename OpTy> bool match(OpTy *V) {
1174     Value *ICmpLHS, *ICmpRHS;
1175     ICmpInst::Predicate Pred;
1176     if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1177       return false;
1178
1179     Value *AddLHS, *AddRHS;
1180     auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1181
1182     // (a + b) u< a, (a + b) u< b
1183     if (Pred == ICmpInst::ICMP_ULT)
1184       if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1185         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1186
1187     // a >u (a + b), b >u (a + b)
1188     if (Pred == ICmpInst::ICMP_UGT)
1189       if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1190         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1191
1192     return false;
1193   }
1194 };
1195
1196 /// \brief Match an icmp instruction checking for unsigned overflow on addition.
1197 ///
1198 /// S is matched to the addition whose result is being checked for overflow, and
1199 /// L and R are matched to the LHS and RHS of S.
1200 template <typename LHS_t, typename RHS_t, typename Sum_t>
1201 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
1202 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1203   return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1204 }
1205
1206 /// \brief Match an 'unordered' floating point minimum function.
1207 /// Floating point has one special value 'NaN'. Therefore, there is no total
1208 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1209 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1210 /// semantics. In the presence of 'NaN' we have to preserve the original
1211 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1212 ///
1213 ///                          max(L, R)  iff L and R are not NaN
1214 ///  m_UnordFMin(L, R) =     L          iff L or R are NaN
1215 template <typename LHS, typename RHS>
1216 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1217 m_UnordFMin(const LHS &L, const RHS &R) {
1218   return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1219 }
1220
1221 template <typename Opnd_t> struct Argument_match {
1222   unsigned OpI;
1223   Opnd_t Val;
1224
1225   Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1226
1227   template <typename OpTy> bool match(OpTy *V) {
1228     CallSite CS(V);
1229     return CS.isCall() && Val.match(CS.getArgument(OpI));
1230   }
1231 };
1232
1233 /// \brief Match an argument.
1234 template <unsigned OpI, typename Opnd_t>
1235 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1236   return Argument_match<Opnd_t>(OpI, Op);
1237 }
1238
1239 /// \brief Intrinsic matchers.
1240 struct IntrinsicID_match {
1241   unsigned ID;
1242
1243   IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1244
1245   template <typename OpTy> bool match(OpTy *V) {
1246     if (const auto *CI = dyn_cast<CallInst>(V))
1247       if (const auto *F = CI->getCalledFunction())
1248         return F->getIntrinsicID() == ID;
1249     return false;
1250   }
1251 };
1252
1253 /// Intrinsic matches are combinations of ID matchers, and argument
1254 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
1255 /// them with lower arity matchers. Here's some convenient typedefs for up to
1256 /// several arguments, and more can be added as needed
1257 template <typename T0 = void, typename T1 = void, typename T2 = void,
1258           typename T3 = void, typename T4 = void, typename T5 = void,
1259           typename T6 = void, typename T7 = void, typename T8 = void,
1260           typename T9 = void, typename T10 = void>
1261 struct m_Intrinsic_Ty;
1262 template <typename T0> struct m_Intrinsic_Ty<T0> {
1263   using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1264 };
1265 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1266   using Ty =
1267       match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1268 };
1269 template <typename T0, typename T1, typename T2>
1270 struct m_Intrinsic_Ty<T0, T1, T2> {
1271   using Ty =
1272       match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
1273                         Argument_match<T2>>;
1274 };
1275 template <typename T0, typename T1, typename T2, typename T3>
1276 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
1277   using Ty =
1278       match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
1279                         Argument_match<T3>>;
1280 };
1281
1282 /// \brief Match intrinsic calls like this:
1283 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
1284 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
1285   return IntrinsicID_match(IntrID);
1286 }
1287
1288 template <Intrinsic::ID IntrID, typename T0>
1289 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
1290   return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
1291 }
1292
1293 template <Intrinsic::ID IntrID, typename T0, typename T1>
1294 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
1295                                                        const T1 &Op1) {
1296   return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
1297 }
1298
1299 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
1300 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
1301 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
1302   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
1303 }
1304
1305 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1306           typename T3>
1307 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
1308 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
1309   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
1310 }
1311
1312 // Helper intrinsic matching specializations.
1313 template <typename Opnd0>
1314 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
1315   return m_Intrinsic<Intrinsic::bswap>(Op0);
1316 }
1317
1318 template <typename Opnd0, typename Opnd1>
1319 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
1320                                                         const Opnd1 &Op1) {
1321   return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
1322 }
1323
1324 template <typename Opnd0, typename Opnd1>
1325 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
1326                                                         const Opnd1 &Op1) {
1327   return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
1328 }
1329
1330 template <typename Opnd_t> struct Signum_match {
1331   Opnd_t Val;
1332   Signum_match(const Opnd_t &V) : Val(V) {}
1333
1334   template <typename OpTy> bool match(OpTy *V) {
1335     unsigned TypeSize = V->getType()->getScalarSizeInBits();
1336     if (TypeSize == 0)
1337       return false;
1338
1339     unsigned ShiftWidth = TypeSize - 1;
1340     Value *OpL = nullptr, *OpR = nullptr;
1341
1342     // This is the representation of signum we match:
1343     //
1344     //  signum(x) == (x >> 63) | (-x >>u 63)
1345     //
1346     // An i1 value is its own signum, so it's correct to match
1347     //
1348     //  signum(x) == (x >> 0)  | (-x >>u 0)
1349     //
1350     // for i1 values.
1351
1352     auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
1353     auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
1354     auto Signum = m_Or(LHS, RHS);
1355
1356     return Signum.match(V) && OpL == OpR && Val.match(OpL);
1357   }
1358 };
1359
1360 /// \brief Matches a signum pattern.
1361 ///
1362 /// signum(x) =
1363 ///      x >  0  ->  1
1364 ///      x == 0  ->  0
1365 ///      x <  0  -> -1
1366 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
1367   return Signum_match<Val_t>(V);
1368 }
1369
1370 //===----------------------------------------------------------------------===//
1371 // Matchers for two-operands operators with the operators in either order
1372 //
1373
1374 /// \brief Matches a BinaryOperator with LHS and RHS in either order.
1375 template<typename LHS, typename RHS>
1376 inline match_combine_or<AnyBinaryOp_match<LHS, RHS>,
1377                         AnyBinaryOp_match<RHS, LHS>>
1378 m_c_BinOp(const LHS &L, const RHS &R) {
1379   return m_CombineOr(m_BinOp(L, R), m_BinOp(R, L));
1380 }
1381
1382 /// \brief Matches an ICmp with a predicate over LHS and RHS in either order.
1383 /// Does not swap the predicate.
1384 template<typename LHS, typename RHS>
1385 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
1386                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
1387 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1388   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
1389 }
1390
1391 /// \brief Matches a Add with LHS and RHS in either order.
1392 template<typename LHS, typename RHS>
1393 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Add>,
1394                         BinaryOp_match<RHS, LHS, Instruction::Add>>
1395 m_c_Add(const LHS &L, const RHS &R) {
1396   return m_CombineOr(m_Add(L, R), m_Add(R, L));
1397 }
1398
1399 /// \brief Matches a Mul with LHS and RHS in either order.
1400 template<typename LHS, typename RHS>
1401 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Mul>,
1402                         BinaryOp_match<RHS, LHS, Instruction::Mul>>
1403 m_c_Mul(const LHS &L, const RHS &R) {
1404   return m_CombineOr(m_Mul(L, R), m_Mul(R, L));
1405 }
1406
1407 /// \brief Matches an And with LHS and RHS in either order.
1408 template<typename LHS, typename RHS>
1409 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
1410                         BinaryOp_match<RHS, LHS, Instruction::And>>
1411 m_c_And(const LHS &L, const RHS &R) {
1412   return m_CombineOr(m_And(L, R), m_And(R, L));
1413 }
1414
1415 /// \brief Matches an Or with LHS and RHS in either order.
1416 template<typename LHS, typename RHS>
1417 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
1418                         BinaryOp_match<RHS, LHS, Instruction::Or>>
1419 m_c_Or(const LHS &L, const RHS &R) {
1420   return m_CombineOr(m_Or(L, R), m_Or(R, L));
1421 }
1422
1423 /// \brief Matches an Xor with LHS and RHS in either order.
1424 template<typename LHS, typename RHS>
1425 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
1426                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
1427 m_c_Xor(const LHS &L, const RHS &R) {
1428   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
1429 }
1430
1431 /// Matches an SMin with LHS and RHS in either order.
1432 template <typename LHS, typename RHS>
1433 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>,
1434                         MaxMin_match<ICmpInst, RHS, LHS, smin_pred_ty>>
1435 m_c_SMin(const LHS &L, const RHS &R) {
1436   return m_CombineOr(m_SMin(L, R), m_SMin(R, L));
1437 }
1438 /// Matches an SMax with LHS and RHS in either order.
1439 template <typename LHS, typename RHS>
1440 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
1441                         MaxMin_match<ICmpInst, RHS, LHS, smax_pred_ty>>
1442 m_c_SMax(const LHS &L, const RHS &R) {
1443   return m_CombineOr(m_SMax(L, R), m_SMax(R, L));
1444 }
1445 /// Matches a UMin with LHS and RHS in either order.
1446 template <typename LHS, typename RHS>
1447 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>,
1448                         MaxMin_match<ICmpInst, RHS, LHS, umin_pred_ty>>
1449 m_c_UMin(const LHS &L, const RHS &R) {
1450   return m_CombineOr(m_UMin(L, R), m_UMin(R, L));
1451 }
1452 /// Matches a UMax with LHS and RHS in either order.
1453 template <typename LHS, typename RHS>
1454 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
1455                         MaxMin_match<ICmpInst, RHS, LHS, umax_pred_ty>>
1456 m_c_UMax(const LHS &L, const RHS &R) {
1457   return m_CombineOr(m_UMax(L, R), m_UMax(R, L));
1458 }
1459
1460 } // end namespace PatternMatch
1461 } // end namespace llvm
1462
1463 #endif // LLVM_IR_PATTERNMATCH_H