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