Bug Summary

File:include/llvm/IR/PatternMatch.h
Warning:line 1208, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstCombineAddSub.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp

/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp

1//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/AlignOf.h"
30#include "llvm/Support/Casting.h"
31#include "llvm/Support/KnownBits.h"
32#include <cassert>
33#include <utility>
34
35using namespace llvm;
36using namespace PatternMatch;
37
38#define DEBUG_TYPE"instcombine" "instcombine"
39
40namespace {
41
42 /// Class representing coefficient of floating-point addend.
43 /// This class needs to be highly efficient, which is especially true for
44 /// the constructor. As of I write this comment, the cost of the default
45 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
46 /// perform write-merging).
47 ///
48 class FAddendCoef {
49 public:
50 // The constructor has to initialize a APFloat, which is unnecessary for
51 // most addends which have coefficient either 1 or -1. So, the constructor
52 // is expensive. In order to avoid the cost of the constructor, we should
53 // reuse some instances whenever possible. The pre-created instances
54 // FAddCombine::Add[0-5] embodies this idea.
55 FAddendCoef() = default;
56 ~FAddendCoef();
57
58 // If possible, don't define operator+/operator- etc because these
59 // operators inevitably call FAddendCoef's constructor which is not cheap.
60 void operator=(const FAddendCoef &A);
61 void operator+=(const FAddendCoef &A);
62 void operator*=(const FAddendCoef &S);
63
64 void set(short C) {
65 assert(!insaneIntVal(C) && "Insane coefficient")((!insaneIntVal(C) && "Insane coefficient") ? static_cast
<void> (0) : __assert_fail ("!insaneIntVal(C) && \"Insane coefficient\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 65, __PRETTY_FUNCTION__))
;
66 IsFp = false; IntVal = C;
67 }
68
69 void set(const APFloat& C);
70
71 void negate();
72
73 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
74 Value *getValue(Type *) const;
75
76 bool isOne() const { return isInt() && IntVal == 1; }
77 bool isTwo() const { return isInt() && IntVal == 2; }
78 bool isMinusOne() const { return isInt() && IntVal == -1; }
79 bool isMinusTwo() const { return isInt() && IntVal == -2; }
80
81 private:
82 bool insaneIntVal(int V) { return V > 4 || V < -4; }
83
84 APFloat *getFpValPtr()
85 { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
86
87 const APFloat *getFpValPtr() const
88 { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
89
90 const APFloat &getFpVal() const {
91 assert(IsFp && BufHasFpVal && "Incorret state")((IsFp && BufHasFpVal && "Incorret state") ? static_cast
<void> (0) : __assert_fail ("IsFp && BufHasFpVal && \"Incorret state\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 91, __PRETTY_FUNCTION__))
;
92 return *getFpValPtr();
93 }
94
95 APFloat &getFpVal() {
96 assert(IsFp && BufHasFpVal && "Incorret state")((IsFp && BufHasFpVal && "Incorret state") ? static_cast
<void> (0) : __assert_fail ("IsFp && BufHasFpVal && \"Incorret state\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 96, __PRETTY_FUNCTION__))
;
97 return *getFpValPtr();
98 }
99
100 bool isInt() const { return !IsFp; }
101
102 // If the coefficient is represented by an integer, promote it to a
103 // floating point.
104 void convertToFpType(const fltSemantics &Sem);
105
106 // Construct an APFloat from a signed integer.
107 // TODO: We should get rid of this function when APFloat can be constructed
108 // from an *SIGNED* integer.
109 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
110
111 bool IsFp = false;
112
113 // True iff FpValBuf contains an instance of APFloat.
114 bool BufHasFpVal = false;
115
116 // The integer coefficient of an individual addend is either 1 or -1,
117 // and we try to simplify at most 4 addends from neighboring at most
118 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
119 // is overkill of this end.
120 short IntVal = 0;
121
122 AlignedCharArrayUnion<APFloat> FpValBuf;
123 };
124
125 /// FAddend is used to represent floating-point addend. An addend is
126 /// represented as <C, V>, where the V is a symbolic value, and C is a
127 /// constant coefficient. A constant addend is represented as <C, 0>.
128 class FAddend {
129 public:
130 FAddend() = default;
131
132 void operator+=(const FAddend &T) {
133 assert((Val == T.Val) && "Symbolic-values disagree")(((Val == T.Val) && "Symbolic-values disagree") ? static_cast
<void> (0) : __assert_fail ("(Val == T.Val) && \"Symbolic-values disagree\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 133, __PRETTY_FUNCTION__))
;
134 Coeff += T.Coeff;
135 }
136
137 Value *getSymVal() const { return Val; }
138 const FAddendCoef &getCoef() const { return Coeff; }
139
140 bool isConstant() const { return Val == nullptr; }
141 bool isZero() const { return Coeff.isZero(); }
142
143 void set(short Coefficient, Value *V) {
144 Coeff.set(Coefficient);
145 Val = V;
146 }
147 void set(const APFloat &Coefficient, Value *V) {
148 Coeff.set(Coefficient);
149 Val = V;
150 }
151 void set(const ConstantFP *Coefficient, Value *V) {
152 Coeff.set(Coefficient->getValueAPF());
153 Val = V;
154 }
155
156 void negate() { Coeff.negate(); }
157
158 /// Drill down the U-D chain one step to find the definition of V, and
159 /// try to break the definition into one or two addends.
160 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
161
162 /// Similar to FAddend::drillDownOneStep() except that the value being
163 /// splitted is the addend itself.
164 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
165
166 private:
167 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
168
169 // This addend has the value of "Coeff * Val".
170 Value *Val = nullptr;
171 FAddendCoef Coeff;
172 };
173
174 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
175 /// with its neighboring at most two instructions.
176 ///
177 class FAddCombine {
178 public:
179 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
180
181 Value *simplify(Instruction *FAdd);
182
183 private:
184 using AddendVect = SmallVector<const FAddend *, 4>;
185
186 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
187
188 /// Convert given addend to a Value
189 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
190
191 /// Return the number of instructions needed to emit the N-ary addition.
192 unsigned calcInstrNumber(const AddendVect& Vect);
193
194 Value *createFSub(Value *Opnd0, Value *Opnd1);
195 Value *createFAdd(Value *Opnd0, Value *Opnd1);
196 Value *createFMul(Value *Opnd0, Value *Opnd1);
197 Value *createFNeg(Value *V);
198 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
199 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
200
201 // Debugging stuff are clustered here.
202 #ifndef NDEBUG
203 unsigned CreateInstrNum;
204 void initCreateInstNum() { CreateInstrNum = 0; }
205 void incCreateInstNum() { CreateInstrNum++; }
206 #else
207 void initCreateInstNum() {}
208 void incCreateInstNum() {}
209 #endif
210
211 InstCombiner::BuilderTy &Builder;
212 Instruction *Instr = nullptr;
213 };
214
215} // end anonymous namespace
216
217//===----------------------------------------------------------------------===//
218//
219// Implementation of
220// {FAddendCoef, FAddend, FAddition, FAddCombine}.
221//
222//===----------------------------------------------------------------------===//
223FAddendCoef::~FAddendCoef() {
224 if (BufHasFpVal)
225 getFpValPtr()->~APFloat();
226}
227
228void FAddendCoef::set(const APFloat& C) {
229 APFloat *P = getFpValPtr();
230
231 if (isInt()) {
232 // As the buffer is meanless byte stream, we cannot call
233 // APFloat::operator=().
234 new(P) APFloat(C);
235 } else
236 *P = C;
237
238 IsFp = BufHasFpVal = true;
239}
240
241void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
242 if (!isInt())
243 return;
244
245 APFloat *P = getFpValPtr();
246 if (IntVal > 0)
247 new(P) APFloat(Sem, IntVal);
248 else {
249 new(P) APFloat(Sem, 0 - IntVal);
250 P->changeSign();
251 }
252 IsFp = BufHasFpVal = true;
253}
254
255APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
256 if (Val >= 0)
257 return APFloat(Sem, Val);
258
259 APFloat T(Sem, 0 - Val);
260 T.changeSign();
261
262 return T;
263}
264
265void FAddendCoef::operator=(const FAddendCoef &That) {
266 if (That.isInt())
267 set(That.IntVal);
268 else
269 set(That.getFpVal());
270}
271
272void FAddendCoef::operator+=(const FAddendCoef &That) {
273 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
274 if (isInt() == That.isInt()) {
275 if (isInt())
276 IntVal += That.IntVal;
277 else
278 getFpVal().add(That.getFpVal(), RndMode);
279 return;
280 }
281
282 if (isInt()) {
283 const APFloat &T = That.getFpVal();
284 convertToFpType(T.getSemantics());
285 getFpVal().add(T, RndMode);
286 return;
287 }
288
289 APFloat &T = getFpVal();
290 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
291}
292
293void FAddendCoef::operator*=(const FAddendCoef &That) {
294 if (That.isOne())
295 return;
296
297 if (That.isMinusOne()) {
298 negate();
299 return;
300 }
301
302 if (isInt() && That.isInt()) {
303 int Res = IntVal * (int)That.IntVal;
304 assert(!insaneIntVal(Res) && "Insane int value")((!insaneIntVal(Res) && "Insane int value") ? static_cast
<void> (0) : __assert_fail ("!insaneIntVal(Res) && \"Insane int value\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 304, __PRETTY_FUNCTION__))
;
305 IntVal = Res;
306 return;
307 }
308
309 const fltSemantics &Semantic =
310 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
311
312 if (isInt())
313 convertToFpType(Semantic);
314 APFloat &F0 = getFpVal();
315
316 if (That.isInt())
317 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318 APFloat::rmNearestTiesToEven);
319 else
320 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
321}
322
323void FAddendCoef::negate() {
324 if (isInt())
325 IntVal = 0 - IntVal;
326 else
327 getFpVal().changeSign();
328}
329
330Value *FAddendCoef::getValue(Type *Ty) const {
331 return isInt() ?
332 ConstantFP::get(Ty, float(IntVal)) :
333 ConstantFP::get(Ty->getContext(), getFpVal());
334}
335
336// The definition of <Val> Addends
337// =========================================
338// A + B <1, A>, <1,B>
339// A - B <1, A>, <1,B>
340// 0 - B <-1, B>
341// C * A, <C, A>
342// A + C <1, A> <C, NULL>
343// 0 +/- 0 <0, NULL> (corner case)
344//
345// Legend: A and B are not constant, C is constant
346unsigned FAddend::drillValueDownOneStep
347 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
348 Instruction *I = nullptr;
349 if (!Val || !(I = dyn_cast<Instruction>(Val)))
350 return 0;
351
352 unsigned Opcode = I->getOpcode();
353
354 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
355 ConstantFP *C0, *C1;
356 Value *Opnd0 = I->getOperand(0);
357 Value *Opnd1 = I->getOperand(1);
358 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
359 Opnd0 = nullptr;
360
361 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
362 Opnd1 = nullptr;
363
364 if (Opnd0) {
365 if (!C0)
366 Addend0.set(1, Opnd0);
367 else
368 Addend0.set(C0, nullptr);
369 }
370
371 if (Opnd1) {
372 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
373 if (!C1)
374 Addend.set(1, Opnd1);
375 else
376 Addend.set(C1, nullptr);
377 if (Opcode == Instruction::FSub)
378 Addend.negate();
379 }
380
381 if (Opnd0 || Opnd1)
382 return Opnd0 && Opnd1 ? 2 : 1;
383
384 // Both operands are zero. Weird!
385 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
386 return 1;
387 }
388
389 if (I->getOpcode() == Instruction::FMul) {
390 Value *V0 = I->getOperand(0);
391 Value *V1 = I->getOperand(1);
392 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
393 Addend0.set(C, V1);
394 return 1;
395 }
396
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
398 Addend0.set(C, V0);
399 return 1;
400 }
401 }
402
403 return 0;
404}
405
406// Try to break *this* addend into two addends. e.g. Suppose this addend is
407// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
408// i.e. <2.3, X> and <2.3, Y>.
409unsigned FAddend::drillAddendDownOneStep
410 (FAddend &Addend0, FAddend &Addend1) const {
411 if (isConstant())
412 return 0;
413
414 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
415 if (!BreakNum || Coeff.isOne())
416 return BreakNum;
417
418 Addend0.Scale(Coeff);
419
420 if (BreakNum == 2)
421 Addend1.Scale(Coeff);
422
423 return BreakNum;
424}
425
426Value *FAddCombine::simplify(Instruction *I) {
427 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&((I->hasAllowReassoc() && I->hasNoSignedZeros()
&& "Expected 'reassoc'+'nsz' instruction") ? static_cast
<void> (0) : __assert_fail ("I->hasAllowReassoc() && I->hasNoSignedZeros() && \"Expected 'reassoc'+'nsz' instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 428, __PRETTY_FUNCTION__))
428 "Expected 'reassoc'+'nsz' instruction")((I->hasAllowReassoc() && I->hasNoSignedZeros()
&& "Expected 'reassoc'+'nsz' instruction") ? static_cast
<void> (0) : __assert_fail ("I->hasAllowReassoc() && I->hasNoSignedZeros() && \"Expected 'reassoc'+'nsz' instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 428, __PRETTY_FUNCTION__))
;
429
430 // Currently we are not able to handle vector type.
431 if (I->getType()->isVectorTy())
432 return nullptr;
433
434 assert((I->getOpcode() == Instruction::FAdd ||(((I->getOpcode() == Instruction::FAdd || I->getOpcode(
) == Instruction::FSub) && "Expect add/sub") ? static_cast
<void> (0) : __assert_fail ("(I->getOpcode() == Instruction::FAdd || I->getOpcode() == Instruction::FSub) && \"Expect add/sub\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 435, __PRETTY_FUNCTION__))
435 I->getOpcode() == Instruction::FSub) && "Expect add/sub")(((I->getOpcode() == Instruction::FAdd || I->getOpcode(
) == Instruction::FSub) && "Expect add/sub") ? static_cast
<void> (0) : __assert_fail ("(I->getOpcode() == Instruction::FAdd || I->getOpcode() == Instruction::FSub) && \"Expect add/sub\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 435, __PRETTY_FUNCTION__))
;
436
437 // Save the instruction before calling other member-functions.
438 Instr = I;
439
440 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
441
442 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
443
444 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
445 unsigned Opnd0_ExpNum = 0;
446 unsigned Opnd1_ExpNum = 0;
447
448 if (!Opnd0.isConstant())
449 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
450
451 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
452 if (OpndNum == 2 && !Opnd1.isConstant())
453 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
454
455 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
456 if (Opnd0_ExpNum && Opnd1_ExpNum) {
457 AddendVect AllOpnds;
458 AllOpnds.push_back(&Opnd0_0);
459 AllOpnds.push_back(&Opnd1_0);
460 if (Opnd0_ExpNum == 2)
461 AllOpnds.push_back(&Opnd0_1);
462 if (Opnd1_ExpNum == 2)
463 AllOpnds.push_back(&Opnd1_1);
464
465 // Compute instruction quota. We should save at least one instruction.
466 unsigned InstQuota = 0;
467
468 Value *V0 = I->getOperand(0);
469 Value *V1 = I->getOperand(1);
470 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
471 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
472
473 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
474 return R;
475 }
476
477 if (OpndNum != 2) {
478 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
479 // splitted into two addends, say "V = X - Y", the instruction would have
480 // been optimized into "I = Y - X" in the previous steps.
481 //
482 const FAddendCoef &CE = Opnd0.getCoef();
483 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
484 }
485
486 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
487 if (Opnd1_ExpNum) {
488 AddendVect AllOpnds;
489 AllOpnds.push_back(&Opnd0);
490 AllOpnds.push_back(&Opnd1_0);
491 if (Opnd1_ExpNum == 2)
492 AllOpnds.push_back(&Opnd1_1);
493
494 if (Value *R = simplifyFAdd(AllOpnds, 1))
495 return R;
496 }
497
498 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
499 if (Opnd0_ExpNum) {
500 AddendVect AllOpnds;
501 AllOpnds.push_back(&Opnd1);
502 AllOpnds.push_back(&Opnd0_0);
503 if (Opnd0_ExpNum == 2)
504 AllOpnds.push_back(&Opnd0_1);
505
506 if (Value *R = simplifyFAdd(AllOpnds, 1))
507 return R;
508 }
509
510 return nullptr;
511}
512
513Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
514 unsigned AddendNum = Addends.size();
515 assert(AddendNum <= 4 && "Too many addends")((AddendNum <= 4 && "Too many addends") ? static_cast
<void> (0) : __assert_fail ("AddendNum <= 4 && \"Too many addends\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 515, __PRETTY_FUNCTION__))
;
516
517 // For saving intermediate results;
518 unsigned NextTmpIdx = 0;
519 FAddend TmpResult[3];
520
521 // Points to the constant addend of the resulting simplified expression.
522 // If the resulting expr has constant-addend, this constant-addend is
523 // desirable to reside at the top of the resulting expression tree. Placing
524 // constant close to supper-expr(s) will potentially reveal some optimization
525 // opportunities in super-expr(s).
526 const FAddend *ConstAdd = nullptr;
527
528 // Simplified addends are placed <SimpVect>.
529 AddendVect SimpVect;
530
531 // The outer loop works on one symbolic-value at a time. Suppose the input
532 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
533 // The symbolic-values will be processed in this order: x, y, z.
534 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
535
536 const FAddend *ThisAddend = Addends[SymIdx];
537 if (!ThisAddend) {
538 // This addend was processed before.
539 continue;
540 }
541
542 Value *Val = ThisAddend->getSymVal();
543 unsigned StartIdx = SimpVect.size();
544 SimpVect.push_back(ThisAddend);
545
546 // The inner loop collects addends sharing same symbolic-value, and these
547 // addends will be later on folded into a single addend. Following above
548 // example, if the symbolic value "y" is being processed, the inner loop
549 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
550 // be later on folded into "<b1+b2, y>".
551 for (unsigned SameSymIdx = SymIdx + 1;
552 SameSymIdx < AddendNum; SameSymIdx++) {
553 const FAddend *T = Addends[SameSymIdx];
554 if (T && T->getSymVal() == Val) {
555 // Set null such that next iteration of the outer loop will not process
556 // this addend again.
557 Addends[SameSymIdx] = nullptr;
558 SimpVect.push_back(T);
559 }
560 }
561
562 // If multiple addends share same symbolic value, fold them together.
563 if (StartIdx + 1 != SimpVect.size()) {
564 FAddend &R = TmpResult[NextTmpIdx ++];
565 R = *SimpVect[StartIdx];
566 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
567 R += *SimpVect[Idx];
568
569 // Pop all addends being folded and push the resulting folded addend.
570 SimpVect.resize(StartIdx);
571 if (Val) {
572 if (!R.isZero()) {
573 SimpVect.push_back(&R);
574 }
575 } else {
576 // Don't push constant addend at this time. It will be the last element
577 // of <SimpVect>.
578 ConstAdd = &R;
579 }
580 }
581 }
582
583 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&(((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access") ? static_cast<void> (0) : __assert_fail
("(NextTmpIdx <= array_lengthof(TmpResult) + 1) && \"out-of-bound access\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 584, __PRETTY_FUNCTION__))
584 "out-of-bound access")(((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access") ? static_cast<void> (0) : __assert_fail
("(NextTmpIdx <= array_lengthof(TmpResult) + 1) && \"out-of-bound access\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 584, __PRETTY_FUNCTION__))
;
585
586 if (ConstAdd)
587 SimpVect.push_back(ConstAdd);
588
589 Value *Result;
590 if (!SimpVect.empty())
591 Result = createNaryFAdd(SimpVect, InstrQuota);
592 else {
593 // The addition is folded to 0.0.
594 Result = ConstantFP::get(Instr->getType(), 0.0);
595 }
596
597 return Result;
598}
599
600Value *FAddCombine::createNaryFAdd
601 (const AddendVect &Opnds, unsigned InstrQuota) {
602 assert(!Opnds.empty() && "Expect at least one addend")((!Opnds.empty() && "Expect at least one addend") ? static_cast
<void> (0) : __assert_fail ("!Opnds.empty() && \"Expect at least one addend\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 602, __PRETTY_FUNCTION__))
;
603
604 // Step 1: Check if the # of instructions needed exceeds the quota.
605
606 unsigned InstrNeeded = calcInstrNumber(Opnds);
607 if (InstrNeeded > InstrQuota)
608 return nullptr;
609
610 initCreateInstNum();
611
612 // step 2: Emit the N-ary addition.
613 // Note that at most three instructions are involved in Fadd-InstCombine: the
614 // addition in question, and at most two neighboring instructions.
615 // The resulting optimized addition should have at least one less instruction
616 // than the original addition expression tree. This implies that the resulting
617 // N-ary addition has at most two instructions, and we don't need to worry
618 // about tree-height when constructing the N-ary addition.
619
620 Value *LastVal = nullptr;
621 bool LastValNeedNeg = false;
622
623 // Iterate the addends, creating fadd/fsub using adjacent two addends.
624 for (const FAddend *Opnd : Opnds) {
625 bool NeedNeg;
626 Value *V = createAddendVal(*Opnd, NeedNeg);
627 if (!LastVal) {
628 LastVal = V;
629 LastValNeedNeg = NeedNeg;
630 continue;
631 }
632
633 if (LastValNeedNeg == NeedNeg) {
634 LastVal = createFAdd(LastVal, V);
635 continue;
636 }
637
638 if (LastValNeedNeg)
639 LastVal = createFSub(V, LastVal);
640 else
641 LastVal = createFSub(LastVal, V);
642
643 LastValNeedNeg = false;
644 }
645
646 if (LastValNeedNeg) {
647 LastVal = createFNeg(LastVal);
648 }
649
650#ifndef NDEBUG
651 assert(CreateInstrNum == InstrNeeded &&((CreateInstrNum == InstrNeeded && "Inconsistent in instruction numbers"
) ? static_cast<void> (0) : __assert_fail ("CreateInstrNum == InstrNeeded && \"Inconsistent in instruction numbers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 652, __PRETTY_FUNCTION__))
652 "Inconsistent in instruction numbers")((CreateInstrNum == InstrNeeded && "Inconsistent in instruction numbers"
) ? static_cast<void> (0) : __assert_fail ("CreateInstrNum == InstrNeeded && \"Inconsistent in instruction numbers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 652, __PRETTY_FUNCTION__))
;
653#endif
654
655 return LastVal;
656}
657
658Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
659 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
660 if (Instruction *I = dyn_cast<Instruction>(V))
661 createInstPostProc(I);
662 return V;
663}
664
665Value *FAddCombine::createFNeg(Value *V) {
666 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
667 Value *NewV = createFSub(Zero, V);
668 if (Instruction *I = dyn_cast<Instruction>(NewV))
669 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
670 return NewV;
671}
672
673Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
674 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
675 if (Instruction *I = dyn_cast<Instruction>(V))
676 createInstPostProc(I);
677 return V;
678}
679
680Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
681 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
682 if (Instruction *I = dyn_cast<Instruction>(V))
683 createInstPostProc(I);
684 return V;
685}
686
687void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
688 NewInstr->setDebugLoc(Instr->getDebugLoc());
689
690 // Keep track of the number of instruction created.
691 if (!NoNumber)
692 incCreateInstNum();
693
694 // Propagate fast-math flags
695 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
696}
697
698// Return the number of instruction needed to emit the N-ary addition.
699// NOTE: Keep this function in sync with createAddendVal().
700unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
701 unsigned OpndNum = Opnds.size();
702 unsigned InstrNeeded = OpndNum - 1;
703
704 // The number of addends in the form of "(-1)*x".
705 unsigned NegOpndNum = 0;
706
707 // Adjust the number of instructions needed to emit the N-ary add.
708 for (const FAddend *Opnd : Opnds) {
709 if (Opnd->isConstant())
710 continue;
711
712 // The constant check above is really for a few special constant
713 // coefficients.
714 if (isa<UndefValue>(Opnd->getSymVal()))
715 continue;
716
717 const FAddendCoef &CE = Opnd->getCoef();
718 if (CE.isMinusOne() || CE.isMinusTwo())
719 NegOpndNum++;
720
721 // Let the addend be "c * x". If "c == +/-1", the value of the addend
722 // is immediately available; otherwise, it needs exactly one instruction
723 // to evaluate the value.
724 if (!CE.isMinusOne() && !CE.isOne())
725 InstrNeeded++;
726 }
727 if (NegOpndNum == OpndNum)
728 InstrNeeded++;
729 return InstrNeeded;
730}
731
732// Input Addend Value NeedNeg(output)
733// ================================================================
734// Constant C C false
735// <+/-1, V> V coefficient is -1
736// <2/-2, V> "fadd V, V" coefficient is -2
737// <C, V> "fmul V, C" false
738//
739// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
740Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
741 const FAddendCoef &Coeff = Opnd.getCoef();
742
743 if (Opnd.isConstant()) {
744 NeedNeg = false;
745 return Coeff.getValue(Instr->getType());
746 }
747
748 Value *OpndVal = Opnd.getSymVal();
749
750 if (Coeff.isMinusOne() || Coeff.isOne()) {
751 NeedNeg = Coeff.isMinusOne();
752 return OpndVal;
753 }
754
755 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
756 NeedNeg = Coeff.isMinusTwo();
757 return createFAdd(OpndVal, OpndVal);
758 }
759
760 NeedNeg = false;
761 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
762}
763
764// Checks if any operand is negative and we can convert add to sub.
765// This function checks for following negative patterns
766// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
767// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
768// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
769static Value *checkForNegativeOperand(BinaryOperator &I,
770 InstCombiner::BuilderTy &Builder) {
771 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
772
773 // This function creates 2 instructions to replace ADD, we need at least one
774 // of LHS or RHS to have one use to ensure benefit in transform.
775 if (!LHS->hasOneUse() && !RHS->hasOneUse())
776 return nullptr;
777
778 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
779 const APInt *C1 = nullptr, *C2 = nullptr;
780
781 // if ONE is on other side, swap
782 if (match(RHS, m_Add(m_Value(X), m_One())))
783 std::swap(LHS, RHS);
784
785 if (match(LHS, m_Add(m_Value(X), m_One()))) {
786 // if XOR on other side, swap
787 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
788 std::swap(X, RHS);
789
790 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
791 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
792 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
793 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
794 Value *NewAnd = Builder.CreateAnd(Z, *C1);
795 return Builder.CreateSub(RHS, NewAnd, "sub");
796 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
797 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
798 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
799 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
800 return Builder.CreateSub(RHS, NewOr, "sub");
801 }
802 }
803 }
804
805 // Restore LHS and RHS
806 LHS = I.getOperand(0);
807 RHS = I.getOperand(1);
808
809 // if XOR is on other side, swap
810 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
811 std::swap(LHS, RHS);
812
813 // C2 is ODD
814 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
815 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
816 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
817 if (C1->countTrailingZeros() == 0)
818 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
819 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
820 return Builder.CreateSub(RHS, NewOr, "sub");
821 }
822 return nullptr;
823}
824
825/// Wrapping flags may allow combining constants separated by an extend.
826static Instruction *foldNoWrapAdd(BinaryOperator &Add,
827 InstCombiner::BuilderTy &Builder) {
828 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
829 Type *Ty = Add.getType();
830 Constant *Op1C;
831 if (!match(Op1, m_Constant(Op1C)))
832 return nullptr;
833
834 // Try this match first because it results in an add in the narrow type.
835 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
836 Value *X;
837 const APInt *C1, *C2;
838 if (match(Op1, m_APInt(C1)) &&
839 match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
840 C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
841 Constant *NewC =
842 ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
843 return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
844 }
845
846 // More general combining of constants in the wide type.
847 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
848 Constant *NarrowC;
849 if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
850 Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
851 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
852 Value *WideX = Builder.CreateSExt(X, Ty);
853 return BinaryOperator::CreateAdd(WideX, NewC);
854 }
855 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
856 if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
857 Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
858 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
859 Value *WideX = Builder.CreateZExt(X, Ty);
860 return BinaryOperator::CreateAdd(WideX, NewC);
861 }
862
863 return nullptr;
864}
865
866Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
867 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
868 Constant *Op1C;
869 if (!match(Op1, m_Constant(Op1C)))
870 return nullptr;
871
872 if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
873 return NV;
874
875 Value *X;
876 Constant *Op00C;
877
878 // add (sub C1, X), C2 --> sub (add C1, C2), X
879 if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
880 return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
881
882 Value *Y;
883
884 // add (sub X, Y), -1 --> add (not Y), X
885 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
886 match(Op1, m_AllOnes()))
887 return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
888
889 // zext(bool) + C -> bool ? C + 1 : C
890 if (match(Op0, m_ZExt(m_Value(X))) &&
891 X->getType()->getScalarSizeInBits() == 1)
892 return SelectInst::Create(X, AddOne(Op1C), Op1);
893
894 // ~X + C --> (C-1) - X
895 if (match(Op0, m_Not(m_Value(X))))
896 return BinaryOperator::CreateSub(SubOne(Op1C), X);
897
898 const APInt *C;
899 if (!match(Op1, m_APInt(C)))
900 return nullptr;
901
902 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
903 const APInt *C2;
904 if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
905 return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
906
907 if (C->isSignMask()) {
908 // If wrapping is not allowed, then the addition must set the sign bit:
909 // X + (signmask) --> X | signmask
910 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
911 return BinaryOperator::CreateOr(Op0, Op1);
912
913 // If wrapping is allowed, then the addition flips the sign bit of LHS:
914 // X + (signmask) --> X ^ signmask
915 return BinaryOperator::CreateXor(Op0, Op1);
916 }
917
918 // Is this add the last step in a convoluted sext?
919 // add(zext(xor i16 X, -32768), -32768) --> sext X
920 Type *Ty = Add.getType();
921 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
922 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
923 return CastInst::Create(Instruction::SExt, X, Ty);
924
925 if (C->isOneValue() && Op0->hasOneUse()) {
926 // add (sext i1 X), 1 --> zext (not X)
927 // TODO: The smallest IR representation is (select X, 0, 1), and that would
928 // not require the one-use check. But we need to remove a transform in
929 // visitSelect and make sure that IR value tracking for select is equal or
930 // better than for these ops.
931 if (match(Op0, m_SExt(m_Value(X))) &&
932 X->getType()->getScalarSizeInBits() == 1)
933 return new ZExtInst(Builder.CreateNot(X), Ty);
934
935 // Shifts and add used to flip and mask off the low bit:
936 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
937 const APInt *C3;
938 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
939 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
940 Value *NotX = Builder.CreateNot(X);
941 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
942 }
943 }
944
945 return nullptr;
946}
947
948// Matches multiplication expression Op * C where C is a constant. Returns the
949// constant value in C and the other operand in Op. Returns true if such a
950// match is found.
951static bool MatchMul(Value *E, Value *&Op, APInt &C) {
952 const APInt *AI;
953 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
954 C = *AI;
955 return true;
956 }
957 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
958 C = APInt(AI->getBitWidth(), 1);
959 C <<= *AI;
960 return true;
961 }
962 return false;
963}
964
965// Matches remainder expression Op % C where C is a constant. Returns the
966// constant value in C and the other operand in Op. Returns the signedness of
967// the remainder operation in IsSigned. Returns true if such a match is
968// found.
969static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
970 const APInt *AI;
971 IsSigned = false;
972 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
973 IsSigned = true;
974 C = *AI;
975 return true;
976 }
977 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
978 C = *AI;
979 return true;
980 }
981 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
982 C = *AI + 1;
983 return true;
984 }
985 return false;
986}
987
988// Matches division expression Op / C with the given signedness as indicated
989// by IsSigned, where C is a constant. Returns the constant value in C and the
990// other operand in Op. Returns true if such a match is found.
991static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
992 const APInt *AI;
993 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
994 C = *AI;
995 return true;
996 }
997 if (!IsSigned) {
998 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
999 C = *AI;
1000 return true;
1001 }
1002 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1003 C = APInt(AI->getBitWidth(), 1);
1004 C <<= *AI;
1005 return true;
1006 }
1007 }
1008 return false;
1009}
1010
1011// Returns whether C0 * C1 with the given signedness overflows.
1012static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1013 bool overflow;
1014 if (IsSigned)
1015 (void)C0.smul_ov(C1, overflow);
1016 else
1017 (void)C0.umul_ov(C1, overflow);
1018 return overflow;
1019}
1020
1021// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1022// does not overflow.
1023Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
1024 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1025 Value *X, *MulOpV;
1026 APInt C0, MulOpC;
1027 bool IsSigned;
1028 // Match I = X % C0 + MulOpV * C0
1029 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1030 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1031 C0 == MulOpC) {
1032 Value *RemOpV;
1033 APInt C1;
1034 bool Rem2IsSigned;
1035 // Match MulOpC = RemOpV % C1
1036 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1037 IsSigned == Rem2IsSigned) {
1038 Value *DivOpV;
1039 APInt DivOpC;
1040 // Match RemOpV = X / C0
1041 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1042 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1043 Value *NewDivisor =
1044 ConstantInt::get(X->getType()->getContext(), C0 * C1);
1045 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1046 : Builder.CreateURem(X, NewDivisor, "urem");
1047 }
1048 }
1049 }
1050
1051 return nullptr;
1052}
1053
1054/// Fold
1055/// (1 << NBits) - 1
1056/// Into:
1057/// ~(-(1 << NBits))
1058/// Because a 'not' is better for bit-tracking analysis and other transforms
1059/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1060static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1061 InstCombiner::BuilderTy &Builder) {
1062 Value *NBits;
1063 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1064 return nullptr;
1065
1066 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1067 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1068 // Be wary of constant folding.
1069 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1070 // Always NSW. But NUW propagates from `add`.
1071 BOp->setHasNoSignedWrap();
1072 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1073 }
1074
1075 return BinaryOperator::CreateNot(NotMask, I.getName());
1076}
1077
1078static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1079 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction")((I.getOpcode() == Instruction::Add && "Expecting add instruction"
) ? static_cast<void> (0) : __assert_fail ("I.getOpcode() == Instruction::Add && \"Expecting add instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1079, __PRETTY_FUNCTION__))
;
1080 Type *Ty = I.getType();
1081 auto getUAddSat = [&]() {
1082 return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
1083 };
1084
1085 // add (umin X, ~Y), Y --> uaddsat X, Y
1086 Value *X, *Y;
1087 if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
1088 m_Deferred(Y))))
1089 return CallInst::Create(getUAddSat(), { X, Y });
1090
1091 // add (umin X, ~C), C --> uaddsat X, C
1092 const APInt *C, *NotC;
1093 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1094 *C == ~*NotC)
1095 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1096
1097 return nullptr;
1098}
1099
1100static Instruction *
1101canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1102 BinaryOperator &I, InstCombiner::BuilderTy &Builder) {
1103 assert((I.getOpcode() == Instruction::Add ||(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Sub) && "Expecting add/sub instruction") ? static_cast
<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Sub) && \"Expecting add/sub instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1105, __PRETTY_FUNCTION__))
1
Assuming the condition is false
2
Assuming the condition is true
3
'?' condition is true
1104 I.getOpcode() == Instruction::Sub) &&(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Sub) && "Expecting add/sub instruction") ? static_cast
<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Sub) && \"Expecting add/sub instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1105, __PRETTY_FUNCTION__))
1105 "Expecting add/sub instruction")(((I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction
::Sub) && "Expecting add/sub instruction") ? static_cast
<void> (0) : __assert_fail ("(I.getOpcode() == Instruction::Add || I.getOpcode() == Instruction::Sub) && \"Expecting add/sub instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106
1107 // We have a subtraction/addition between a (potentially truncated) *logical*
1108 // right-shift of X and a "select".
1109 Value *X, *Select;
1110 Instruction *LowBitsToSkip, *Extract;
1111 if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
9
Calling 'm_c_BinOp<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
11
Returning from 'm_c_BinOp<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>>'
12
Calling 'match<llvm::BinaryOperator, llvm::PatternMatch::AnyBinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>, true>>'
35
Returning from 'match<llvm::BinaryOperator, llvm::PatternMatch::AnyBinaryOp_match<llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> >, 38>, llvm::PatternMatch::match_combine_and<llvm::PatternMatch::BinaryOp_match<llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Instruction>, 26, false>, llvm::PatternMatch::bind_ty<llvm::Instruction> > >, llvm::PatternMatch::bind_ty<llvm::Value>, true>>'
36
Taking false branch
1112 m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
1113 m_Instruction(Extract))),
1114 m_Value(Select))))
4
Calling 'm_Value'
8
Returning from 'm_Value'
1115 return nullptr;
1116
1117 // `add` is commutative; but for `sub`, "select" *must* be on RHS.
1118 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
37
Assuming pointer value is null
38
Taking false branch
1119 return nullptr;
1120
1121 Type *XTy = X->getType();
1122 bool HadTrunc = I.getType() != XTy;
39
Assuming the condition is false
1123
1124 // If there was a truncation of extracted value, then we'll need to produce
1125 // one extra instruction, so we need to ensure one instruction will go away.
1126 if (HadTrunc
39.1
'HadTrunc' is false
39.1
'HadTrunc' is false
&& !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
40
Taking false branch
1127 return nullptr;
1128
1129 // Extraction should extract high NBits bits, with shift amount calculated as:
1130 // low bits to skip = shift bitwidth - high bits to extract
1131 // The shift amount itself may be extended, and we need to look past zero-ext
1132 // when matching NBits, that will matter for matching later.
1133 Constant *C;
1134 Value *NBits;
1135 if (!match(
42
Taking false branch
1136 LowBitsToSkip,
1137 m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
1138 !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
41
Assuming the condition is false
1139 APInt(C->getType()->getScalarSizeInBits(),
1140 X->getType()->getScalarSizeInBits()))))
1141 return nullptr;
1142
1143 // Sign-extending value can be sign-extended itself if we `add` it,
1144 // or zero-extended if we `sub`tract it.
1145 auto SkipExtInMagic = [&I](Value *&V) {
1146 if (I.getOpcode() == Instruction::Add)
44
Taking false branch
1147 match(V, m_SExtOrSelf(m_Value(V)));
1148 else
1149 match(V, m_ZExtOrSelf(m_Value(V)));
45
Calling 'm_Value'
47
Returning from 'm_Value'
48
Calling 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
56
Returning from 'm_ZExtOrSelf<llvm::PatternMatch::bind_ty<llvm::Value>>'
57
Calling 'match<llvm::Value, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
59
Returning from 'match<llvm::Value, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value> >>'
1150 };
60
Returning without writing to 'V'
1151
1152 // Now, finally validate the sign-extending magic.
1153 // `select` itself may be appropriately extended, look past that.
1154 SkipExtInMagic(Select);
43
Calling 'operator()'
61
Returning from 'operator()'
1155
1156 ICmpInst::Predicate Pred;
1157 const APInt *Thr;
1158 Value *SignExtendingValue, *Zero;
1159 bool ShouldSignext;
1160 // It must be a select between two values we will later estabilish to be a
1161 // sign-extending value and a zero constant. The condition guarding the
1162 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1163 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
62
Passing null pointer value via 1st parameter 'V'
63
Calling 'match<llvm::Value, llvm::PatternMatch::ThreeOps_match<llvm::PatternMatch::CmpClass_match<llvm::PatternMatch::specificval_ty, llvm::PatternMatch::apint_match, llvm::ICmpInst, llvm::CmpInst::Predicate, false>, llvm::PatternMatch::bind_ty<llvm::Value>, llvm::PatternMatch::bind_ty<llvm::Value>, 57>>'
1164 m_Value(SignExtendingValue), m_Value(Zero))) ||
1165 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1166 return nullptr;
1167
1168 // icmp-select pair is commutative.
1169 if (!ShouldSignext)
1170 std::swap(SignExtendingValue, Zero);
1171
1172 // If we should not perform sign-extension then we must add/subtract zero.
1173 if (!match(Zero, m_Zero()))
1174 return nullptr;
1175 // Otherwise, it should be some constant, left-shifted by the same NBits we
1176 // had in `lshr`. Said left-shift can also be appropriately extended.
1177 // Again, we must look past zero-ext when looking for NBits.
1178 SkipExtInMagic(SignExtendingValue);
1179 Constant *SignExtendingValueBaseConstant;
1180 if (!match(SignExtendingValue,
1181 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1182 m_ZExtOrSelf(m_Specific(NBits)))))
1183 return nullptr;
1184 // If we `add`, then the constant should be all-ones, else it should be one.
1185 if (I.getOpcode() == Instruction::Add
1186 ? !match(SignExtendingValueBaseConstant, m_AllOnes())
1187 : !match(SignExtendingValueBaseConstant, m_One()))
1188 return nullptr;
1189
1190 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1191 Extract->getName() + ".sext");
1192 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1193 if (!HadTrunc)
1194 return NewAShr;
1195
1196 Builder.Insert(NewAShr);
1197 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1198}
1199
1200Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1201 if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
1202 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1203 SQ.getWithInstruction(&I)))
1204 return replaceInstUsesWith(I, V);
1205
1206 if (SimplifyAssociativeOrCommutative(I))
1207 return &I;
1208
1209 if (Instruction *X = foldVectorBinop(I))
1210 return X;
1211
1212 // (A*B)+(A*C) -> A*(B+C) etc
1213 if (Value *V = SimplifyUsingDistributiveLaws(I))
1214 return replaceInstUsesWith(I, V);
1215
1216 if (Instruction *X = foldAddWithConstant(I))
1217 return X;
1218
1219 if (Instruction *X = foldNoWrapAdd(I, Builder))
1220 return X;
1221
1222 // FIXME: This should be moved into the above helper function to allow these
1223 // transforms for general constant or constant splat vectors.
1224 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1225 Type *Ty = I.getType();
1226 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1227 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
1228 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1229 unsigned TySizeBits = Ty->getScalarSizeInBits();
1230 const APInt &RHSVal = CI->getValue();
1231 unsigned ExtendAmt = 0;
1232 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1233 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1234 if (XorRHS->getValue() == -RHSVal) {
1235 if (RHSVal.isPowerOf2())
1236 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1237 else if (XorRHS->getValue().isPowerOf2())
1238 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1239 }
1240
1241 if (ExtendAmt) {
1242 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1243 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
1244 ExtendAmt = 0;
1245 }
1246
1247 if (ExtendAmt) {
1248 Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
1249 Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
1250 return BinaryOperator::CreateAShr(NewShl, ShAmt);
1251 }
1252
1253 // If this is a xor that was canonicalized from a sub, turn it back into
1254 // a sub and fuse this add with it.
1255 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1256 KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
1257 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
1258 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1259 XorLHS);
1260 }
1261 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1262 // transform them into (X + (signmask ^ C))
1263 if (XorRHS->getValue().isSignMask())
1264 return BinaryOperator::CreateAdd(XorLHS,
1265 ConstantExpr::getXor(XorRHS, CI));
1266 }
1267 }
1268
1269 if (Ty->isIntOrIntVectorTy(1))
1270 return BinaryOperator::CreateXor(LHS, RHS);
1271
1272 // X + X --> X << 1
1273 if (LHS == RHS) {
1274 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1275 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1276 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1277 return Shl;
1278 }
1279
1280 Value *A, *B;
1281 if (match(LHS, m_Neg(m_Value(A)))) {
1282 // -A + -B --> -(A + B)
1283 if (match(RHS, m_Neg(m_Value(B))))
1284 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1285
1286 // -A + B --> B - A
1287 return BinaryOperator::CreateSub(RHS, A);
1288 }
1289
1290 // Canonicalize sext to zext for better value tracking potential.
1291 // add A, sext(B) --> sub A, zext(B)
1292 if (match(&I, m_c_Add(m_Value(A), m_OneUse(m_SExt(m_Value(B))))) &&
1293 B->getType()->isIntOrIntVectorTy(1))
1294 return BinaryOperator::CreateSub(A, Builder.CreateZExt(B, Ty));
1295
1296 // A + -B --> A - B
1297 if (match(RHS, m_Neg(m_Value(B))))
1298 return BinaryOperator::CreateSub(LHS, B);
1299
1300 if (Value *V = checkForNegativeOperand(I, Builder))
1301 return replaceInstUsesWith(I, V);
1302
1303 // (A + 1) + ~B --> A - B
1304 // ~B + (A + 1) --> A - B
1305 // (~B + A) + 1 --> A - B
1306 // (A + ~B) + 1 --> A - B
1307 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1308 match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
1309 return BinaryOperator::CreateSub(A, B);
1310
1311 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1312 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1313
1314 // A+B --> A|B iff A and B have no bits set in common.
1315 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
1316 return BinaryOperator::CreateOr(LHS, RHS);
1317
1318 // FIXME: We already did a check for ConstantInt RHS above this.
1319 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1320 // removal.
1321 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1322 // (X & FF00) + xx00 -> (X+xx00) & FF00
1323 Value *X;
1324 ConstantInt *C2;
1325 if (LHS->hasOneUse() &&
1326 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1327 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1328 // See if all bits from the first bit set in the Add RHS up are included
1329 // in the mask. First, get the rightmost bit.
1330 const APInt &AddRHSV = CRHS->getValue();
1331
1332 // Form a mask of all bits from the lowest bit added through the top.
1333 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1334
1335 // See if the and mask includes all of these bits.
1336 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1337
1338 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1339 // Okay, the xform is safe. Insert the new add pronto.
1340 Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
1341 return BinaryOperator::CreateAnd(NewAdd, C2);
1342 }
1343 }
1344 }
1345
1346 // add (select X 0 (sub n A)) A --> select X A n
1347 {
1348 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1349 Value *A = RHS;
1350 if (!SI) {
1351 SI = dyn_cast<SelectInst>(RHS);
1352 A = LHS;
1353 }
1354 if (SI && SI->hasOneUse()) {
1355 Value *TV = SI->getTrueValue();
1356 Value *FV = SI->getFalseValue();
1357 Value *N;
1358
1359 // Can we fold the add into the argument of the select?
1360 // We check both true and false select arguments for a matching subtract.
1361 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1362 // Fold the add into the true select value.
1363 return SelectInst::Create(SI->getCondition(), N, A);
1364
1365 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1366 // Fold the add into the false select value.
1367 return SelectInst::Create(SI->getCondition(), A, N);
1368 }
1369 }
1370
1371 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1372 return Ext;
1373
1374 // (add (xor A, B) (and A, B)) --> (or A, B)
1375 // (add (and A, B) (xor A, B)) --> (or A, B)
1376 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1377 m_c_And(m_Deferred(A), m_Deferred(B)))))
1378 return BinaryOperator::CreateOr(A, B);
1379
1380 // (add (or A, B) (and A, B)) --> (add A, B)
1381 // (add (and A, B) (or A, B)) --> (add A, B)
1382 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1383 m_c_And(m_Deferred(A), m_Deferred(B))))) {
1384 I.setOperand(0, A);
1385 I.setOperand(1, B);
1386 return &I;
1387 }
1388
1389 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1390 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1391 // computeKnownBits.
1392 bool Changed = false;
1393 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
1394 Changed = true;
1395 I.setHasNoSignedWrap(true);
1396 }
1397 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
1398 Changed = true;
1399 I.setHasNoUnsignedWrap(true);
1400 }
1401
1402 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1403 return V;
1404
1405 if (Instruction *V =
1406 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1407 I, Builder))
1408 return V;
1409
1410 if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1411 return SatAdd;
1412
1413 return Changed ? &I : nullptr;
1414}
1415
1416/// Eliminate an op from a linear interpolation (lerp) pattern.
1417static Instruction *factorizeLerp(BinaryOperator &I,
1418 InstCombiner::BuilderTy &Builder) {
1419 Value *X, *Y, *Z;
1420 if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
1421 m_OneUse(m_FSub(m_FPOne(),
1422 m_Value(Z))))),
1423 m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
1424 return nullptr;
1425
1426 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
1427 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
1428 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
1429 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
1430}
1431
1432/// Factor a common operand out of fadd/fsub of fmul/fdiv.
1433static Instruction *factorizeFAddFSub(BinaryOperator &I,
1434 InstCombiner::BuilderTy &Builder) {
1435 assert((I.getOpcode() == Instruction::FAdd ||(((I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction
::FSub) && "Expecting fadd/fsub") ? static_cast<void
> (0) : __assert_fail ("(I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub) && \"Expecting fadd/fsub\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1436, __PRETTY_FUNCTION__))
1436 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub")(((I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction
::FSub) && "Expecting fadd/fsub") ? static_cast<void
> (0) : __assert_fail ("(I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub) && \"Expecting fadd/fsub\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1436, __PRETTY_FUNCTION__))
;
1437 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&((I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF") ? static_cast<void> (
0) : __assert_fail ("I.hasAllowReassoc() && I.hasNoSignedZeros() && \"FP factorization requires FMF\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1438, __PRETTY_FUNCTION__))
1438 "FP factorization requires FMF")((I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF") ? static_cast<void> (
0) : __assert_fail ("I.hasAllowReassoc() && I.hasNoSignedZeros() && \"FP factorization requires FMF\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1438, __PRETTY_FUNCTION__))
;
1439
1440 if (Instruction *Lerp = factorizeLerp(I, Builder))
1441 return Lerp;
1442
1443 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1444 Value *X, *Y, *Z;
1445 bool IsFMul;
1446 if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
1447 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
1448 (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
1449 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
1450 IsFMul = true;
1451 else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
1452 match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
1453 IsFMul = false;
1454 else
1455 return nullptr;
1456
1457 // (X * Z) + (Y * Z) --> (X + Y) * Z
1458 // (X * Z) - (Y * Z) --> (X - Y) * Z
1459 // (X / Z) + (Y / Z) --> (X + Y) / Z
1460 // (X / Z) - (Y / Z) --> (X - Y) / Z
1461 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
1462 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
1463 : Builder.CreateFSubFMF(X, Y, &I);
1464
1465 // Bail out if we just created a denormal constant.
1466 // TODO: This is copied from a previous implementation. Is it necessary?
1467 const APFloat *C;
1468 if (match(XY, m_APFloat(C)) && !C->isNormal())
1469 return nullptr;
1470
1471 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
1472 : BinaryOperator::CreateFDivFMF(XY, Z, &I);
1473}
1474
1475Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1476 if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
1477 I.getFastMathFlags(),
1478 SQ.getWithInstruction(&I)))
1479 return replaceInstUsesWith(I, V);
1480
1481 if (SimplifyAssociativeOrCommutative(I))
1482 return &I;
1483
1484 if (Instruction *X = foldVectorBinop(I))
1485 return X;
1486
1487 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1488 return FoldedFAdd;
1489
1490 // (-X) + Y --> Y - X
1491 Value *X, *Y;
1492 if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
1493 return BinaryOperator::CreateFSubFMF(Y, X, &I);
1494
1495 // Similar to above, but look through fmul/fdiv for the negated term.
1496 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
1497 Value *Z;
1498 if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
1499 m_Value(Z)))) {
1500 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
1501 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1502 }
1503 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
1504 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
1505 if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
1506 m_Value(Z))) ||
1507 match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
1508 m_Value(Z)))) {
1509 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
1510 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1511 }
1512
1513 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1514 // integer add followed by a promotion.
1515 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1516 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1517 Value *LHSIntVal = LHSConv->getOperand(0);
1518 Type *FPType = LHSConv->getType();
1519
1520 // TODO: This check is overly conservative. In many cases known bits
1521 // analysis can tell us that the result of the addition has less significant
1522 // bits than the integer type can hold.
1523 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
1524 Type *FScalarTy = FTy->getScalarType();
1525 Type *IScalarTy = ITy->getScalarType();
1526
1527 // Do we have enough bits in the significand to represent the result of
1528 // the integer addition?
1529 unsigned MaxRepresentableBits =
1530 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1531 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
1532 };
1533
1534 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1535 // ... if the constant fits in the integer value. This is useful for things
1536 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1537 // requires a constant pool load, and generally allows the add to be better
1538 // instcombined.
1539 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1540 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1541 Constant *CI =
1542 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1543 if (LHSConv->hasOneUse() &&
1544 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1545 willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1546 // Insert the new integer add.
1547 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
1548 return new SIToFPInst(NewAdd, I.getType());
1549 }
1550 }
1551
1552 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1553 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1554 Value *RHSIntVal = RHSConv->getOperand(0);
1555 // It's enough to check LHS types only because we require int types to
1556 // be the same for this transform.
1557 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1558 // Only do this if x/y have the same type, if at least one of them has a
1559 // single use (so we don't increase the number of int->fp conversions),
1560 // and if the integer add will not overflow.
1561 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1562 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1563 willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1564 // Insert the new integer add.
1565 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
1566 return new SIToFPInst(NewAdd, I.getType());
1567 }
1568 }
1569 }
1570 }
1571
1572 // Handle specials cases for FAdd with selects feeding the operation
1573 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1574 return replaceInstUsesWith(I, V);
1575
1576 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1577 if (Instruction *F = factorizeFAddFSub(I, Builder))
1578 return F;
1579 if (Value *V = FAddCombine(Builder).simplify(&I))
1580 return replaceInstUsesWith(I, V);
1581 }
1582
1583 return nullptr;
1584}
1585
1586/// Optimize pointer differences into the same array into a size. Consider:
1587/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1588/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1589Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1590 Type *Ty) {
1591 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1592 // this.
1593 bool Swapped = false;
1594 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1595
1596 // For now we require one side to be the base pointer "A" or a constant
1597 // GEP derived from it.
1598 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1599 // (gep X, ...) - X
1600 if (LHSGEP->getOperand(0) == RHS) {
1601 GEP1 = LHSGEP;
1602 Swapped = false;
1603 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1604 // (gep X, ...) - (gep X, ...)
1605 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1606 RHSGEP->getOperand(0)->stripPointerCasts()) {
1607 GEP2 = RHSGEP;
1608 GEP1 = LHSGEP;
1609 Swapped = false;
1610 }
1611 }
1612 }
1613
1614 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1615 // X - (gep X, ...)
1616 if (RHSGEP->getOperand(0) == LHS) {
1617 GEP1 = RHSGEP;
1618 Swapped = true;
1619 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1620 // (gep X, ...) - (gep X, ...)
1621 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1622 LHSGEP->getOperand(0)->stripPointerCasts()) {
1623 GEP2 = LHSGEP;
1624 GEP1 = RHSGEP;
1625 Swapped = true;
1626 }
1627 }
1628 }
1629
1630 if (!GEP1)
1631 // No GEP found.
1632 return nullptr;
1633
1634 if (GEP2) {
1635 // (gep X, ...) - (gep X, ...)
1636 //
1637 // Avoid duplicating the arithmetic if there are more than one non-constant
1638 // indices between the two GEPs and either GEP has a non-constant index and
1639 // multiple users. If zero non-constant index, the result is a constant and
1640 // there is no duplication. If one non-constant index, the result is an add
1641 // or sub with a constant, which is no larger than the original code, and
1642 // there's no duplicated arithmetic, even if either GEP has multiple
1643 // users. If more than one non-constant indices combined, as long as the GEP
1644 // with at least one non-constant index doesn't have multiple users, there
1645 // is no duplication.
1646 unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1647 unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1648 if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1649 ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1650 (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1651 return nullptr;
1652 }
1653 }
1654
1655 // Emit the offset of the GEP and an intptr_t.
1656 Value *Result = EmitGEPOffset(GEP1);
1657
1658 // If we had a constant expression GEP on the other side offsetting the
1659 // pointer, subtract it from the offset we have.
1660 if (GEP2) {
1661 Value *Offset = EmitGEPOffset(GEP2);
1662 Result = Builder.CreateSub(Result, Offset);
1663 }
1664
1665 // If we have p - gep(p, ...) then we have to negate the result.
1666 if (Swapped)
1667 Result = Builder.CreateNeg(Result, "diff.neg");
1668
1669 return Builder.CreateIntCast(Result, Ty, true);
1670}
1671
1672Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1673 if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
1674 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1675 SQ.getWithInstruction(&I)))
1676 return replaceInstUsesWith(I, V);
1677
1678 if (Instruction *X = foldVectorBinop(I))
1679 return X;
1680
1681 // (A*B)-(A*C) -> A*(B-C) etc
1682 if (Value *V = SimplifyUsingDistributiveLaws(I))
1683 return replaceInstUsesWith(I, V);
1684
1685 // If this is a 'B = x-(-A)', change to B = x+A.
1686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1687 if (Value *V = dyn_castNegVal(Op1)) {
1688 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1689
1690 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1691 assert(BO->getOpcode() == Instruction::Sub &&((BO->getOpcode() == Instruction::Sub && "Expected a subtraction operator!"
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == Instruction::Sub && \"Expected a subtraction operator!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1692, __PRETTY_FUNCTION__))
1692 "Expected a subtraction operator!")((BO->getOpcode() == Instruction::Sub && "Expected a subtraction operator!"
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == Instruction::Sub && \"Expected a subtraction operator!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/InstCombine/InstCombineAddSub.cpp"
, 1692, __PRETTY_FUNCTION__))
;
1693 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1694 Res->setHasNoSignedWrap(true);
1695 } else {
1696 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1697 Res->setHasNoSignedWrap(true);
1698 }
1699
1700 return Res;
1701 }
1702
1703 if (I.getType()->isIntOrIntVectorTy(1))
1704 return BinaryOperator::CreateXor(Op0, Op1);
1705
1706 // Replace (-1 - A) with (~A).
1707 if (match(Op0, m_AllOnes()))
1708 return BinaryOperator::CreateNot(Op1);
1709
1710 // (~X) - (~Y) --> Y - X
1711 Value *X, *Y;
1712 if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1713 return BinaryOperator::CreateSub(Y, X);
1714
1715 // (X + -1) - Y --> ~Y + X
1716 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
1717 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
1718
1719 // Y - (X + 1) --> ~X + Y
1720 if (match(Op1, m_OneUse(m_Add(m_Value(X), m_One()))))
1721 return BinaryOperator::CreateAdd(Builder.CreateNot(X), Op0);
1722
1723 // Y - ~X --> (X + 1) + Y
1724 if (match(Op1, m_OneUse(m_Not(m_Value(X))))) {
1725 return BinaryOperator::CreateAdd(
1726 Builder.CreateAdd(Op0, ConstantInt::get(I.getType(), 1)), X);
1727 }
1728
1729 if (Constant *C = dyn_cast<Constant>(Op0)) {
1730 bool IsNegate = match(C, m_ZeroInt());
1731 Value *X;
1732 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1733 // 0 - (zext bool) --> sext bool
1734 // C - (zext bool) --> bool ? C - 1 : C
1735 if (IsNegate)
1736 return CastInst::CreateSExtOrBitCast(X, I.getType());
1737 return SelectInst::Create(X, SubOne(C), C);
1738 }
1739 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1740 // 0 - (sext bool) --> zext bool
1741 // C - (sext bool) --> bool ? C + 1 : C
1742 if (IsNegate)
1743 return CastInst::CreateZExtOrBitCast(X, I.getType());
1744 return SelectInst::Create(X, AddOne(C), C);
1745 }
1746
1747 // C - ~X == X + (1+C)
1748 if (match(Op1, m_Not(m_Value(X))))
1749 return BinaryOperator::CreateAdd(X, AddOne(C));
1750
1751 // Try to fold constant sub into select arguments.
1752 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1753 if (Instruction *R = FoldOpIntoSelect(I, SI))
1754 return R;
1755
1756 // Try to fold constant sub into PHI values.
1757 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1758 if (Instruction *R = foldOpIntoPhi(I, PN))
1759 return R;
1760
1761 Constant *C2;
1762
1763 // C-(C2-X) --> X+(C-C2)
1764 if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))))
1765 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
1766
1767 // C-(X+C2) --> (C-C2)-X
1768 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1769 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1770 }
1771
1772 const APInt *Op0C;
1773 if (match(Op0, m_APInt(Op0C))) {
1774
1775 if (Op0C->isNullValue()) {
1776 Value *Op1Wide;
1777 match(Op1, m_TruncOrSelf(m_Value(Op1Wide)));
1778 bool HadTrunc = Op1Wide != Op1;
1779 bool NoTruncOrTruncIsOneUse = !HadTrunc || Op1->hasOneUse();
1780 unsigned BitWidth = Op1Wide->getType()->getScalarSizeInBits();
1781
1782 Value *X;
1783 const APInt *ShAmt;
1784 // -(X >>u 31) -> (X >>s 31)
1785 if (NoTruncOrTruncIsOneUse &&
1786 match(Op1Wide, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1787 *ShAmt == BitWidth - 1) {
1788 Value *ShAmtOp = cast<Instruction>(Op1Wide)->getOperand(1);
1789 Instruction *NewShift = BinaryOperator::CreateAShr(X, ShAmtOp);
1790 NewShift->copyIRFlags(Op1Wide);
1791 if (!HadTrunc)
1792 return NewShift;
1793 Builder.Insert(NewShift);
1794 return TruncInst::CreateTruncOrBitCast(NewShift, Op1->getType());
1795 }
1796 // -(X >>s 31) -> (X >>u 31)
1797 if (NoTruncOrTruncIsOneUse &&
1798 match(Op1Wide, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
1799 *ShAmt == BitWidth - 1) {
1800 Value *ShAmtOp = cast<Instruction>(Op1Wide)->getOperand(1);
1801 Instruction *NewShift = BinaryOperator::CreateLShr(X, ShAmtOp);
1802 NewShift->copyIRFlags(Op1Wide);
1803 if (!HadTrunc)
1804 return NewShift;
1805 Builder.Insert(NewShift);
1806 return TruncInst::CreateTruncOrBitCast(NewShift, Op1->getType());
1807 }
1808
1809 if (!HadTrunc && Op1->hasOneUse()) {
1810 Value *LHS, *RHS;
1811 SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor;
1812 if (SPF == SPF_ABS || SPF == SPF_NABS) {
1813 // This is a negate of an ABS/NABS pattern. Just swap the operands
1814 // of the select.
1815 cast<SelectInst>(Op1)->swapValues();
1816 // Don't swap prof metadata, we didn't change the branch behavior.
1817 return replaceInstUsesWith(I, Op1);
1818 }
1819 }
1820 }
1821
1822 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1823 // zero.
1824 if (Op0C->isMask()) {
1825 KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
1826 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
1827 return BinaryOperator::CreateXor(Op1, Op0);
1828 }
1829 }
1830
1831 {
1832 Value *Y;
1833 // X-(X+Y) == -Y X-(Y+X) == -Y
1834 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
1835 return BinaryOperator::CreateNeg(Y);
1836
1837 // (X-Y)-X == -Y
1838 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1839 return BinaryOperator::CreateNeg(Y);
1840 }
1841
1842 // (sub (or A, B) (and A, B)) --> (xor A, B)
1843 {
1844 Value *A, *B;
1845 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1846 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1847 return BinaryOperator::CreateXor(A, B);
1848 }
1849
1850 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
1851 {
1852 Value *A, *B;
1853 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1854 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1855 (Op0->hasOneUse() || Op1->hasOneUse()))
1856 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
1857 }
1858
1859 // (sub (or A, B), (xor A, B)) --> (and A, B)
1860 {
1861 Value *A, *B;
1862 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1863 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1864 return BinaryOperator::CreateAnd(A, B);
1865 }
1866
1867 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
1868 {
1869 Value *A, *B;
1870 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1871 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1872 (Op0->hasOneUse() || Op1->hasOneUse()))
1873 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
1874 }
1875
1876 {
1877 Value *Y;
1878 // ((X | Y) - X) --> (~X & Y)
1879 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
1880 return BinaryOperator::CreateAnd(
1881 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
1882 }
1883
1884 if (Op1->hasOneUse()) {
1885 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1886 Constant *C = nullptr;
1887
1888 // (X - (Y - Z)) --> (X + (Z - Y)).
1889 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1890 return BinaryOperator::CreateAdd(Op0,
1891 Builder.CreateSub(Z, Y, Op1->getName()));
1892
1893 // (X - (X & Y)) --> (X & ~Y)
1894 if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
1895 return BinaryOperator::CreateAnd(Op0,
1896 Builder.CreateNot(Y, Y->getName() + ".not"));
1897
1898 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1899 // TODO: This could be extended to match arbitrary vector constants.
1900 const APInt *DivC;
1901 if (match(Op0, m_Zero()) && match(Op1, m_SDiv(m_Value(X), m_APInt(DivC))) &&
1902 !DivC->isMinSignedValue() && *DivC != 1) {
1903 Constant *NegDivC = ConstantInt::get(I.getType(), -(*DivC));
1904 Instruction *BO = BinaryOperator::CreateSDiv(X, NegDivC);
1905 BO->setIsExact(cast<BinaryOperator>(Op1)->isExact());
1906 return BO;
1907 }
1908
1909 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1910 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1911 if (Value *XNeg = dyn_castNegVal(X))
1912 return BinaryOperator::CreateShl(XNeg, Y);
1913
1914 // Subtracting -1/0 is the same as adding 1/0:
1915 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1916 // 'nuw' is dropped in favor of the canonical form.
1917 if (match(Op1, m_SExt(m_Value(Y))) &&
1918 Y->getType()->getScalarSizeInBits() == 1) {
1919 Value *Zext = Builder.CreateZExt(Y, I.getType());
1920 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1921 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1922 return Add;
1923 }
1924
1925 // X - A*-B -> X + A*B
1926 // X - -A*B -> X + A*B
1927 Value *A, *B;
1928 if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
1929 return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B));
1930
1931 // X - A*C -> X + A*-C
1932 // No need to handle commuted multiply because multiply handling will
1933 // ensure constant will be move to the right hand side.
1934 if (match(Op1, m_Mul(m_Value(A), m_Constant(C))) && !isa<ConstantExpr>(C)) {
1935 Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(C));
1936 return BinaryOperator::CreateAdd(Op0, NewMul);
1937 }
1938 }
1939
1940 {
1941 // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
1942 // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
1943 // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
1944 // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
1945 // So long as O here is freely invertible, this will be neutral or a win.
1946 Value *LHS, *RHS, *A;
1947 Value *NotA = Op0, *MinMax = Op1;
1948 SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1949 if (!SelectPatternResult::isMinOrMax(SPF)) {
1950 NotA = Op1;
1951 MinMax = Op0;
1952 SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1953 }
1954 if (SelectPatternResult::isMinOrMax(SPF) &&
1955 match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
1956 if (NotA == LHS)
1957 std::swap(LHS, RHS);
1958 // LHS is now O above and expected to have at least 2 uses (the min/max)
1959 // NotA is epected to have 2 uses from the min/max and 1 from the sub.
1960 if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
1961 !NotA->hasNUsesOrMore(4)) {
1962 // Note: We don't generate the inverse max/min, just create the not of
1963 // it and let other folds do the rest.
1964 Value *Not = Builder.CreateNot(MinMax);
1965 if (NotA == Op0)
1966 return BinaryOperator::CreateSub(Not, A);
1967 else
1968 return BinaryOperator::CreateSub(A, Not);
1969 }
1970 }
1971 }
1972
1973 // Optimize pointer differences into the same array into a size. Consider:
1974 // &A[10] - &A[0]: we should compile this to "10".
1975 Value *LHSOp, *RHSOp;
1976 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1977 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1978 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1979 return replaceInstUsesWith(I, Res);
1980
1981 // trunc(p)-trunc(q) -> trunc(p-q)
1982 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1983 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1984 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1985 return replaceInstUsesWith(I, Res);
1986
1987 // Canonicalize a shifty way to code absolute value to the common pattern.
1988 // There are 2 potential commuted variants.
1989 // We're relying on the fact that we only do this transform when the shift has
1990 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
1991 // instructions).
1992 Value *A;
1993 const APInt *ShAmt;
1994 Type *Ty = I.getType();
1995 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
1996 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
1997 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
1998 // B = ashr i32 A, 31 ; smear the sign bit
1999 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2000 // --> (A < 0) ? -A : A
2001 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
2002 // Copy the nuw/nsw flags from the sub to the negate.
2003 Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
2004 I.hasNoSignedWrap());
2005 return SelectInst::Create(Cmp, Neg, A);
2006 }
2007
2008 if (Instruction *V =
2009 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
2010 I, Builder))
2011 return V;
2012
2013 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2014 return Ext;
2015
2016 bool Changed = false;
2017 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2018 Changed = true;
2019 I.setHasNoSignedWrap(true);
2020 }
2021 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2022 Changed = true;
2023 I.setHasNoUnsignedWrap(true);
2024 }
2025
2026 return Changed ? &I : nullptr;
2027}
2028
2029/// This eliminates floating-point negation in either 'fneg(X)' or
2030/// 'fsub(-0.0, X)' form by combining into a constant operand.
2031static Instruction *foldFNegIntoConstant(Instruction &I) {
2032 Value *X;
2033 Constant *C;
2034
2035 // Fold negation into constant operand. This is limited with one-use because
2036 // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
2037 // -(X * C) --> X * (-C)
2038 // FIXME: It's arguable whether these should be m_OneUse or not. The current
2039 // belief is that the FNeg allows for better reassociation opportunities.
2040 if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
2041 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
2042 // -(X / C) --> X / (-C)
2043 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
2044 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
2045 // -(C / X) --> (-C) / X
2046 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
2047 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
2048
2049 return nullptr;
2050}
2051
2052static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
2053 InstCombiner::BuilderTy &Builder) {
2054 Value *FNeg;
2055 if (!match(&I, m_FNeg(m_Value(FNeg))))
2056 return nullptr;
2057
2058 Value *X, *Y;
2059 if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
2060 return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2061
2062 if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
2063 return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2064
2065 return nullptr;
2066}
2067
2068Instruction *InstCombiner::visitFNeg(UnaryOperator &I) {
2069 Value *Op = I.getOperand(0);
2070
2071 if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
2072 SQ.getWithInstruction(&I)))
2073 return replaceInstUsesWith(I, V);
2074
2075 if (Instruction *X = foldFNegIntoConstant(I))
2076 return X;
2077
2078 Value *X, *Y;
2079
2080 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
2081 if (I.hasNoSignedZeros() &&
2082 match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
2083 return BinaryOperator::CreateFSubFMF(Y, X, &I);
2084
2085 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2086 return R;
2087
2088 return nullptr;
2089}
2090
2091Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2092 if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
2093 I.getFastMathFlags(),
2094 SQ.getWithInstruction(&I)))
2095 return replaceInstUsesWith(I, V);
2096
2097 if (Instruction *X = foldVectorBinop(I))
2098 return X;
2099
2100 // Subtraction from -0.0 is the canonical form of fneg.
2101 // fsub nsz 0, X ==> fsub nsz -0.0, X
2102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2103 if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP()))
2104 return BinaryOperator::CreateFNegFMF(Op1, &I);
2105
2106 if (Instruction *X = foldFNegIntoConstant(I))
2107 return X;
2108
2109 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2110 return R;
2111
2112 Value *X, *Y;
2113 Constant *C;
2114
2115 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
2116 // Canonicalize to fadd to make analysis easier.
2117 // This can also help codegen because fadd is commutative.
2118 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
2119 // killed later. We still limit that particular transform with 'hasOneUse'
2120 // because an fneg is assumed better/cheaper than a generic fsub.
2121 if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
2122 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2123 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
2124 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
2125 }
2126 }
2127
2128 if (isa<Constant>(Op0))
2129 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2130 if (Instruction *NV = FoldOpIntoSelect(I, SI))
2131 return NV;
2132
2133 // X - C --> X + (-C)
2134 // But don't transform constant expressions because there's an inverse fold
2135 // for X + (-Y) --> X - Y.
2136 if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
2137 return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
2138
2139 // X - (-Y) --> X + Y
2140 if (match(Op1, m_FNeg(m_Value(Y))))
2141 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
2142
2143 // Similar to above, but look through a cast of the negated value:
2144 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
2145 Type *Ty = I.getType();
2146 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
2147 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
2148
2149 // X - (fpext(-Y)) --> X + fpext(Y)
2150 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
2151 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
2152
2153 // Similar to above, but look through fmul/fdiv of the negated value:
2154 // Op0 - (-X * Y) --> Op0 + (X * Y)
2155 // Op0 - (Y * -X) --> Op0 + (X * Y)
2156 if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
2157 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
2158 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
2159 }
2160 // Op0 - (-X / Y) --> Op0 + (X / Y)
2161 // Op0 - (X / -Y) --> Op0 + (X / Y)
2162 if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
2163 match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
2164 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
2165 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
2166 }
2167
2168 // Handle special cases for FSub with selects feeding the operation
2169 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
2170 return replaceInstUsesWith(I, V);
2171
2172 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2173 // (Y - X) - Y --> -X
2174 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
2175 return BinaryOperator::CreateFNegFMF(X, &I);
2176
2177 // Y - (X + Y) --> -X
2178 // Y - (Y + X) --> -X
2179 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
2180 return BinaryOperator::CreateFNegFMF(X, &I);
2181
2182 // (X * C) - X --> X * (C - 1.0)
2183 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
2184 Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
2185 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
2186 }
2187 // X - (X * C) --> X * (1.0 - C)
2188 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
2189 Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
2190 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
2191 }
2192
2193 if (Instruction *F = factorizeFAddFSub(I, Builder))
2194 return F;
2195
2196 // TODO: This performs reassociative folds for FP ops. Some fraction of the
2197 // functionality has been subsumed by simple pattern matching here and in
2198 // InstSimplify. We should let a dedicated reassociation pass handle more
2199 // complex pattern matching and remove this from InstCombine.
2200 if (Value *V = FAddCombine(Builder).simplify(&I))
2201 return replaceInstUsesWith(I, V);
2202 }
2203
2204 return nullptr;
2205}

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/PatternMatch.h

