]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/PatternMatch.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, and update
[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         if (isAllOnes(O->getOperand(1)))
891           return L.match(O->getOperand(0));
892         if (isAllOnes(O->getOperand(0)))
893           return L.match(O->getOperand(1));
894       }
895     return false;
896   }
897
898 private:
899   bool isAllOnes(Value *V) {
900     return (isa<ConstantInt>(V) || isa<ConstantDataVector>(V) ||
901             // FIXME: Remove CV.
902             isa<ConstantVector>(V)) &&
903            cast<Constant>(V)->isAllOnesValue();
904   }
905 };
906
907 template <typename LHS> inline not_match<LHS> m_Not(const LHS &L) { return L; }
908
909 template <typename LHS_t> struct neg_match {
910   LHS_t L;
911
912   neg_match(const LHS_t &LHS) : L(LHS) {}
913
914   template <typename OpTy> bool match(OpTy *V) {
915     if (auto *O = dyn_cast<Operator>(V))
916       if (O->getOpcode() == Instruction::Sub)
917         return matchIfNeg(O->getOperand(0), O->getOperand(1));
918     return false;
919   }
920
921 private:
922   bool matchIfNeg(Value *LHS, Value *RHS) {
923     return ((isa<ConstantInt>(LHS) && cast<ConstantInt>(LHS)->isZero()) ||
924             isa<ConstantAggregateZero>(LHS)) &&
925            L.match(RHS);
926   }
927 };
928
929 /// \brief Match an integer negate.
930 template <typename LHS> inline neg_match<LHS> m_Neg(const LHS &L) { return L; }
931
932 template <typename LHS_t> struct fneg_match {
933   LHS_t L;
934
935   fneg_match(const LHS_t &LHS) : L(LHS) {}
936
937   template <typename OpTy> bool match(OpTy *V) {
938     if (auto *O = dyn_cast<Operator>(V))
939       if (O->getOpcode() == Instruction::FSub)
940         return matchIfFNeg(O->getOperand(0), O->getOperand(1));
941     return false;
942   }
943
944 private:
945   bool matchIfFNeg(Value *LHS, Value *RHS) {
946     if (const auto *C = dyn_cast<ConstantFP>(LHS))
947       return C->isNegativeZeroValue() && L.match(RHS);
948     return false;
949   }
950 };
951
952 /// \brief Match a floating point negate.
953 template <typename LHS> inline fneg_match<LHS> m_FNeg(const LHS &L) {
954   return L;
955 }
956
957 //===----------------------------------------------------------------------===//
958 // Matchers for control flow.
959 //
960
961 struct br_match {
962   BasicBlock *&Succ;
963
964   br_match(BasicBlock *&Succ) : Succ(Succ) {}
965
966   template <typename OpTy> bool match(OpTy *V) {
967     if (auto *BI = dyn_cast<BranchInst>(V))
968       if (BI->isUnconditional()) {
969         Succ = BI->getSuccessor(0);
970         return true;
971       }
972     return false;
973   }
974 };
975
976 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
977
978 template <typename Cond_t> struct brc_match {
979   Cond_t Cond;
980   BasicBlock *&T, *&F;
981
982   brc_match(const Cond_t &C, BasicBlock *&t, BasicBlock *&f)
983       : Cond(C), T(t), F(f) {}
984
985   template <typename OpTy> bool match(OpTy *V) {
986     if (auto *BI = dyn_cast<BranchInst>(V))
987       if (BI->isConditional() && Cond.match(BI->getCondition())) {
988         T = BI->getSuccessor(0);
989         F = BI->getSuccessor(1);
990         return true;
991       }
992     return false;
993   }
994 };
995
996 template <typename Cond_t>
997 inline brc_match<Cond_t> m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
998   return brc_match<Cond_t>(C, T, F);
999 }
1000
1001 //===----------------------------------------------------------------------===//
1002 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1003 //
1004
1005 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t>
1006 struct MaxMin_match {
1007   LHS_t L;
1008   RHS_t R;
1009
1010   MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1011
1012   template <typename OpTy> bool match(OpTy *V) {
1013     // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1014     auto *SI = dyn_cast<SelectInst>(V);
1015     if (!SI)
1016       return false;
1017     auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1018     if (!Cmp)
1019       return false;
1020     // At this point we have a select conditioned on a comparison.  Check that
1021     // it is the values returned by the select that are being compared.
1022     Value *TrueVal = SI->getTrueValue();
1023     Value *FalseVal = SI->getFalseValue();
1024     Value *LHS = Cmp->getOperand(0);
1025     Value *RHS = Cmp->getOperand(1);
1026     if ((TrueVal != LHS || FalseVal != RHS) &&
1027         (TrueVal != RHS || FalseVal != LHS))
1028       return false;
1029     typename CmpInst_t::Predicate Pred =
1030         LHS == TrueVal ? Cmp->getPredicate() : Cmp->getSwappedPredicate();
1031     // Does "(x pred y) ? x : y" represent the desired max/min operation?
1032     if (!Pred_t::match(Pred))
1033       return false;
1034     // It does!  Bind the operands.
1035     return L.match(LHS) && R.match(RHS);
1036   }
1037 };
1038
1039 /// \brief Helper class for identifying signed max predicates.
1040 struct smax_pred_ty {
1041   static bool match(ICmpInst::Predicate Pred) {
1042     return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1043   }
1044 };
1045
1046 /// \brief Helper class for identifying signed min predicates.
1047 struct smin_pred_ty {
1048   static bool match(ICmpInst::Predicate Pred) {
1049     return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1050   }
1051 };
1052
1053 /// \brief Helper class for identifying unsigned max predicates.
1054 struct umax_pred_ty {
1055   static bool match(ICmpInst::Predicate Pred) {
1056     return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1057   }
1058 };
1059
1060 /// \brief Helper class for identifying unsigned min predicates.
1061 struct umin_pred_ty {
1062   static bool match(ICmpInst::Predicate Pred) {
1063     return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1064   }
1065 };
1066
1067 /// \brief Helper class for identifying ordered max predicates.
1068 struct ofmax_pred_ty {
1069   static bool match(FCmpInst::Predicate Pred) {
1070     return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1071   }
1072 };
1073
1074 /// \brief Helper class for identifying ordered min predicates.
1075 struct ofmin_pred_ty {
1076   static bool match(FCmpInst::Predicate Pred) {
1077     return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1078   }
1079 };
1080
1081 /// \brief Helper class for identifying unordered max predicates.
1082 struct ufmax_pred_ty {
1083   static bool match(FCmpInst::Predicate Pred) {
1084     return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1085   }
1086 };
1087
1088 /// \brief Helper class for identifying unordered min predicates.
1089 struct ufmin_pred_ty {
1090   static bool match(FCmpInst::Predicate Pred) {
1091     return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1092   }
1093 };
1094
1095 template <typename LHS, typename RHS>
1096 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1097                                                              const RHS &R) {
1098   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1099 }
1100
1101 template <typename LHS, typename RHS>
1102 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1103                                                              const RHS &R) {
1104   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1105 }
1106
1107 template <typename LHS, typename RHS>
1108 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1109                                                              const RHS &R) {
1110   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1111 }
1112
1113 template <typename LHS, typename RHS>
1114 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1115                                                              const RHS &R) {
1116   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1117 }
1118
1119 /// \brief Match an 'ordered' floating point maximum function.
1120 /// Floating point has one special value 'NaN'. Therefore, there is no total
1121 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1122 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1123 /// semantics. In the presence of 'NaN' we have to preserve the original
1124 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1125 ///
1126 ///                         max(L, R)  iff L and R are not NaN
1127 ///  m_OrdFMax(L, R) =      R          iff L or R are NaN
1128 template <typename LHS, typename RHS>
1129 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1130                                                                  const RHS &R) {
1131   return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1132 }
1133
1134 /// \brief Match an 'ordered' floating point minimum function.
1135 /// Floating point has one special value 'NaN'. Therefore, there is no total
1136 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1137 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1138 /// semantics. In the presence of 'NaN' we have to preserve the original
1139 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1140 ///
1141 ///                         max(L, R)  iff L and R are not NaN
1142 ///  m_OrdFMin(L, R) =      R          iff L or R are NaN
1143 template <typename LHS, typename RHS>
1144 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1145                                                                  const RHS &R) {
1146   return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1147 }
1148
1149 /// \brief Match an 'unordered' floating point maximum function.
1150 /// Floating point has one special value 'NaN'. Therefore, there is no total
1151 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1152 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1153 /// semantics. In the presence of 'NaN' we have to preserve the original
1154 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1155 ///
1156 ///                         max(L, R)  iff L and R are not NaN
1157 ///  m_UnordFMin(L, R) =    L          iff L or R are NaN
1158 template <typename LHS, typename RHS>
1159 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1160 m_UnordFMax(const LHS &L, const RHS &R) {
1161   return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1162 }
1163
1164 //===----------------------------------------------------------------------===//
1165 // Matchers for overflow check patterns: e.g. (a + b) u< a
1166 //
1167
1168 template <typename LHS_t, typename RHS_t, typename Sum_t>
1169 struct UAddWithOverflow_match {
1170   LHS_t L;
1171   RHS_t R;
1172   Sum_t S;
1173
1174   UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1175       : L(L), R(R), S(S) {}
1176
1177   template <typename OpTy> bool match(OpTy *V) {
1178     Value *ICmpLHS, *ICmpRHS;
1179     ICmpInst::Predicate Pred;
1180     if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1181       return false;
1182
1183     Value *AddLHS, *AddRHS;
1184     auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1185
1186     // (a + b) u< a, (a + b) u< b
1187     if (Pred == ICmpInst::ICMP_ULT)
1188       if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1189         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1190
1191     // a >u (a + b), b >u (a + b)
1192     if (Pred == ICmpInst::ICMP_UGT)
1193       if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1194         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1195
1196     return false;
1197   }
1198 };
1199
1200 /// \brief Match an icmp instruction checking for unsigned overflow on addition.
1201 ///
1202 /// S is matched to the addition whose result is being checked for overflow, and
1203 /// L and R are matched to the LHS and RHS of S.
1204 template <typename LHS_t, typename RHS_t, typename Sum_t>
1205 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
1206 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1207   return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1208 }
1209
1210 /// \brief Match an 'unordered' floating point minimum function.
1211 /// Floating point has one special value 'NaN'. Therefore, there is no total
1212 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1213 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1214 /// semantics. In the presence of 'NaN' we have to preserve the original
1215 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1216 ///
1217 ///                          max(L, R)  iff L and R are not NaN
1218 ///  m_UnordFMin(L, R) =     L          iff L or R are NaN
1219 template <typename LHS, typename RHS>
1220 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1221 m_UnordFMin(const LHS &L, const RHS &R) {
1222   return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1223 }
1224
1225 template <typename Opnd_t> struct Argument_match {
1226   unsigned OpI;
1227   Opnd_t Val;
1228
1229   Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1230
1231   template <typename OpTy> bool match(OpTy *V) {
1232     CallSite CS(V);
1233     return CS.isCall() && Val.match(CS.getArgument(OpI));
1234   }
1235 };
1236
1237 /// \brief Match an argument.
1238 template <unsigned OpI, typename Opnd_t>
1239 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1240   return Argument_match<Opnd_t>(OpI, Op);
1241 }
1242
1243 /// \brief Intrinsic matchers.
1244 struct IntrinsicID_match {
1245   unsigned ID;
1246
1247   IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1248
1249   template <typename OpTy> bool match(OpTy *V) {
1250     if (const auto *CI = dyn_cast<CallInst>(V))
1251       if (const auto *F = CI->getCalledFunction())
1252         return F->getIntrinsicID() == ID;
1253     return false;
1254   }
1255 };
1256
1257 /// Intrinsic matches are combinations of ID matchers, and argument
1258 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
1259 /// them with lower arity matchers. Here's some convenient typedefs for up to
1260 /// several arguments, and more can be added as needed
1261 template <typename T0 = void, typename T1 = void, typename T2 = void,
1262           typename T3 = void, typename T4 = void, typename T5 = void,
1263           typename T6 = void, typename T7 = void, typename T8 = void,
1264           typename T9 = void, typename T10 = void>
1265 struct m_Intrinsic_Ty;
1266 template <typename T0> struct m_Intrinsic_Ty<T0> {
1267   using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1268 };
1269 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1270   using Ty =
1271       match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1272 };
1273 template <typename T0, typename T1, typename T2>
1274 struct m_Intrinsic_Ty<T0, T1, T2> {
1275   using Ty =
1276       match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
1277                         Argument_match<T2>>;
1278 };
1279 template <typename T0, typename T1, typename T2, typename T3>
1280 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
1281   using Ty =
1282       match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
1283                         Argument_match<T3>>;
1284 };
1285
1286 /// \brief Match intrinsic calls like this:
1287 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
1288 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
1289   return IntrinsicID_match(IntrID);
1290 }
1291
1292 template <Intrinsic::ID IntrID, typename T0>
1293 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
1294   return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
1295 }
1296
1297 template <Intrinsic::ID IntrID, typename T0, typename T1>
1298 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
1299                                                        const T1 &Op1) {
1300   return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
1301 }
1302
1303 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
1304 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
1305 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
1306   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
1307 }
1308
1309 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1310           typename T3>
1311 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
1312 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
1313   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
1314 }
1315
1316 // Helper intrinsic matching specializations.
1317 template <typename Opnd0>
1318 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
1319   return m_Intrinsic<Intrinsic::bswap>(Op0);
1320 }
1321
1322 template <typename Opnd0, typename Opnd1>
1323 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
1324                                                         const Opnd1 &Op1) {
1325   return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
1326 }
1327
1328 template <typename Opnd0, typename Opnd1>
1329 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
1330                                                         const Opnd1 &Op1) {
1331   return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
1332 }
1333
1334 template <typename Opnd_t> struct Signum_match {
1335   Opnd_t Val;
1336   Signum_match(const Opnd_t &V) : Val(V) {}
1337
1338   template <typename OpTy> bool match(OpTy *V) {
1339     unsigned TypeSize = V->getType()->getScalarSizeInBits();
1340     if (TypeSize == 0)
1341       return false;
1342
1343     unsigned ShiftWidth = TypeSize - 1;
1344     Value *OpL = nullptr, *OpR = nullptr;
1345
1346     // This is the representation of signum we match:
1347     //
1348     //  signum(x) == (x >> 63) | (-x >>u 63)
1349     //
1350     // An i1 value is its own signum, so it's correct to match
1351     //
1352     //  signum(x) == (x >> 0)  | (-x >>u 0)
1353     //
1354     // for i1 values.
1355
1356     auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
1357     auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
1358     auto Signum = m_Or(LHS, RHS);
1359
1360     return Signum.match(V) && OpL == OpR && Val.match(OpL);
1361   }
1362 };
1363
1364 /// \brief Matches a signum pattern.
1365 ///
1366 /// signum(x) =
1367 ///      x >  0  ->  1
1368 ///      x == 0  ->  0
1369 ///      x <  0  -> -1
1370 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
1371   return Signum_match<Val_t>(V);
1372 }
1373
1374 //===----------------------------------------------------------------------===//
1375 // Matchers for two-operands operators with the operators in either order
1376 //
1377
1378 /// \brief Matches a BinaryOperator with LHS and RHS in either order.
1379 template<typename LHS, typename RHS>
1380 inline match_combine_or<AnyBinaryOp_match<LHS, RHS>,
1381                         AnyBinaryOp_match<RHS, LHS>>
1382 m_c_BinOp(const LHS &L, const RHS &R) {
1383   return m_CombineOr(m_BinOp(L, R), m_BinOp(R, L));
1384 }
1385
1386 /// \brief Matches an ICmp with a predicate over LHS and RHS in either order.
1387 /// Does not swap the predicate.
1388 template<typename LHS, typename RHS>
1389 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
1390                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
1391 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1392   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
1393 }
1394
1395 /// \brief Matches a Add with LHS and RHS in either order.
1396 template<typename LHS, typename RHS>
1397 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Add>,
1398                         BinaryOp_match<RHS, LHS, Instruction::Add>>
1399 m_c_Add(const LHS &L, const RHS &R) {
1400   return m_CombineOr(m_Add(L, R), m_Add(R, L));
1401 }
1402
1403 /// \brief Matches a Mul with LHS and RHS in either order.
1404 template<typename LHS, typename RHS>
1405 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Mul>,
1406                         BinaryOp_match<RHS, LHS, Instruction::Mul>>
1407 m_c_Mul(const LHS &L, const RHS &R) {
1408   return m_CombineOr(m_Mul(L, R), m_Mul(R, L));
1409 }
1410
1411 /// \brief Matches an And with LHS and RHS in either order.
1412 template<typename LHS, typename RHS>
1413 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
1414                         BinaryOp_match<RHS, LHS, Instruction::And>>
1415 m_c_And(const LHS &L, const RHS &R) {
1416   return m_CombineOr(m_And(L, R), m_And(R, L));
1417 }
1418
1419 /// \brief Matches an Or with LHS and RHS in either order.
1420 template<typename LHS, typename RHS>
1421 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
1422                         BinaryOp_match<RHS, LHS, Instruction::Or>>
1423 m_c_Or(const LHS &L, const RHS &R) {
1424   return m_CombineOr(m_Or(L, R), m_Or(R, L));
1425 }
1426
1427 /// \brief Matches an Xor with LHS and RHS in either order.
1428 template<typename LHS, typename RHS>
1429 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
1430                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
1431 m_c_Xor(const LHS &L, const RHS &R) {
1432   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
1433 }
1434
1435 /// Matches an SMin with LHS and RHS in either order.
1436 template <typename LHS, typename RHS>
1437 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>,
1438                         MaxMin_match<ICmpInst, RHS, LHS, smin_pred_ty>>
1439 m_c_SMin(const LHS &L, const RHS &R) {
1440   return m_CombineOr(m_SMin(L, R), m_SMin(R, L));
1441 }
1442 /// Matches an SMax with LHS and RHS in either order.
1443 template <typename LHS, typename RHS>
1444 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
1445                         MaxMin_match<ICmpInst, RHS, LHS, smax_pred_ty>>
1446 m_c_SMax(const LHS &L, const RHS &R) {
1447   return m_CombineOr(m_SMax(L, R), m_SMax(R, L));
1448 }
1449 /// Matches a UMin with LHS and RHS in either order.
1450 template <typename LHS, typename RHS>
1451 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>,
1452                         MaxMin_match<ICmpInst, RHS, LHS, umin_pred_ty>>
1453 m_c_UMin(const LHS &L, const RHS &R) {
1454   return m_CombineOr(m_UMin(L, R), m_UMin(R, L));
1455 }
1456 /// Matches a UMax with LHS and RHS in either order.
1457 template <typename LHS, typename RHS>
1458 inline match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
1459                         MaxMin_match<ICmpInst, RHS, LHS, umax_pred_ty>>
1460 m_c_UMax(const LHS &L, const RHS &R) {
1461   return m_CombineOr(m_UMax(L, R), m_UMax(R, L));
1462 }
1463
1464 } // end namespace PatternMatch
1465 } // end namespace llvm
1466
1467 #endif // LLVM_IR_PATTERNMATCH_H