1//===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides a simple and efficient mechanism for performing general
10// tree-based pattern matches on the LLVM IR. The power of these routines is
11// that it allows you to write concise patterns that are expressive and easy to
12// understand. The other major advantage of this is that it allows you to
13// trivially capture/bind elements in the pattern to variables. For example,
14// you can do something like this:
15//
16// Value *Exp = ...
17// Value *X, *Y; ConstantInt *C1, *C2; // (X & C1) | (Y & C2)
18// if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
19// m_And(m_Value(Y), m_ConstantInt(C2))))) {
20// ... Pattern is matched and variables are bound ...
21// }
22//
23// This is primarily useful to things like the instruction combiner, but can
24// also be useful for static analysis tools or code generators.
25//
26//===----------------------------------------------------------------------===//
27
28#ifndef LLVM_IR_PATTERNMATCH_H
29#define LLVM_IR_PATTERNMATCH_H
30
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Support/Casting.h"
42#include <cstdint>
43
44namespace llvm {
45namespace PatternMatch {
46
47template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
48 return const_cast<Pattern &>(P).match(V);
13
Calling 'AnyBinaryOp_match::match'
33
Returning from 'AnyBinaryOp_match::match'
34
Returning the value 1, which participates in a condition later
58
Returning without writing to 'P.R.VR'
64
Passing null pointer value via 1st parameter 'V'
65
Calling 'ThreeOps_match::match'
49}
50
51template <typename SubPattern_t> struct OneUse_match {
52 SubPattern_t SubPattern;
53
54 OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
55
56 template <typename OpTy> bool match(OpTy *V) {
57 return V->hasOneUse() && SubPattern.match(V);
58 }
59};
60
61template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
62 return SubPattern;
63}
64
65template <typename Class> struct class_match {
66 template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
67};
68
69/// Match an arbitrary value and ignore it.
70inline class_match<Value> m_Value() { return class_match<Value>(); }
71
72/// Match an arbitrary binary operation and ignore it.
73inline class_match<BinaryOperator> m_BinOp() {
74 return class_match<BinaryOperator>();
75}
76
77/// Matches any compare instruction and ignore it.
78inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
79
80/// Match an arbitrary ConstantInt and ignore it.
81inline class_match<ConstantInt> m_ConstantInt() {
82 return class_match<ConstantInt>();
83}
84
85/// Match an arbitrary undef constant.
86inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
87
88/// Match an arbitrary Constant and ignore it.
89inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
90
91/// Match an arbitrary basic block value and ignore it.
92inline class_match<BasicBlock> m_BasicBlock() {
93 return class_match<BasicBlock>();
94}
95
96/// Inverting matcher
97template <typename Ty> struct match_unless {
98 Ty M;
99
100 match_unless(const Ty &Matcher) : M(Matcher) {}
101
102 template <typename ITy> bool match(ITy *V) { return !M.match(V); }
103};
104
105/// Match if the inner matcher does *NOT* match.
106template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) {
107 return match_unless<Ty>(M);
108}
109
110/// Matching combinators
111template <typename LTy, typename RTy> struct match_combine_or {
112 LTy L;
113 RTy R;
114
115 match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
116
117 template <typename ITy> bool match(ITy *V) {
118 if (L.match(V))
17
Taking false branch
119 return true;
120 if (R.match(V))
18
Calling 'match_combine_and::match'
29
Returning from 'match_combine_and::match'
30
Taking true branch
121 return true;
122 return false;
123 }
124};
125
126template <typename LTy, typename RTy> struct match_combine_and {
127 LTy L;
128 RTy R;
129
130 match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
131
132 template <typename ITy> bool match(ITy *V) {
133 if (L.match(V))
19
Calling 'BinaryOp_match::match'
26
Returning from 'BinaryOp_match::match'
27
Taking true branch
134 if (R.match(V))
28
Taking true branch
135 return true;
136 return false;
137 }
138};
139
140/// Combine two pattern matchers matching L || R
141template <typename LTy, typename RTy>
142inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
143 return match_combine_or<LTy, RTy>(L, R);
53
Returning without writing to 'L.Op.VR'
144}
145
146/// Combine two pattern matchers matching L && R
147template <typename LTy, typename RTy>
148inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
149 return match_combine_and<LTy, RTy>(L, R);
150}
151
152struct apint_match {
153 const APInt *&Res;
154
155 apint_match(const APInt *&R) : Res(R) {}
156
157 template <typename ITy> bool match(ITy *V) {
158 if (auto *CI = dyn_cast<ConstantInt>(V)) {
159 Res = &CI->getValue();
160 return true;
161 }
162 if (V->getType()->isVectorTy())
163 if (const auto *C = dyn_cast<Constant>(V))
164 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
165 Res = &CI->getValue();
166 return true;
167 }
168 return false;
169 }
170};
171// Either constexpr if or renaming ConstantFP::getValueAPF to
172// ConstantFP::getValue is needed to do it via single template
173// function for both apint/apfloat.
174struct apfloat_match {
175 const APFloat *&Res;
176 apfloat_match(const APFloat *&R) : Res(R) {}
177 template <typename ITy> bool match(ITy *V) {
178 if (auto *CI = dyn_cast<ConstantFP>(V)) {
179 Res = &CI->getValueAPF();
180 return true;
181 }
182 if (V->getType()->isVectorTy())
183 if (const auto *C = dyn_cast<Constant>(V))
184 if (auto *CI = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) {
185 Res = &CI->getValueAPF();
186 return true;
187 }
188 return false;
189 }
190};
191
192/// Match a ConstantInt or splatted ConstantVector, binding the
193/// specified pointer to the contained APInt.
194inline apint_match m_APInt(const APInt *&Res) { return Res; }
195
196/// Match a ConstantFP or splatted ConstantVector, binding the
197/// specified pointer to the contained APFloat.
198inline apfloat_match m_APFloat(const APFloat *&Res) { return Res; }
199
200template <int64_t Val> struct constantint_match {
201 template <typename ITy> bool match(ITy *V) {
202 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
203 const APInt &CIV = CI->getValue();
204 if (Val >= 0)
205 return CIV == static_cast<uint64_t>(Val);
206 // If Val is negative, and CI is shorter than it, truncate to the right
207 // number of bits. If it is larger, then we have to sign extend. Just
208 // compare their negated values.
209 return -CIV == -Val;
210 }
211 return false;
212 }
213};
214
215/// Match a ConstantInt with a specific value.
216template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
217 return constantint_match<Val>();
218}
219
220/// This helper class is used to match scalar and vector integer constants that
221/// satisfy a specified predicate.
222/// For vector constants, undefined elements are ignored.
223template <typename Predicate> struct cst_pred_ty : public Predicate {
224 template <typename ITy> bool match(ITy *V) {
225 if (const auto *CI = dyn_cast<ConstantInt>(V))
226 return this->isValue(CI->getValue());
227 if (V->getType()->isVectorTy()) {
228 if (const auto *C = dyn_cast<Constant>(V)) {
229 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
230 return this->isValue(CI->getValue());
231
232 // Non-splat vector constant: check each element for a match.
233 unsigned NumElts = V->getType()->getVectorNumElements();
234 assert(NumElts != 0 && "Constant vector with no elements?")((NumElts != 0 && "Constant vector with no elements?"
) ? static_cast<void> (0) : __assert_fail ("NumElts != 0 && \"Constant vector with no elements?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/PatternMatch.h"
, 234, __PRETTY_FUNCTION__))
;
235 bool HasNonUndefElements = false;
236 for (unsigned i = 0; i != NumElts; ++i) {
237 Constant *Elt = C->getAggregateElement(i);
238 if (!Elt)
239 return false;
240 if (isa<UndefValue>(Elt))
241 continue;
242 auto *CI = dyn_cast<ConstantInt>(Elt);
243 if (!CI || !this->isValue(CI->getValue()))
244 return false;
245 HasNonUndefElements = true;
246 }
247 return HasNonUndefElements;
248 }
249 }
250 return false;
251 }
252};
253
254/// This helper class is used to match scalar and vector constants that
255/// satisfy a specified predicate, and bind them to an APInt.
256template <typename Predicate> struct api_pred_ty : public Predicate {
257 const APInt *&Res;
258
259 api_pred_ty(const APInt *&R) : Res(R) {}
260
261 template <typename ITy> bool match(ITy *V) {
262 if (const auto *CI = dyn_cast<ConstantInt>(V))
263 if (this->isValue(CI->getValue())) {
264 Res = &CI->getValue();
265 return true;
266 }
267 if (V->getType()->isVectorTy())
268 if (const auto *C = dyn_cast<Constant>(V))
269 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
270 if (this->isValue(CI->getValue())) {
271 Res = &CI->getValue();
272 return true;
273 }
274
275 return false;
276 }
277};
278
279/// This helper class is used to match scalar and vector floating-point
280/// constants that satisfy a specified predicate.
281/// For vector constants, undefined elements are ignored.
282template <typename Predicate> struct cstfp_pred_ty : public Predicate {
283 template <typename ITy> bool match(ITy *V) {
284 if (const auto *CF = dyn_cast<ConstantFP>(V))
285 return this->isValue(CF->getValueAPF());
286 if (V->getType()->isVectorTy()) {
287 if (const auto *C = dyn_cast<Constant>(V)) {
288 if (const auto *CF = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
289 return this->isValue(CF->getValueAPF());
290
291 // Non-splat vector constant: check each element for a match.
292 unsigned NumElts = V->getType()->getVectorNumElements();
293 assert(NumElts != 0 && "Constant vector with no elements?")((NumElts != 0 && "Constant vector with no elements?"
) ? static_cast<void> (0) : __assert_fail ("NumElts != 0 && \"Constant vector with no elements?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/PatternMatch.h"
, 293, __PRETTY_FUNCTION__))
;
294 bool HasNonUndefElements = false;
295 for (unsigned i = 0; i != NumElts; ++i) {
296 Constant *Elt = C->getAggregateElement(i);
297 if (!Elt)
298 return false;
299 if (isa<UndefValue>(Elt))
300 continue;
301 auto *CF = dyn_cast<ConstantFP>(Elt);
302 if (!CF || !this->isValue(CF->getValueAPF()))
303 return false;
304 HasNonUndefElements = true;
305 }
306 return HasNonUndefElements;
307 }
308 }
309 return false;
310 }
311};
312
313///////////////////////////////////////////////////////////////////////////////
314//
315// Encapsulate constant value queries for use in templated predicate matchers.
316// This allows checking if constants match using compound predicates and works
317// with vector constants, possibly with relaxed constraints. For example, ignore
318// undef values.
319//
320///////////////////////////////////////////////////////////////////////////////
321
322struct is_any_apint {
323 bool isValue(const APInt &C) { return true; }
324};
325/// Match an integer or vector with any integral constant.
326/// For vectors, this includes constants with undefined elements.
327inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() {
328 return cst_pred_ty<is_any_apint>();
329}
330
331struct is_all_ones {
332 bool isValue(const APInt &C) { return C.isAllOnesValue(); }
333};
334/// Match an integer or vector with all bits set.
335/// For vectors, this includes constants with undefined elements.
336inline cst_pred_ty<is_all_ones> m_AllOnes() {
337 return cst_pred_ty<is_all_ones>();
338}
339
340struct is_maxsignedvalue {
341 bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
342};
343/// Match an integer or vector with values having all bits except for the high
344/// bit set (0x7f...).
345/// For vectors, this includes constants with undefined elements.
346inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
347 return cst_pred_ty<is_maxsignedvalue>();
348}
349inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
350 return V;
351}
352
353struct is_negative {
354 bool isValue(const APInt &C) { return C.isNegative(); }
355};
356/// Match an integer or vector of negative values.
357/// For vectors, this includes constants with undefined elements.
358inline cst_pred_ty<is_negative> m_Negative() {
359 return cst_pred_ty<is_negative>();
360}
361inline api_pred_ty<is_negative> m_Negative(const APInt *&V) {
362 return V;
363}
364
365struct is_nonnegative {
366 bool isValue(const APInt &C) { return C.isNonNegative(); }
367};
368/// Match an integer or vector of nonnegative values.
369/// For vectors, this includes constants with undefined elements.
370inline cst_pred_ty<is_nonnegative> m_NonNegative() {
371 return cst_pred_ty<is_nonnegative>();
372}
373inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) {
374 return V;
375}
376
377struct is_one {
378 bool isValue(const APInt &C) { return C.isOneValue(); }
379};
380/// Match an integer 1 or a vector with all elements equal to 1.
381/// For vectors, this includes constants with undefined elements.
382inline cst_pred_ty<is_one> m_One() {
383 return cst_pred_ty<is_one>();
384}
385
386struct is_zero_int {
387 bool isValue(const APInt &C) { return C.isNullValue(); }
388};
389/// Match an integer 0 or a vector with all elements equal to 0.
390/// For vectors, this includes constants with undefined elements.
391inline cst_pred_ty<is_zero_int> m_ZeroInt() {
392 return cst_pred_ty<is_zero_int>();
393}
394
395struct is_zero {
396 template <typename ITy> bool match(ITy *V) {
397 auto *C = dyn_cast<Constant>(V);
398 return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
399 }
400};
401/// Match any null constant or a vector with all elements equal to 0.
402/// For vectors, this includes constants with undefined elements.
403inline is_zero m_Zero() {
404 return is_zero();
405}
406
407struct is_power2 {
408 bool isValue(const APInt &C) { return C.isPowerOf2(); }
409};
410/// Match an integer or vector power-of-2.
411/// For vectors, this includes constants with undefined elements.
412inline cst_pred_ty<is_power2> m_Power2() {
413 return cst_pred_ty<is_power2>();
414}
415inline api_pred_ty<is_power2> m_Power2(const APInt *&V) {
416 return V;
417}
418
419struct is_negated_power2 {
420 bool isValue(const APInt &C) { return (-C).isPowerOf2(); }
421};
422/// Match a integer or vector negated power-of-2.
423/// For vectors, this includes constants with undefined elements.
424inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
425 return cst_pred_ty<is_negated_power2>();
426}
427inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
428 return V;
429}
430
431struct is_power2_or_zero {
432 bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
433};
434/// Match an integer or vector of 0 or power-of-2 values.
435/// For vectors, this includes constants with undefined elements.
436inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
437 return cst_pred_ty<is_power2_or_zero>();
438}
439inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
440 return V;
441}
442
443struct is_sign_mask {
444 bool isValue(const APInt &C) { return C.isSignMask(); }
445};
446/// Match an integer or vector with only the sign bit(s) set.
447/// For vectors, this includes constants with undefined elements.
448inline cst_pred_ty<is_sign_mask> m_SignMask() {
449 return cst_pred_ty<is_sign_mask>();
450}
451
452struct is_lowbit_mask {
453 bool isValue(const APInt &C) { return C.isMask(); }
454};
455/// Match an integer or vector with only the low bit(s) set.
456/// For vectors, this includes constants with undefined elements.
457inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
458 return cst_pred_ty<is_lowbit_mask>();
459}
460
461struct icmp_pred_with_threshold {
462 ICmpInst::Predicate Pred;
463 const APInt *Thr;
464 bool isValue(const APInt &C) {
465 switch (Pred) {
466 case ICmpInst::Predicate::ICMP_EQ:
467 return C.eq(*Thr);
468 case ICmpInst::Predicate::ICMP_NE:
469 return C.ne(*Thr);
470 case ICmpInst::Predicate::ICMP_UGT:
471 return C.ugt(*Thr);
472 case ICmpInst::Predicate::ICMP_UGE:
473 return C.uge(*Thr);
474 case ICmpInst::Predicate::ICMP_ULT:
475 return C.ult(*Thr);
476 case ICmpInst::Predicate::ICMP_ULE:
477 return C.ule(*Thr);
478 case ICmpInst::Predicate::ICMP_SGT:
479 return C.sgt(*Thr);
480 case ICmpInst::Predicate::ICMP_SGE:
481 return C.sge(*Thr);
482 case ICmpInst::Predicate::ICMP_SLT:
483 return C.slt(*Thr);
484 case ICmpInst::Predicate::ICMP_SLE:
485 return C.sle(*Thr);
486 default:
487 llvm_unreachable("Unhandled ICmp predicate")::llvm::llvm_unreachable_internal("Unhandled ICmp predicate",
"/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/PatternMatch.h"
, 487)
;
488 }
489 }
490};
491/// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
492/// to Threshold. For vectors, this includes constants with undefined elements.
493inline cst_pred_ty<icmp_pred_with_threshold>
494m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
495 cst_pred_ty<icmp_pred_with_threshold> P;
496 P.Pred = Predicate;
497 P.Thr = &Threshold;
498 return P;
499}
500
501struct is_nan {
502 bool isValue(const APFloat &C) { return C.isNaN(); }
503};
504/// Match an arbitrary NaN constant. This includes quiet and signalling nans.
505/// For vectors, this includes constants with undefined elements.
506inline cstfp_pred_ty<is_nan> m_NaN() {
507 return cstfp_pred_ty<is_nan>();
508}
509
510struct is_any_zero_fp {
511 bool isValue(const APFloat &C) { return C.isZero(); }
512};
513/// Match a floating-point negative zero or positive zero.
514/// For vectors, this includes constants with undefined elements.
515inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
516 return cstfp_pred_ty<is_any_zero_fp>();
517}
518
519struct is_pos_zero_fp {
520 bool isValue(const APFloat &C) { return C.isPosZero(); }
521};
522/// Match a floating-point positive zero.
523/// For vectors, this includes constants with undefined elements.
524inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
525 return cstfp_pred_ty<is_pos_zero_fp>();
526}
527
528struct is_neg_zero_fp {
529 bool isValue(const APFloat &C) { return C.isNegZero(); }
530};
531/// Match a floating-point negative zero.
532/// For vectors, this includes constants with undefined elements.
533inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
534 return cstfp_pred_ty<is_neg_zero_fp>();
535}
536
537///////////////////////////////////////////////////////////////////////////////
538
539template <typename Class> struct bind_ty {
540 Class *&VR;
541
542 bind_ty(Class *&V) : VR(V) {}
543
544 template <typename ITy> bool match(ITy *V) {
545 if (auto *CV = dyn_cast<Class>(V)) {
546 VR = CV;
547 return true;
548 }
549 return false;
550 }
551};
552
553/// Match a value, capturing it if we match.
554inline bind_ty<Value> m_Value(Value *&V) { return V; }
5
Calling constructor for 'bind_ty<llvm::Value>'
6
Returning from constructor for 'bind_ty<llvm::Value>'
7
Returning without writing to 'V'
46
Returning without writing to 'V'
555inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
556
557/// Match an instruction, capturing it if we match.
558inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
559/// Match a binary operator, capturing it if we match.
560inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
561
562/// Match a ConstantInt, capturing the value if we match.
563inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
564
565/// Match a Constant, capturing the value if we match.
566inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
567
568/// Match a ConstantFP, capturing the value if we match.
569inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
570
571/// Match a basic block value, capturing it if we match.
572inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
573inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
574 return V;
575}
576
577/// Match a specified Value*.
578struct specificval_ty {
579 const Value *Val;
580
581 specificval_ty(const Value *V) : Val(V) {}
582
583 template <typename ITy> bool match(ITy *V) { return V == Val; }
584};
585
586/// Match if we have a specific specified value.
587inline specificval_ty m_Specific(const Value *V) { return V; }
588
589/// Stores a reference to the Value *, not the Value * itself,
590/// thus can be used in commutative matchers.
591template <typename Class> struct deferredval_ty {
592 Class *const &Val;
593
594 deferredval_ty(Class *const &V) : Val(V) {}
595
596 template <typename ITy> bool match(ITy *const V) { return V == Val; }
597};
598
599/// A commutative-friendly version of m_Specific().
600inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
601inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
602 return V;
603}
604
605/// Match a specified floating point value or vector of all elements of
606/// that value.
607struct specific_fpval {
608 double Val;
609
610 specific_fpval(double V) : Val(V) {}
611
612 template <typename ITy> bool match(ITy *V) {
613 if (const auto *CFP = dyn_cast<ConstantFP>(V))
614 return CFP->isExactlyValue(Val);
615 if (V->getType()->isVectorTy())
616 if (const auto *C = dyn_cast<Constant>(V))
617 if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
618 return CFP->isExactlyValue(Val);
619 return false;
620 }
621};
622
623/// Match a specific floating point value or vector with all elements
624/// equal to the value.
625inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
626
627/// Match a float 1.0 or vector with all elements equal to 1.0.
628inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
629
630struct bind_const_intval_ty {
631 uint64_t &VR;
632
633 bind_const_intval_ty(uint64_t &V) : VR(V) {}
634
635 template <typename ITy> bool match(ITy *V) {
636 if (const auto *CV = dyn_cast<ConstantInt>(V))
637 if (CV->getValue().ule(UINT64_MAX(18446744073709551615UL))) {
638 VR = CV->getZExtValue();
639 return true;
640 }
641 return false;
642 }
643};
644
645/// Match a specified integer value or vector of all elements of that
646/// value.
647struct specific_intval {
648 APInt Val;
649
650 specific_intval(APInt V) : Val(std::move(V)) {}
651
652 template <typename ITy> bool match(ITy *V) {
653 const auto *CI = dyn_cast<ConstantInt>(V);
654 if (!CI && V->getType()->isVectorTy())
655 if (const auto *C = dyn_cast<Constant>(V))
656 CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue());
657
658 return CI && APInt::isSameValue(CI->getValue(), Val);
659 }
660};
661
662/// Match a specific integer value or vector with all elements equal to
663/// the value.
664inline specific_intval m_SpecificInt(APInt V) {
665 return specific_intval(std::move(V));
666}
667
668inline specific_intval m_SpecificInt(uint64_t V) {
669 return m_SpecificInt(APInt(64, V));
670}
671
672/// Match a ConstantInt and bind to its value. This does not match
673/// ConstantInts wider than 64-bits.
674inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
675
676/// Match a specified basic block value.
677struct specific_bbval {
678 BasicBlock *Val;
679
680 specific_bbval(BasicBlock *Val) : Val(Val) {}
681
682 template <typename ITy> bool match(ITy *V) {
683 const auto *BB = dyn_cast<BasicBlock>(V);
684 return BB && BB == Val;
685 }
686};
687
688/// Match a specific basic block value.
689inline specific_bbval m_SpecificBB(BasicBlock *BB) {
690 return specific_bbval(BB);
691}
692
693/// A commutative-friendly version of m_Specific().
694inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
695 return BB;
696}
697inline deferredval_ty<const BasicBlock>
698m_Deferred(const BasicBlock *const &BB) {
699 return BB;
700}
701
702//===----------------------------------------------------------------------===//
703// Matcher for any binary operator.
704//
705template <typename LHS_t, typename RHS_t, bool Commutable = false>
706struct AnyBinaryOp_match {
707 LHS_t L;
708 RHS_t R;
709
710 // The evaluation order is always stable, regardless of Commutability.
711 // The LHS is always matched first.
712 AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
713
714 template <typename OpTy> bool match(OpTy *V) {
715 if (auto *I
14.1
'I' is non-null
14.1
'I' is non-null
= dyn_cast<BinaryOperator>(V))
14
Assuming 'V' is a 'BinaryOperator'
15
Taking true branch
716 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
16
Calling 'match_combine_or::match'
31
Returning from 'match_combine_or::match'
32
Returning the value 1, which participates in a condition later
717 (Commutable && L.match(I->getOperand(1)) &&
718 R.match(I->getOperand(0)));
719 return false;
720 }
721};
722
723template <typename LHS, typename RHS>
724inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
725 return AnyBinaryOp_match<LHS, RHS>(L, R);
726}
727
728//===----------------------------------------------------------------------===//
729// Matchers for specific binary operators.
730//
731
732template <typename LHS_t, typename RHS_t, unsigned Opcode,
733 bool Commutable = false>
734struct BinaryOp_match {
735 LHS_t L;
736 RHS_t R;
737
738 // The evaluation order is always stable, regardless of Commutability.
739 // The LHS is always matched first.
740 BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
741
742 template <typename OpTy> bool match(OpTy *V) {
743 if (V->getValueID() == Value::InstructionVal + Opcode) {
20
Assuming the condition is true
21
Taking true branch
744 auto *I = cast<BinaryOperator>(V);
22
'V' is a 'BinaryOperator'
745 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
23
Value assigned to 'Select'
24
Assuming the condition is true
25
Assuming the condition is true
746 (Commutable && L.match(I->getOperand(1)) &&
747 R.match(I->getOperand(0)));
748 }
749 if (auto *CE = dyn_cast<ConstantExpr>(V))
750 return CE->getOpcode() == Opcode &&
751 ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) ||
752 (Commutable && L.match(CE->getOperand(1)) &&
753 R.match(CE->getOperand(0))));
754 return false;
755 }
756};
757
758template <typename LHS, typename RHS>
759inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
760 const RHS &R) {
761 return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
762}
763
764template <typename LHS, typename RHS>
765inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
766 const RHS &R) {
767 return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
768}
769
770template <typename LHS, typename RHS>
771inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
772 const RHS &R) {
773 return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
774}
775
776template <typename LHS, typename RHS>
777inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
778 const RHS &R) {
779 return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
780}
781
782template <typename Op_t> struct FNeg_match {
783 Op_t X;
784
785 FNeg_match(const Op_t &Op) : X(Op) {}
786 template <typename OpTy> bool match(OpTy *V) {
787 auto *FPMO = dyn_cast<FPMathOperator>(V);
788 if (!FPMO) return false;
789
790 if (FPMO->getOpcode() == Instruction::FNeg)
791 return X.match(FPMO->getOperand(0));
792
793 if (FPMO->getOpcode() == Instruction::FSub) {
794 if (FPMO->hasNoSignedZeros()) {
795 // With 'nsz', any zero goes.
796 if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
797 return false;
798 } else {
799 // Without 'nsz', we need fsub -0.0, X exactly.
800 if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
801 return false;
802 }
803
804 return X.match(FPMO->getOperand(1));
805 }
806
807 return false;
808 }
809};
810
811/// Match 'fneg X' as 'fsub -0.0, X'.
812template <typename OpTy>
813inline FNeg_match<OpTy>
814m_FNeg(const OpTy &X) {
815 return FNeg_match<OpTy>(X);
816}
817
818/// Match 'fneg X' as 'fsub +-0.0, X'.
819template <typename RHS>
820inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
821m_FNegNSZ(const RHS &X) {
822 return m_FSub(m_AnyZeroFP(), X);
823}
824
825template <typename LHS, typename RHS>
826inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
827 const RHS &R) {
828 return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
829}
830
831template <typename LHS, typename RHS>
832inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
833 const RHS &R) {
834 return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
835}
836
837template <typename LHS, typename RHS>
838inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
839 const RHS &R) {
840 return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
841}
842
843template <typename LHS, typename RHS>
844inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
845 const RHS &R) {
846 return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
847}
848
849template <typename LHS, typename RHS>
850inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
851 const RHS &R) {
852 return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
853}
854
855template <typename LHS, typename RHS>
856inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
857 const RHS &R) {
858 return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
859}
860
861template <typename LHS, typename RHS>
862inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
863 const RHS &R) {
864 return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
865}
866
867template <typename LHS, typename RHS>
868inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
869 const RHS &R) {
870 return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
871}
872
873template <typename LHS, typename RHS>
874inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
875 const RHS &R) {
876 return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
877}
878
879template <typename LHS, typename RHS>
880inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
881 const RHS &R) {
882 return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
883}
884
885template <typename LHS, typename RHS>
886inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
887 const RHS &R) {
888 return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
889}
890
891template <typename LHS, typename RHS>
892inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
893 const RHS &R) {
894 return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
895}
896
897template <typename LHS, typename RHS>
898inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
899 const RHS &R) {
900 return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
901}
902
903template <typename LHS, typename RHS>
904inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
905 const RHS &R) {
906 return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
907}
908
909template <typename LHS_t, typename RHS_t, unsigned Opcode,
910 unsigned WrapFlags = 0>
911struct OverflowingBinaryOp_match {
912 LHS_t L;
913 RHS_t R;
914
915 OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
916 : L(LHS), R(RHS) {}
917
918 template <typename OpTy> bool match(OpTy *V) {
919 if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
920 if (Op->getOpcode() != Opcode)
921 return false;
922 if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap &&
923 !Op->hasNoUnsignedWrap())
924 return false;
925 if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap &&
926 !Op->hasNoSignedWrap())
927 return false;
928 return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
929 }
930 return false;
931 }
932};
933
934template <typename LHS, typename RHS>
935inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
936 OverflowingBinaryOperator::NoSignedWrap>
937m_NSWAdd(const LHS &L, const RHS &R) {
938 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
939 OverflowingBinaryOperator::NoSignedWrap>(
940 L, R);
941}
942template <typename LHS, typename RHS>
943inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
944 OverflowingBinaryOperator::NoSignedWrap>
945m_NSWSub(const LHS &L, const RHS &R) {
946 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
947 OverflowingBinaryOperator::NoSignedWrap>(
948 L, R);
949}
950template <typename LHS, typename RHS>
951inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
952 OverflowingBinaryOperator::NoSignedWrap>
953m_NSWMul(const LHS &L, const RHS &R) {
954 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
955 OverflowingBinaryOperator::NoSignedWrap>(
956 L, R);
957}
958template <typename LHS, typename RHS>
959inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
960 OverflowingBinaryOperator::NoSignedWrap>
961m_NSWShl(const LHS &L, const RHS &R) {
962 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
963 OverflowingBinaryOperator::NoSignedWrap>(
964 L, R);
965}
966
967template <typename LHS, typename RHS>
968inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
969 OverflowingBinaryOperator::NoUnsignedWrap>
970m_NUWAdd(const LHS &L, const RHS &R) {
971 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
972 OverflowingBinaryOperator::NoUnsignedWrap>(
973 L, R);
974}
975template <typename LHS, typename RHS>
976inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
977 OverflowingBinaryOperator::NoUnsignedWrap>
978m_NUWSub(const LHS &L, const RHS &R) {
979 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
980 OverflowingBinaryOperator::NoUnsignedWrap>(
981 L, R);
982}
983template <typename LHS, typename RHS>
984inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
985 OverflowingBinaryOperator::NoUnsignedWrap>
986m_NUWMul(const LHS &L, const RHS &R) {
987 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
988 OverflowingBinaryOperator::NoUnsignedWrap>(
989 L, R);
990}
991template <typename LHS, typename RHS>
992inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
993 OverflowingBinaryOperator::NoUnsignedWrap>
994m_NUWShl(const LHS &L, const RHS &R) {
995 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
996 OverflowingBinaryOperator::NoUnsignedWrap>(
997 L, R);
998}
999
1000//===----------------------------------------------------------------------===//
1001// Class that matches a group of binary opcodes.
1002//
1003template <typename LHS_t, typename RHS_t, typename Predicate>
1004struct BinOpPred_match : Predicate {
1005 LHS_t L;
1006 RHS_t R;
1007
1008 BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1009
1010 template <typename OpTy> bool match(OpTy *V) {
1011 if (auto *I = dyn_cast<Instruction>(V))
1012 return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
1013 R.match(I->getOperand(1));
1014 if (auto *CE = dyn_cast<ConstantExpr>(V))
1015 return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) &&
1016 R.match(CE->getOperand(1));
1017 return false;
1018 }
1019};
1020
1021struct is_shift_op {
1022 bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1023};
1024
1025struct is_right_shift_op {
1026 bool isOpType(unsigned Opcode) {
1027 return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1028 }
1029};
1030
1031struct is_logical_shift_op {
1032 bool isOpType(unsigned Opcode) {
1033 return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1034 }
1035};
1036
1037struct is_bitwiselogic_op {
1038 bool isOpType(unsigned Opcode) {
1039 return Instruction::isBitwiseLogicOp(Opcode);
1040 }
1041};
1042
1043struct is_idiv_op {
1044 bool isOpType(unsigned Opcode) {
1045 return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1046 }
1047};
1048
1049struct is_irem_op {
1050 bool isOpType(unsigned Opcode) {
1051 return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1052 }
1053};
1054
1055/// Matches shift operations.
1056template <typename LHS, typename RHS>
1057inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1058 const RHS &R) {
1059 return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1060}
1061
1062/// Matches logical shift operations.
1063template <typename LHS, typename RHS>
1064inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1065 const RHS &R) {
1066 return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1067}
1068
1069/// Matches logical shift operations.
1070template <typename LHS, typename RHS>
1071inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
1072m_LogicalShift(const LHS &L, const RHS &R) {
1073 return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1074}
1075
1076/// Matches bitwise logic operations.
1077template <typename LHS, typename RHS>
1078inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
1079m_BitwiseLogic(const LHS &L, const RHS &R) {
1080 return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1081}
1082
1083/// Matches integer division operations.
1084template <typename LHS, typename RHS>
1085inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1086 const RHS &R) {
1087 return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1088}
1089
1090/// Matches integer remainder operations.
1091template <typename LHS, typename RHS>
1092inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1093 const RHS &R) {
1094 return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1095}
1096
1097//===----------------------------------------------------------------------===//
1098// Class that matches exact binary ops.
1099//
1100template <typename SubPattern_t> struct Exact_match {
1101 SubPattern_t SubPattern;
1102
1103 Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1104
1105 template <typename OpTy> bool match(OpTy *V) {
1106 if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1107 return PEO->isExact() && SubPattern.match(V);
1108 return false;
1109 }
1110};
1111
1112template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1113 return SubPattern;
1114}
1115
1116//===----------------------------------------------------------------------===//
1117// Matchers for CmpInst classes
1118//
1119
1120template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1121 bool Commutable = false>
1122struct CmpClass_match {
1123 PredicateTy &Predicate;
1124 LHS_t L;
1125 RHS_t R;
1126
1127 // The evaluation order is always stable, regardless of Commutability.
1128 // The LHS is always matched first.
1129 CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1130 : Predicate(Pred), L(LHS), R(RHS) {}
1131
1132 template <typename OpTy> bool match(OpTy *V) {
1133 if (auto *I = dyn_cast<Class>(V))
1134 if ((L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
1135 (Commutable && L.match(I->getOperand(1)) &&
1136 R.match(I->getOperand(0)))) {
1137 Predicate = I->getPredicate();
1138 return true;
1139 }
1140 return false;
1141 }
1142};
1143
1144template <typename LHS, typename RHS>
1145inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1146m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1147 return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1148}
1149
1150template <typename LHS, typename RHS>
1151inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1152m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1153 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1154}
1155
1156template <typename LHS, typename RHS>
1157inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1158m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1159 return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1160}
1161
1162//===----------------------------------------------------------------------===//
1163// Matchers for instructions with a given opcode and number of operands.
1164//
1165
1166/// Matches instructions with Opcode and three operands.
1167template <typename T0, unsigned Opcode> struct OneOps_match {
1168 T0 Op1;
1169
1170 OneOps_match(const T0 &Op1) : Op1(Op1) {}
1171
1172 template <typename OpTy> bool match(OpTy *V) {
1173 if (V->getValueID() == Value::InstructionVal + Opcode) {
1174 auto *I = cast<Instruction>(V);
1175 return Op1.match(I->getOperand(0));
1176 }
1177 return false;
1178 }
1179};
1180
1181/// Matches instructions with Opcode and three operands.
1182template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1183 T0 Op1;
1184 T1 Op2;
1185
1186 TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1187
1188 template <typename OpTy> bool match(OpTy *V) {
1189 if (V->getValueID() == Value::InstructionVal + Opcode) {
1190 auto *I = cast<Instruction>(V);
1191 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1192 }
1193 return false;
1194 }
1195};
1196
1197/// Matches instructions with Opcode and three operands.
1198template <typename T0, typename T1, typename T2, unsigned Opcode>
1199struct ThreeOps_match {
1200 T0 Op1;
1201 T1 Op2;
1202 T2 Op3;
1203
1204 ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1205 : Op1(Op1), Op2(Op2), Op3(Op3) {}
1206
1207 template <typename OpTy> bool match(OpTy *V) {
1208 if (V->getValueID() == Value::InstructionVal + Opcode) {
66
Called C++ object pointer is null
1209 auto *I = cast<Instruction>(V);
1210 return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1211 Op3.match(I->getOperand(2));
1212 }
1213 return false;
1214 }
1215};
1216
1217/// Matches SelectInst.
1218template <typename Cond, typename LHS, typename RHS>
1219inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
1220m_Select(const Cond &C, const LHS &L, const RHS &R) {
1221 return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1222}
1223
1224/// This matches a select of two constants, e.g.:
1225/// m_SelectCst<-1, 0>(m_Value(V))
1226template <int64_t L, int64_t R, typename Cond>
1227inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1228 Instruction::Select>
1229m_SelectCst(const Cond &C) {
1230 return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1231}
1232
1233/// Matches InsertElementInst.
1234template <typename Val_t, typename Elt_t, typename Idx_t>
1235inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>
1236m_InsertElement(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1237 return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1238 Val, Elt, Idx);
1239}
1240
1241/// Matches ExtractElementInst.
1242template <typename Val_t, typename Idx_t>
1243inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
1244m_ExtractElement(const Val_t &Val, const Idx_t &Idx) {
1245 return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1246}
1247
1248/// Matches ShuffleVectorInst.
1249template <typename V1_t, typename V2_t, typename Mask_t>
1250inline ThreeOps_match<V1_t, V2_t, Mask_t, Instruction::ShuffleVector>
1251m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m) {
1252 return ThreeOps_match<V1_t, V2_t, Mask_t, Instruction::ShuffleVector>(v1, v2,
1253 m);
1254}
1255
1256/// Matches LoadInst.
1257template <typename OpTy>
1258inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1259 return OneOps_match<OpTy, Instruction::Load>(Op);
1260}
1261
1262/// Matches StoreInst.
1263template <typename ValueOpTy, typename PointerOpTy>
1264inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
1265m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1266 return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1267 PointerOp);
1268}
1269
1270//===----------------------------------------------------------------------===//
1271// Matchers for CastInst classes
1272//
1273
1274template <typename Op_t, unsigned Opcode> struct CastClass_match {
1275 Op_t Op;
1276
1277 CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1278
1279 template <typename OpTy> bool match(OpTy *V) {
1280 if (auto *O = dyn_cast<Operator>(V))
1281 return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1282 return false;
1283 }
1284};
1285
1286/// Matches BitCast.
1287template <typename OpTy>
1288inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
1289 return CastClass_match<OpTy, Instruction::BitCast>(Op);
1290}
1291
1292/// Matches PtrToInt.
1293template <typename OpTy>
1294inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
1295 return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
1296}
1297
1298/// Matches Trunc.
1299template <typename OpTy>
1300inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1301 return CastClass_match<OpTy, Instruction::Trunc>(Op);
1302}
1303
1304template <typename OpTy>
1305inline match_combine_or<CastClass_match<OpTy, Instruction::Trunc>, OpTy>
1306m_TruncOrSelf(const OpTy &Op) {
1307 return m_CombineOr(m_Trunc(Op), Op);
1308}
1309
1310/// Matches SExt.
1311template <typename OpTy>
1312inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
1313 return CastClass_match<OpTy, Instruction::SExt>(Op);
1314}
1315
1316/// Matches ZExt.
1317template <typename OpTy>
1318inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
1319 return CastClass_match<OpTy, Instruction::ZExt>(Op);
50
Returning without writing to 'Op.VR'
1320}
1321
1322template <typename OpTy>
1323inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, OpTy>
1324m_ZExtOrSelf(const OpTy &Op) {
1325 return m_CombineOr(m_ZExt(Op), Op);
49
Calling 'm_ZExt<llvm::PatternMatch::bind_ty<llvm::Value>>'
51
Returning from 'm_ZExt<llvm::PatternMatch::bind_ty<llvm::Value>>'
52
Calling 'm_CombineOr<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value>>'
54
Returning from 'm_CombineOr<llvm::PatternMatch::CastClass_match<llvm::PatternMatch::bind_ty<llvm::Value>, 39>, llvm::PatternMatch::bind_ty<llvm::Value>>'
55
Returning without writing to 'Op.VR'
1326}
1327
1328template <typename OpTy>
1329inline match_combine_or<CastClass_match<OpTy, Instruction::SExt>, OpTy>
1330m_SExtOrSelf(const OpTy &Op) {
1331 return m_CombineOr(m_SExt(Op), Op);
1332}
1333
1334template <typename OpTy>
1335inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1336 CastClass_match<OpTy, Instruction::SExt>>
1337m_ZExtOrSExt(const OpTy &Op) {
1338 return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1339}
1340
1341template <typename OpTy>
1342inline match_combine_or<
1343 match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1344 CastClass_match<OpTy, Instruction::SExt>>,
1345 OpTy>
1346m_ZExtOrSExtOrSelf(const OpTy &Op) {
1347 return m_CombineOr(m_ZExtOrSExt(Op), Op);
1348}
1349
1350/// Matches UIToFP.
1351template <typename OpTy>
1352inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
1353 return CastClass_match<OpTy, Instruction::UIToFP>(Op);
1354}
1355
1356/// Matches SIToFP.
1357template <typename OpTy>
1358inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
1359 return CastClass_match<OpTy, Instruction::SIToFP>(Op);
1360}
1361
1362/// Matches FPTrunc
1363template <typename OpTy>
1364inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
1365 return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
1366}
1367
1368/// Matches FPExt
1369template <typename OpTy>
1370inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
1371 return CastClass_match<OpTy, Instruction::FPExt>(Op);
1372}
1373
1374//===----------------------------------------------------------------------===//
1375// Matchers for control flow.
1376//
1377
1378struct br_match {
1379 BasicBlock *&Succ;
1380
1381 br_match(BasicBlock *&Succ) : Succ(Succ) {}
1382
1383 template <typename OpTy> bool match(OpTy *V) {
1384 if (auto *BI = dyn_cast<BranchInst>(V))
1385 if (BI->isUnconditional()) {
1386 Succ = BI->getSuccessor(0);
1387 return true;
1388 }
1389 return false;
1390 }
1391};
1392
1393inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1394
1395template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1396struct brc_match {
1397 Cond_t Cond;
1398 TrueBlock_t T;
1399 FalseBlock_t F;
1400
1401 brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
1402 : Cond(C), T(t), F(f) {}
1403
1404 template <typename OpTy> bool match(OpTy *V) {
1405 if (auto *BI = dyn_cast<BranchInst>(V))
1406 if (BI->isConditional() && Cond.match(BI->getCondition()))
1407 return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
1408 return false;
1409 }
1410};
1411
1412template <typename Cond_t>
1413inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
1414m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1415 return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
1416 C, m_BasicBlock(T), m_BasicBlock(F));
1417}
1418
1419template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1420inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
1421m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
1422 return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
1423}
1424
1425//===----------------------------------------------------------------------===//
1426// Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1427//
1428
1429template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1430 bool Commutable = false>
1431struct MaxMin_match {
1432 LHS_t L;
1433 RHS_t R;
1434
1435 // The evaluation order is always stable, regardless of Commutability.
1436 // The LHS is always matched first.
1437 MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1438
1439 template <typename OpTy> bool match(OpTy *V) {
1440 // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1441 auto *SI = dyn_cast<SelectInst>(V);
1442 if (!SI)
1443 return false;
1444 auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1445 if (!Cmp)
1446 return false;
1447 // At this point we have a select conditioned on a comparison. Check that
1448 // it is the values returned by the select that are being compared.
1449 Value *TrueVal = SI->getTrueValue();
1450 Value *FalseVal = SI->getFalseValue();
1451 Value *LHS = Cmp->getOperand(0);
1452 Value *RHS = Cmp->getOperand(1);
1453 if ((TrueVal != LHS || FalseVal != RHS) &&
1454 (TrueVal != RHS || FalseVal != LHS))
1455 return false;
1456 typename CmpInst_t::Predicate Pred =
1457 LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1458 // Does "(x pred y) ? x : y" represent the desired max/min operation?
1459 if (!Pred_t::match(Pred))
1460 return false;
1461 // It does! Bind the operands.
1462 return (L.match(LHS) && R.match(RHS)) ||
1463 (Commutable && L.match(RHS) && R.match(LHS));
1464 }
1465};
1466
1467/// Helper class for identifying signed max predicates.
1468struct smax_pred_ty {
1469 static bool match(ICmpInst::Predicate Pred) {
1470 return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1471 }
1472};
1473
1474/// Helper class for identifying signed min predicates.
1475struct smin_pred_ty {
1476 static bool match(ICmpInst::Predicate Pred) {
1477 return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1478 }
1479};
1480
1481/// Helper class for identifying unsigned max predicates.
1482struct umax_pred_ty {
1483 static bool match(ICmpInst::Predicate Pred) {
1484 return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1485 }
1486};
1487
1488/// Helper class for identifying unsigned min predicates.
1489struct umin_pred_ty {
1490 static bool match(ICmpInst::Predicate Pred) {
1491 return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1492 }
1493};
1494
1495/// Helper class for identifying ordered max predicates.
1496struct ofmax_pred_ty {
1497 static bool match(FCmpInst::Predicate Pred) {
1498 return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1499 }
1500};
1501
1502/// Helper class for identifying ordered min predicates.
1503struct ofmin_pred_ty {
1504 static bool match(FCmpInst::Predicate Pred) {
1505 return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1506 }
1507};
1508
1509/// Helper class for identifying unordered max predicates.
1510struct ufmax_pred_ty {
1511 static bool match(FCmpInst::Predicate Pred) {
1512 return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1513 }
1514};
1515
1516/// Helper class for identifying unordered min predicates.
1517struct ufmin_pred_ty {
1518 static bool match(FCmpInst::Predicate Pred) {
1519 return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1520 }
1521};
1522
1523template <typename LHS, typename RHS>
1524inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1525 const RHS &R) {
1526 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1527}
1528
1529template <typename LHS, typename RHS>
1530inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1531 const RHS &R) {
1532 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1533}
1534
1535template <typename LHS, typename RHS>
1536inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1537 const RHS &R) {
1538 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1539}
1540
1541template <typename LHS, typename RHS>
1542inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1543 const RHS &R) {
1544 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1545}
1546
1547/// Match an 'ordered' floating point maximum function.
1548/// Floating point has one special value 'NaN'. Therefore, there is no total
1549/// order. However, if we can ignore the 'NaN' value (for example, because of a
1550/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1551/// semantics. In the presence of 'NaN' we have to preserve the original
1552/// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1553///
1554/// max(L, R) iff L and R are not NaN
1555/// m_OrdFMax(L, R) = R iff L or R are NaN
1556template <typename LHS, typename RHS>
1557inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1558 const RHS &R) {
1559 return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1560}
1561
1562/// Match an 'ordered' floating point minimum function.
1563/// Floating point has one special value 'NaN'. Therefore, there is no total
1564/// order. However, if we can ignore the 'NaN' value (for example, because of a
1565/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1566/// semantics. In the presence of 'NaN' we have to preserve the original
1567/// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1568///
1569/// min(L, R) iff L and R are not NaN
1570/// m_OrdFMin(L, R) = R iff L or R are NaN
1571template <typename LHS, typename RHS>
1572inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1573 const RHS &R) {
1574 return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1575}
1576
1577/// Match an 'unordered' floating point maximum function.
1578/// Floating point has one special value 'NaN'. Therefore, there is no total
1579/// order. However, if we can ignore the 'NaN' value (for example, because of a
1580/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1581/// semantics. In the presence of 'NaN' we have to preserve the original
1582/// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1583///
1584/// max(L, R) iff L and R are not NaN
1585/// m_UnordFMax(L, R) = L iff L or R are NaN
1586template <typename LHS, typename RHS>
1587inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1588m_UnordFMax(const LHS &L, const RHS &R) {
1589 return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1590}
1591
1592/// Match an 'unordered' floating point minimum function.
1593/// Floating point has one special value 'NaN'. Therefore, there is no total
1594/// order. However, if we can ignore the 'NaN' value (for example, because of a
1595/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1596/// semantics. In the presence of 'NaN' we have to preserve the original
1597/// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1598///
1599/// min(L, R) iff L and R are not NaN
1600/// m_UnordFMin(L, R) = L iff L or R are NaN
1601template <typename LHS, typename RHS>
1602inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1603m_UnordFMin(const LHS &L, const RHS &R) {
1604 return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1605}
1606
1607//===----------------------------------------------------------------------===//
1608// Matchers for overflow check patterns: e.g. (a + b) u< a
1609//
1610
1611template <typename LHS_t, typename RHS_t, typename Sum_t>
1612struct UAddWithOverflow_match {
1613 LHS_t L;
1614 RHS_t R;
1615 Sum_t S;
1616
1617 UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1618 : L(L), R(R), S(S) {}
1619
1620 template <typename OpTy> bool match(OpTy *V) {
1621 Value *ICmpLHS, *ICmpRHS;
1622 ICmpInst::Predicate Pred;
1623 if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1624 return false;
1625
1626 Value *AddLHS, *AddRHS;
1627 auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1628
1629 // (a + b) u< a, (a + b) u< b
1630 if (Pred == ICmpInst::ICMP_ULT)
1631 if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1632 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1633
1634 // a >u (a + b), b >u (a + b)
1635 if (Pred == ICmpInst::ICMP_UGT)
1636 if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1637 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1638
1639 // Match special-case for increment-by-1.
1640 if (Pred == ICmpInst::ICMP_EQ) {
1641 // (a + 1) == 0
1642 // (1 + a) == 0
1643 if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
1644 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1645 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1646 // 0 == (a + 1)
1647 // 0 == (1 + a)
1648 if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
1649 (m_One().match(AddLHS) || m_One().match(AddRHS)))
1650 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1651 }
1652
1653 return false;
1654 }
1655};
1656
1657/// Match an icmp instruction checking for unsigned overflow on addition.
1658///
1659/// S is matched to the addition whose result is being checked for overflow, and
1660/// L and R are matched to the LHS and RHS of S.
1661template <typename LHS_t, typename RHS_t, typename Sum_t>
1662UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
1663m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1664 return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1665}
1666
1667template <typename Opnd_t> struct Argument_match {
1668 unsigned OpI;
1669 Opnd_t Val;
1670
1671 Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1672
1673 template <typename OpTy> bool match(OpTy *V) {
1674 // FIXME: Should likely be switched to use `CallBase`.
1675 if (const auto *CI = dyn_cast<CallInst>(V))
1676 return Val.match(CI->getArgOperand(OpI));
1677 return false;
1678 }
1679};
1680
1681/// Match an argument.
1682template <unsigned OpI, typename Opnd_t>
1683inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1684 return Argument_match<Opnd_t>(OpI, Op);
1685}
1686
1687/// Intrinsic matchers.
1688struct IntrinsicID_match {
1689 unsigned ID;
1690
1691 IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1692
1693 template <typename OpTy> bool match(OpTy *V) {
1694 if (const auto *CI = dyn_cast<CallInst>(V))
1695 if (const auto *F = CI->getCalledFunction())
1696 return F->getIntrinsicID() == ID;
1697 return false;
1698 }
1699};
1700
1701/// Intrinsic matches are combinations of ID matchers, and argument
1702/// matchers. Higher arity matcher are defined recursively in terms of and-ing
1703/// them with lower arity matchers. Here's some convenient typedefs for up to
1704/// several arguments, and more can be added as needed
1705template <typename T0 = void, typename T1 = void, typename T2 = void,
1706 typename T3 = void, typename T4 = void, typename T5 = void,
1707 typename T6 = void, typename T7 = void, typename T8 = void,
1708 typename T9 = void, typename T10 = void>
1709struct m_Intrinsic_Ty;
1710template <typename T0> struct m_Intrinsic_Ty<T0> {
1711 using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1712};
1713template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1714 using Ty =
1715 match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1716};
1717template <typename T0, typename T1, typename T2>
1718struct m_Intrinsic_Ty<T0, T1, T2> {
1719 using Ty =
1720 match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
1721 Argument_match<T2>>;
1722};
1723template <typename T0, typename T1, typename T2, typename T3>
1724struct m_Intrinsic_Ty<T0, T1, T2, T3> {
1725 using Ty =
1726 match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
1727 Argument_match<T3>>;
1728};
1729
1730/// Match intrinsic calls like this:
1731/// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
1732template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
1733 return IntrinsicID_match(IntrID);
1734}
1735
1736template <Intrinsic::ID IntrID, typename T0>
1737inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
1738 return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
1739}
1740
1741template <Intrinsic::ID IntrID, typename T0, typename T1>
1742inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
1743 const T1 &Op1) {
1744 return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
1745}
1746
1747template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
1748inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
1749m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
1750 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
1751}
1752
1753template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1754 typename T3>
1755inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
1756m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
1757 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
1758}
1759
1760// Helper intrinsic matching specializations.
1761template <typename Opnd0>
1762inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
1763 return m_Intrinsic<Intrinsic::bitreverse>(Op0);
1764}
1765
1766template <typename Opnd0>
1767inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
1768 return m_Intrinsic<Intrinsic::bswap>(Op0);
1769}
1770
1771template <typename Opnd0>
1772inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
1773 return m_Intrinsic<Intrinsic::fabs>(Op0);
1774}
1775
1776template <typename Opnd0>
1777inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
1778 return m_Intrinsic<Intrinsic::canonicalize>(Op0);
1779}
1780
1781template <typename Opnd0, typename Opnd1>
1782inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
1783 const Opnd1 &Op1) {
1784 return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
1785}
1786
1787template <typename Opnd0, typename Opnd1>
1788inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
1789 const Opnd1 &Op1) {
1790 return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// Matchers for two-operands operators with the operators in either order
1795//
1796
1797/// Matches a BinaryOperator with LHS and RHS in either order.
1798template <typename LHS, typename RHS>
1799inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
1800 return AnyBinaryOp_match<LHS, RHS, true>(L, R);
10
Returning without writing to 'R.VR'
1801}
1802
1803/// Matches an ICmp with a predicate over LHS and RHS in either order.
1804/// Does not swap the predicate.
1805template <typename LHS, typename RHS>
1806inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
1807m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1808 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
1809 R);
1810}
1811
1812/// Matches a Add with LHS and RHS in either order.
1813template <typename LHS, typename RHS>
1814inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
1815 const RHS &R) {
1816 return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
1817}
1818
1819/// Matches a Mul with LHS and RHS in either order.
1820template <typename LHS, typename RHS>
1821inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
1822 const RHS &R) {
1823 return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
1824}
1825
1826/// Matches an And with LHS and RHS in either order.
1827template <typename LHS, typename RHS>
1828inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
1829 const RHS &R) {
1830 return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
1831}
1832
1833/// Matches an Or with LHS and RHS in either order.
1834template <typename LHS, typename RHS>
1835inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
1836 const RHS &R) {
1837 return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
1838}
1839
1840/// Matches an Xor with LHS and RHS in either order.
1841template <typename LHS, typename RHS>
1842inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
1843 const RHS &R) {
1844 return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
1845}
1846
1847/// Matches a 'Neg' as 'sub 0, V'.
1848template <typename ValTy>
1849inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
1850m_Neg(const ValTy &V) {
1851 return m_Sub(m_ZeroInt(), V);
1852}
1853
1854/// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
1855template <typename ValTy>
1856inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true>
1857m_Not(const ValTy &V) {
1858 return m_c_Xor(V, m_AllOnes());
1859}
1860
1861/// Matches an SMin with LHS and RHS in either order.
1862template <typename LHS, typename RHS>
1863inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
1864m_c_SMin(const LHS &L, const RHS &R) {
1865 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
1866}
1867/// Matches an SMax with LHS and RHS in either order.
1868template <typename LHS, typename RHS>
1869inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
1870m_c_SMax(const LHS &L, const RHS &R) {
1871 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
1872}
1873/// Matches a UMin with LHS and RHS in either order.
1874template <typename LHS, typename RHS>
1875inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
1876m_c_UMin(const LHS &L, const RHS &R) {
1877 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
1878}
1879/// Matches a UMax with LHS and RHS in either order.
1880template <typename LHS, typename RHS>
1881inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
1882m_c_UMax(const LHS &L, const RHS &R) {
1883 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
1884}
1885
1886/// Matches FAdd with LHS and RHS in either order.
1887template <typename LHS, typename RHS>
1888inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
1889m_c_FAdd(const LHS &L, const RHS &R) {
1890 return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
1891}
1892
1893/// Matches FMul with LHS and RHS in either order.
1894template <typename LHS, typename RHS>
1895inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
1896m_c_FMul(const LHS &L, const RHS &R) {
1897 return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
1898}
1899
1900template <typename Opnd_t> struct Signum_match {
1901 Opnd_t Val;
1902 Signum_match(const Opnd_t &V) : Val(V) {}
1903
1904 template <typename OpTy> bool match(OpTy *V) {
1905 unsigned TypeSize = V->getType()->getScalarSizeInBits();
1906 if (TypeSize == 0)
1907 return false;
1908
1909 unsigned ShiftWidth = TypeSize - 1;
1910 Value *OpL = nullptr, *OpR = nullptr;
1911
1912 // This is the representation of signum we match:
1913 //
1914 // signum(x) == (x >> 63) | (-x >>u 63)
1915 //
1916 // An i1 value is its own signum, so it's correct to match
1917 //
1918 // signum(x) == (x >> 0) | (-x >>u 0)
1919 //
1920 // for i1 values.
1921
1922 auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
1923 auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
1924 auto Signum = m_Or(LHS, RHS);
1925
1926 return Signum.match(V) && OpL == OpR && Val.match(OpL);
1927 }
1928};
1929
1930/// Matches a signum pattern.
1931///
1932/// signum(x) =
1933/// x > 0 -> 1
1934/// x == 0 -> 0
1935/// x < 0 -> -1
1936template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
1937 return Signum_match<Val_t>(V);
1938}
1939
1940} // end namespace PatternMatch
1941} // end namespace llvm
1942
1943#endif // LLVM_IR_PATTERNMATCH_H