Bug Summary

File:llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
Warning:line 666, column 24
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstCombineMulDivRem.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/lib/Transforms/InstCombine -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/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-13/lib/clang/13.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-13~++20210308111132+66e3a4abe99c/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-03-08-182450-10039-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp

/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp

1//===- InstCombineMulDivRem.cpp -------------------------------------------===//
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 mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/IR/BasicBlock.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/IntrinsicInst.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
28#include "llvm/IR/PatternMatch.h"
29#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/KnownBits.h"
34#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
35#include "llvm/Transforms/InstCombine/InstCombiner.h"
36#include "llvm/Transforms/Utils/BuildLibCalls.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41
42using namespace llvm;
43using namespace PatternMatch;
44
45#define DEBUG_TYPE"instcombine" "instcombine"
46
47/// The specific integer value is used in a context where it is known to be
48/// non-zero. If this allows us to simplify the computation, do so and return
49/// the new operand, otherwise return null.
50static Value *simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC,
51 Instruction &CxtI) {
52 // If V has multiple uses, then we would have to do more analysis to determine
53 // if this is safe. For example, the use could be in dynamically unreached
54 // code.
55 if (!V->hasOneUse()) return nullptr;
56
57 bool MadeChange = false;
58
59 // ((1 << A) >>u B) --> (1 << (A-B))
60 // Because V cannot be zero, we know that B is less than A.
61 Value *A = nullptr, *B = nullptr, *One = nullptr;
62 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
63 match(One, m_One())) {
64 A = IC.Builder.CreateSub(A, B);
65 return IC.Builder.CreateShl(One, A);
66 }
67
68 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
69 // inexact. Similarly for <<.
70 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
71 if (I && I->isLogicalShift() &&
72 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
73 // We know that this is an exact/nuw shift and that the input is a
74 // non-zero context as well.
75 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
76 IC.replaceOperand(*I, 0, V2);
77 MadeChange = true;
78 }
79
80 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
81 I->setIsExact();
82 MadeChange = true;
83 }
84
85 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
86 I->setHasNoUnsignedWrap();
87 MadeChange = true;
88 }
89 }
90
91 // TODO: Lots more we could do here:
92 // If V is a phi node, we can call this on each of its operands.
93 // "select cond, X, 0" can simplify to "X".
94
95 return MadeChange ? V : nullptr;
96}
97
98// TODO: This is a specific form of a much more general pattern.
99// We could detect a select with any binop identity constant, or we
100// could use SimplifyBinOp to see if either arm of the select reduces.
101// But that needs to be done carefully and/or while removing potential
102// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
103static Value *foldMulSelectToNegate(BinaryOperator &I,
104 InstCombiner::BuilderTy &Builder) {
105 Value *Cond, *OtherOp;
106
107 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
108 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
109 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())),
110 m_Value(OtherOp))))
111 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp));
112
113 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
114 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
115 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())),
116 m_Value(OtherOp))))
117 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp);
118
119 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
120 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
121 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0),
122 m_SpecificFP(-1.0))),
123 m_Value(OtherOp)))) {
124 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
125 Builder.setFastMathFlags(I.getFastMathFlags());
126 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
127 }
128
129 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
130 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
131 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0),
132 m_SpecificFP(1.0))),
133 m_Value(OtherOp)))) {
134 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
135 Builder.setFastMathFlags(I.getFastMathFlags());
136 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
137 }
138
139 return nullptr;
140}
141
142Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
143 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
144 SQ.getWithInstruction(&I)))
145 return replaceInstUsesWith(I, V);
146
147 if (SimplifyAssociativeOrCommutative(I))
148 return &I;
149
150 if (Instruction *X = foldVectorBinop(I))
151 return X;
152
153 if (Value *V = SimplifyUsingDistributiveLaws(I))
154 return replaceInstUsesWith(I, V);
155
156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
157 unsigned BitWidth = I.getType()->getScalarSizeInBits();
158
159 // X * -1 == 0 - X
160 if (match(Op1, m_AllOnes())) {
161 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
162 if (I.hasNoSignedWrap())
163 BO->setHasNoSignedWrap();
164 return BO;
165 }
166
167 // Also allow combining multiply instructions on vectors.
168 {
169 Value *NewOp;
170 Constant *C1, *C2;
171 const APInt *IVal;
172 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
173 m_Constant(C1))) &&
174 match(C1, m_APInt(IVal))) {
175 // ((X << C2)*C1) == (X * (C1 << C2))
176 Constant *Shl = ConstantExpr::getShl(C1, C2);
177 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
178 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
179 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
180 BO->setHasNoUnsignedWrap();
181 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
182 Shl->isNotMinSignedValue())
183 BO->setHasNoSignedWrap();
184 return BO;
185 }
186
187 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
188 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
189 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C1)) {
190 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
191
192 if (I.hasNoUnsignedWrap())
193 Shl->setHasNoUnsignedWrap();
194 if (I.hasNoSignedWrap()) {
195 const APInt *V;
196 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
197 Shl->setHasNoSignedWrap();
198 }
199
200 return Shl;
201 }
202 }
203 }
204
205 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
206 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
207 // The "* (1<<C)" thus becomes a potential shifting opportunity.
208 if (Value *NegOp0 = Negator::Negate(/*IsNegation*/ true, Op0, *this))
209 return BinaryOperator::CreateMul(
210 NegOp0, ConstantExpr::getNeg(cast<Constant>(Op1)), I.getName());
211 }
212
213 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
214 return FoldedMul;
215
216 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
217 return replaceInstUsesWith(I, FoldedMul);
218
219 // Simplify mul instructions with a constant RHS.
220 if (isa<Constant>(Op1)) {
221 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
222 Value *X;
223 Constant *C1;
224 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
225 Value *Mul = Builder.CreateMul(C1, Op1);
226 // Only go forward with the transform if C1*CI simplifies to a tidier
227 // constant.
228 if (!match(Mul, m_Mul(m_Value(), m_Value())))
229 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
230 }
231 }
232
233 // abs(X) * abs(X) -> X * X
234 // nabs(X) * nabs(X) -> X * X
235 if (Op0 == Op1) {
236 Value *X, *Y;
237 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
238 if (SPF == SPF_ABS || SPF == SPF_NABS)
239 return BinaryOperator::CreateMul(X, X);
240
241 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
242 return BinaryOperator::CreateMul(X, X);
243 }
244
245 // -X * C --> X * -C
246 Value *X, *Y;
247 Constant *Op1C;
248 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
249 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
250
251 // -X * -Y --> X * Y
252 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
253 auto *NewMul = BinaryOperator::CreateMul(X, Y);
254 if (I.hasNoSignedWrap() &&
255 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
256 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
257 NewMul->setHasNoSignedWrap();
258 return NewMul;
259 }
260
261 // -X * Y --> -(X * Y)
262 // X * -Y --> -(X * Y)
263 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))
264 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
265
266 // (X / Y) * Y = X - (X % Y)
267 // (X / Y) * -Y = (X % Y) - X
268 {
269 Value *Y = Op1;
270 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
271 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
272 Div->getOpcode() != Instruction::SDiv)) {
273 Y = Op0;
274 Div = dyn_cast<BinaryOperator>(Op1);
275 }
276 Value *Neg = dyn_castNegVal(Y);
277 if (Div && Div->hasOneUse() &&
278 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
279 (Div->getOpcode() == Instruction::UDiv ||
280 Div->getOpcode() == Instruction::SDiv)) {
281 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
282
283 // If the division is exact, X % Y is zero, so we end up with X or -X.
284 if (Div->isExact()) {
285 if (DivOp1 == Y)
286 return replaceInstUsesWith(I, X);
287 return BinaryOperator::CreateNeg(X);
288 }
289
290 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
291 : Instruction::SRem;
292 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
293 if (DivOp1 == Y)
294 return BinaryOperator::CreateSub(X, Rem);
295 return BinaryOperator::CreateSub(Rem, X);
296 }
297 }
298
299 /// i1 mul -> i1 and.
300 if (I.getType()->isIntOrIntVectorTy(1))
301 return BinaryOperator::CreateAnd(Op0, Op1);
302
303 // X*(1 << Y) --> X << Y
304 // (1 << Y)*X --> X << Y
305 {
306 Value *Y;
307 BinaryOperator *BO = nullptr;
308 bool ShlNSW = false;
309 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
310 BO = BinaryOperator::CreateShl(Op1, Y);
311 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
312 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
313 BO = BinaryOperator::CreateShl(Op0, Y);
314 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
315 }
316 if (BO) {
317 if (I.hasNoUnsignedWrap())
318 BO->setHasNoUnsignedWrap();
319 if (I.hasNoSignedWrap() && ShlNSW)
320 BO->setHasNoSignedWrap();
321 return BO;
322 }
323 }
324
325 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
326 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
327 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
328 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
329 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
330 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
331 (Op0->hasOneUse() || Op1->hasOneUse())) {
332 Value *And = Builder.CreateAnd(X, Y, "mulbool");
333 return CastInst::Create(Instruction::ZExt, And, I.getType());
334 }
335 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
336 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
337 // Note: -1 * 1 == 1 * -1 == -1
338 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
339 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
340 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
341 (Op0->hasOneUse() || Op1->hasOneUse())) {
342 Value *And = Builder.CreateAnd(X, Y, "mulbool");
343 return CastInst::Create(Instruction::SExt, And, I.getType());
344 }
345
346 // (bool X) * Y --> X ? Y : 0
347 // Y * (bool X) --> X ? Y : 0
348 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
349 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
350 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
351 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
352
353 // (lshr X, 31) * Y --> (ashr X, 31) & Y
354 // Y * (lshr X, 31) --> (ashr X, 31) & Y
355 // TODO: We are not checking one-use because the elimination of the multiply
356 // is better for analysis?
357 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
358 // more similar to what we're doing above.
359 const APInt *C;
360 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
361 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
362 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
363 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
364
365 // ((ashr X, 31) | 1) * X --> abs(X)
366 // X * ((ashr X, 31) | 1) --> abs(X)
367 if (match(&I, m_c_BinOp(m_Or(m_AShr(m_Value(X),
368 m_SpecificIntAllowUndef(BitWidth - 1)),
369 m_One()),
370 m_Deferred(X)))) {
371 Value *Abs = Builder.CreateBinaryIntrinsic(
372 Intrinsic::abs, X,
373 ConstantInt::getBool(I.getContext(), I.hasNoSignedWrap()));
374 Abs->takeName(&I);
375 return replaceInstUsesWith(I, Abs);
376 }
377
378 if (Instruction *Ext = narrowMathIfNoOverflow(I))
379 return Ext;
380
381 bool Changed = false;
382 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
383 Changed = true;
384 I.setHasNoSignedWrap(true);
385 }
386
387 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
388 Changed = true;
389 I.setHasNoUnsignedWrap(true);
390 }
391
392 return Changed ? &I : nullptr;
393}
394
395Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
396 BinaryOperator::BinaryOps Opcode = I.getOpcode();
397 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&(((Opcode == Instruction::FMul || Opcode == Instruction::FDiv
) && "Expected fmul or fdiv") ? static_cast<void>
(0) : __assert_fail ("(Opcode == Instruction::FMul || Opcode == Instruction::FDiv) && \"Expected fmul or fdiv\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 398, __PRETTY_FUNCTION__))
398 "Expected fmul or fdiv")(((Opcode == Instruction::FMul || Opcode == Instruction::FDiv
) && "Expected fmul or fdiv") ? static_cast<void>
(0) : __assert_fail ("(Opcode == Instruction::FMul || Opcode == Instruction::FDiv) && \"Expected fmul or fdiv\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 398, __PRETTY_FUNCTION__))
;
399
400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
401 Value *X, *Y;
402
403 // -X * -Y --> X * Y
404 // -X / -Y --> X / Y
405 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
406 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
407
408 // fabs(X) * fabs(X) -> X * X
409 // fabs(X) / fabs(X) -> X / X
410 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
411 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
412
413 // fabs(X) * fabs(Y) --> fabs(X * Y)
414 // fabs(X) / fabs(Y) --> fabs(X / Y)
415 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
416 (Op0->hasOneUse() || Op1->hasOneUse())) {
417 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
418 Builder.setFastMathFlags(I.getFastMathFlags());
419 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
420 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
421 Fabs->takeName(&I);
422 return replaceInstUsesWith(I, Fabs);
423 }
424
425 return nullptr;
426}
427
428Instruction *InstCombinerImpl::visitFMul(BinaryOperator &I) {
429 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
430 I.getFastMathFlags(),
431 SQ.getWithInstruction(&I)))
432 return replaceInstUsesWith(I, V);
433
434 if (SimplifyAssociativeOrCommutative(I))
435 return &I;
436
437 if (Instruction *X = foldVectorBinop(I))
438 return X;
439
440 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
441 return FoldedMul;
442
443 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
444 return replaceInstUsesWith(I, FoldedMul);
445
446 if (Instruction *R = foldFPSignBitOps(I))
447 return R;
448
449 // X * -1.0 --> -X
450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
451 if (match(Op1, m_SpecificFP(-1.0)))
452 return UnaryOperator::CreateFNegFMF(Op0, &I);
453
454 // -X * C --> X * -C
455 Value *X, *Y;
456 Constant *C;
457 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
458 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
459
460 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
461 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
462 return replaceInstUsesWith(I, V);
463
464 if (I.hasAllowReassoc()) {
465 // Reassociate constant RHS with another constant to form constant
466 // expression.
467 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
468 Constant *C1;
469 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
470 // (C1 / X) * C --> (C * C1) / X
471 Constant *CC1 = ConstantExpr::getFMul(C, C1);
472 if (CC1->isNormalFP())
473 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
474 }
475 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
476 // (X / C1) * C --> X * (C / C1)
477 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
478 if (CDivC1->isNormalFP())
479 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
480
481 // If the constant was a denormal, try reassociating differently.
482 // (X / C1) * C --> X / (C1 / C)
483 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
484 if (Op0->hasOneUse() && C1DivC->isNormalFP())
485 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
486 }
487
488 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
489 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
490 // further folds and (X * C) + C2 is 'fma'.
491 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
492 // (X + C1) * C --> (X * C) + (C * C1)
493 Constant *CC1 = ConstantExpr::getFMul(C, C1);
494 Value *XC = Builder.CreateFMulFMF(X, C, &I);
495 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
496 }
497 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
498 // (C1 - X) * C --> (C * C1) - (X * C)
499 Constant *CC1 = ConstantExpr::getFMul(C, C1);
500 Value *XC = Builder.CreateFMulFMF(X, C, &I);
501 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
502 }
503 }
504
505 Value *Z;
506 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))),
507 m_Value(Z)))) {
508 // Sink division: (X / Y) * Z --> (X * Z) / Y
509 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
510 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
511 }
512
513 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
514 // nnan disallows the possibility of returning a number if both operands are
515 // negative (in that case, we should return NaN).
516 if (I.hasNoNaNs() &&
517 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
518 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
519 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
520 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
521 return replaceInstUsesWith(I, Sqrt);
522 }
523
524 // The following transforms are done irrespective of the number of uses
525 // for the expression "1.0/sqrt(X)".
526 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
527 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
528 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
529 // has the necessary (reassoc) fast-math-flags.
530 if (I.hasNoSignedZeros() &&
531 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
532 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op1 == X)
533 return BinaryOperator::CreateFDivFMF(X, Y, &I);
534 if (I.hasNoSignedZeros() &&
535 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
536 match(Y, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && Op0 == X)
537 return BinaryOperator::CreateFDivFMF(X, Y, &I);
538
539 // Like the similar transform in instsimplify, this requires 'nsz' because
540 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
541 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
542 Op0->hasNUses(2)) {
543 // Peek through fdiv to find squaring of square root:
544 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
545 if (match(Op0, m_FDiv(m_Value(X),
546 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
547 Value *XX = Builder.CreateFMulFMF(X, X, &I);
548 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
549 }
550 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
551 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)),
552 m_Value(X)))) {
553 Value *XX = Builder.CreateFMulFMF(X, X, &I);
554 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
555 }
556 }
557
558 // exp(X) * exp(Y) -> exp(X + Y)
559 // Match as long as at least one of exp has only one use.
560 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
561 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) &&
562 (Op0->hasOneUse() || Op1->hasOneUse())) {
563 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
564 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
565 return replaceInstUsesWith(I, Exp);
566 }
567
568 // exp2(X) * exp2(Y) -> exp2(X + Y)
569 // Match as long as at least one of exp2 has only one use.
570 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
571 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) &&
572 (Op0->hasOneUse() || Op1->hasOneUse())) {
573 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
574 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
575 return replaceInstUsesWith(I, Exp2);
576 }
577
578 // (X*Y) * X => (X*X) * Y where Y != X
579 // The purpose is two-fold:
580 // 1) to form a power expression (of X).
581 // 2) potentially shorten the critical path: After transformation, the
582 // latency of the instruction Y is amortized by the expression of X*X,
583 // and therefore Y is in a "less critical" position compared to what it
584 // was before the transformation.
585 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
586 Op1 != Y) {
587 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
588 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
589 }
590 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
591 Op0 != Y) {
592 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
593 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
594 }
595 }
596
597 // log2(X * 0.5) * Y = log2(X) * Y - Y
598 if (I.isFast()) {
599 IntrinsicInst *Log2 = nullptr;
600 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
601 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
602 Log2 = cast<IntrinsicInst>(Op0);
603 Y = Op1;
604 }
605 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
606 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
607 Log2 = cast<IntrinsicInst>(Op1);
608 Y = Op0;
609 }
610 if (Log2) {
611 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
612 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
613 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
614 }
615 }
616
617 return nullptr;
618}
619
620/// Fold a divide or remainder with a select instruction divisor when one of the
621/// select operands is zero. In that case, we can use the other select operand
622/// because div/rem by zero is undefined.
623bool InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
624 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
625 if (!SI)
9
Assuming 'SI' is non-null
10
Taking false branch
626 return false;
627
628 int NonNullOperand;
629 if (match(SI->getTrueValue(), m_Zero()))
11
Calling 'match<llvm::Value, llvm::PatternMatch::is_zero>'
18
Returning from 'match<llvm::Value, llvm::PatternMatch::is_zero>'
19
Assuming the condition is true
20
Taking true branch
630 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
631 NonNullOperand = 2;
632 else if (match(SI->getFalseValue(), m_Zero()))
633 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
634 NonNullOperand = 1;
635 else
636 return false;
637
638 // Change the div/rem to use 'Y' instead of the select.
639 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
640
641 // Okay, we know we replace the operand of the div/rem with 'Y' with no
642 // problem. However, the select, or the condition of the select may have
643 // multiple uses. Based on our knowledge that the operand must be non-zero,
644 // propagate the known value for the select into other uses of it, and
645 // propagate a known value of the condition into its other users.
646
647 // If the select and condition only have a single use, don't bother with this,
648 // early exit.
649 Value *SelectCond = SI->getCondition();
650 if (SI->use_empty() && SelectCond->hasOneUse())
21
Calling 'Value::use_empty'
24
Returning from 'Value::use_empty'
651 return true;
652
653 // Scan the current block backward, looking for other uses of SI.
654 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
655 Type *CondTy = SelectCond->getType();
656 while (BBI != BBFront) {
25
Calling 'operator!='
28
Returning from 'operator!='
29
Loop condition is true. Entering loop body
38
Calling 'operator!='
41
Returning from 'operator!='
42
Loop condition is true. Entering loop body
657 --BBI;
658 // If we found an instruction that we can't assume will return, so
659 // information from below it cannot be propagated above it.
660 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
30
Assuming the condition is false
31
Taking false branch
43
Assuming the condition is false
44
Taking false branch
661 break;
662
663 // Replace uses of the select or its condition with the known values.
664 for (Use &Op : BBI->operands()) {
32
Assuming '__begin2' is equal to '__end2'
45
Assuming '__begin2' is not equal to '__end2'
665 if (Op == SI) {
46
Assuming the condition is true
47
Taking true branch
666 replaceUse(Op, SI->getOperand(NonNullOperand));
48
Called C++ object pointer is null
667 Worklist.push(&*BBI);
668 } else if (Op == SelectCond) {
669 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
670 : ConstantInt::getFalse(CondTy));
671 Worklist.push(&*BBI);
672 }
673 }
674
675 // If we past the instruction, quit looking for it.
676 if (&*BBI == SI)
33
Assuming the condition is true
34
Taking true branch
677 SI = nullptr;
35
Null pointer value stored to 'SI'
678 if (&*BBI == SelectCond)
36
Assuming the condition is false
37
Taking false branch
679 SelectCond = nullptr;
680
681 // If we ran out of things to eliminate, break out of the loop.
682 if (!SelectCond
37.1
'SelectCond' is non-null
37.1
'SelectCond' is non-null
37.1
'SelectCond' is non-null
37.1
'SelectCond' is non-null
&& !SI)
683 break;
684
685 }
686 return true;
687}
688
689/// True if the multiply can not be expressed in an int this size.
690static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
691 bool IsSigned) {
692 bool Overflow;
693 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
694 return Overflow;
695}
696
697/// True if C1 is a multiple of C2. Quotient contains C1/C2.
698static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
699 bool IsSigned) {
700 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal")((C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal"
) ? static_cast<void> (0) : __assert_fail ("C1.getBitWidth() == C2.getBitWidth() && \"Constant widths not equal\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 700, __PRETTY_FUNCTION__))
;
701
702 // Bail if we will divide by zero.
703 if (C2.isNullValue())
704 return false;
705
706 // Bail if we would divide INT_MIN by -1.
707 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
708 return false;
709
710 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
711 if (IsSigned)
712 APInt::sdivrem(C1, C2, Quotient, Remainder);
713 else
714 APInt::udivrem(C1, C2, Quotient, Remainder);
715
716 return Remainder.isMinValue();
717}
718
719/// This function implements the transforms common to both integer division
720/// instructions (udiv and sdiv). It is called by the visitors to those integer
721/// division instructions.
722/// Common integer divide transforms
723Instruction *InstCombinerImpl::commonIDivTransforms(BinaryOperator &I) {
724 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
725 bool IsSigned = I.getOpcode() == Instruction::SDiv;
726 Type *Ty = I.getType();
727
728 // The RHS is known non-zero.
729 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
730 return replaceOperand(I, 1, V);
731
732 // Handle cases involving: [su]div X, (select Cond, Y, Z)
733 // This does not apply for fdiv.
734 if (simplifyDivRemOfSelectWithZeroOp(I))
735 return &I;
736
737 const APInt *C2;
738 if (match(Op1, m_APInt(C2))) {
739 Value *X;
740 const APInt *C1;
741
742 // (X / C1) / C2 -> X / (C1*C2)
743 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
744 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
745 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
746 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
747 return BinaryOperator::Create(I.getOpcode(), X,
748 ConstantInt::get(Ty, Product));
749 }
750
751 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
752 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
753 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
754
755 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
756 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
757 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
758 ConstantInt::get(Ty, Quotient));
759 NewDiv->setIsExact(I.isExact());
760 return NewDiv;
761 }
762
763 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
764 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
765 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
766 ConstantInt::get(Ty, Quotient));
767 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
768 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
769 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
770 return Mul;
771 }
772 }
773
774 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
775 *C1 != C1->getBitWidth() - 1) ||
776 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
777 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
778 APInt C1Shifted = APInt::getOneBitSet(
779 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
780
781 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
782 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
783 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
784 ConstantInt::get(Ty, Quotient));
785 BO->setIsExact(I.isExact());
786 return BO;
787 }
788
789 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
790 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
791 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
792 ConstantInt::get(Ty, Quotient));
793 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
794 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
795 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
796 return Mul;
797 }
798 }
799
800 if (!C2->isNullValue()) // avoid X udiv 0
801 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
802 return FoldedDiv;
803 }
804
805 if (match(Op0, m_One())) {
806 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?")((!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?"
) ? static_cast<void> (0) : __assert_fail ("!Ty->isIntOrIntVectorTy(1) && \"i1 divide not removed?\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 806, __PRETTY_FUNCTION__))
;
807 if (IsSigned) {
808 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
809 // result is one, if Op1 is -1 then the result is minus one, otherwise
810 // it's zero.
811 Value *Inc = Builder.CreateAdd(Op1, Op0);
812 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
813 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
814 } else {
815 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
816 // result is one, otherwise it's zero.
817 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
818 }
819 }
820
821 // See if we can fold away this div instruction.
822 if (SimplifyDemandedInstructionBits(I))
823 return &I;
824
825 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
826 Value *X, *Z;
827 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
828 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
829 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
830 return BinaryOperator::Create(I.getOpcode(), X, Op1);
831
832 // (X << Y) / X -> 1 << Y
833 Value *Y;
834 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
835 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
836 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
837 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
838
839 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
840 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
841 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
842 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
843 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
844 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
845 replaceOperand(I, 1, Y);
846 return &I;
847 }
848 }
849
850 return nullptr;
851}
852
853static const unsigned MaxDepth = 6;
854
855namespace {
856
857using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
858 const BinaryOperator &I,
859 InstCombinerImpl &IC);
860
861/// Used to maintain state for visitUDivOperand().
862struct UDivFoldAction {
863 /// Informs visitUDiv() how to fold this operand. This can be zero if this
864 /// action joins two actions together.
865 FoldUDivOperandCb FoldAction;
866
867 /// Which operand to fold.
868 Value *OperandToFold;
869
870 union {
871 /// The instruction returned when FoldAction is invoked.
872 Instruction *FoldResult;
873
874 /// Stores the LHS action index if this action joins two actions together.
875 size_t SelectLHSIdx;
876 };
877
878 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
879 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
880 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
881 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
882};
883
884} // end anonymous namespace
885
886// X udiv 2^C -> X >> C
887static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
888 const BinaryOperator &I,
889 InstCombinerImpl &IC) {
890 Constant *C1 = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
891 if (!C1)
892 llvm_unreachable("Failed to constant fold udiv -> logbase2")::llvm::llvm_unreachable_internal("Failed to constant fold udiv -> logbase2"
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 892)
;
893 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
894 if (I.isExact())
895 LShr->setIsExact();
896 return LShr;
897}
898
899// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
900// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
901static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
902 InstCombinerImpl &IC) {
903 Value *ShiftLeft;
904 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
905 ShiftLeft = Op1;
906
907 Constant *CI;
908 Value *N;
909 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
910 llvm_unreachable("match should never fail here!")::llvm::llvm_unreachable_internal("match should never fail here!"
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 910)
;
911 Constant *Log2Base = ConstantExpr::getExactLogBase2(CI);
912 if (!Log2Base)
913 llvm_unreachable("getLogBase2 should never fail here!")::llvm::llvm_unreachable_internal("getLogBase2 should never fail here!"
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp"
, 913)
;
914 N = IC.Builder.CreateAdd(N, Log2Base);
915 if (Op1 != ShiftLeft)
916 N = IC.Builder.CreateZExt(N, Op1->getType());
917 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
918 if (I.isExact())
919 LShr->setIsExact();
920 return LShr;
921}
922
923// Recursively visits the possible right hand operands of a udiv
924// instruction, seeing through select instructions, to determine if we can
925// replace the udiv with something simpler. If we find that an operand is not
926// able to simplify the udiv, we abort the entire transformation.
927static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
928 SmallVectorImpl<UDivFoldAction> &Actions,
929 unsigned Depth = 0) {
930 // FIXME: assert that Op1 isn't/doesn't contain undef.
931
932 // Check to see if this is an unsigned division with an exact power of 2,
933 // if so, convert to a right shift.
934 if (match(Op1, m_Power2())) {
935 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
936 return Actions.size();
937 }
938
939 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
940 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
941 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
942 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
943 return Actions.size();
944 }
945
946 // The remaining tests are all recursive, so bail out if we hit the limit.
947 if (Depth++ == MaxDepth)
948 return 0;
949
950 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
951 // FIXME: missed optimization: if one of the hands of select is/contains
952 // undef, just directly pick the other one.
953 // FIXME: can both hands contain undef?
954 if (size_t LHSIdx =
955 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
956 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
957 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
958 return Actions.size();
959 }
960
961 return 0;
962}
963
964/// If we have zero-extended operands of an unsigned div or rem, we may be able
965/// to narrow the operation (sink the zext below the math).
966static Instruction *narrowUDivURem(BinaryOperator &I,
967 InstCombiner::BuilderTy &Builder) {
968 Instruction::BinaryOps Opcode = I.getOpcode();
969 Value *N = I.getOperand(0);
970 Value *D = I.getOperand(1);
971 Type *Ty = I.getType();
972 Value *X, *Y;
973 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
974 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
975 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
976 // urem (zext X), (zext Y) --> zext (urem X, Y)
977 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
978 return new ZExtInst(NarrowOp, Ty);
979 }
980
981 Constant *C;
982 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
983 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
984 // If the constant is the same in the smaller type, use the narrow version.
985 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
986 if (ConstantExpr::getZExt(TruncC, Ty) != C)
987 return nullptr;
988
989 // udiv (zext X), C --> zext (udiv X, C')
990 // urem (zext X), C --> zext (urem X, C')
991 // udiv C, (zext X) --> zext (udiv C', X)
992 // urem C, (zext X) --> zext (urem C', X)
993 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
994 : Builder.CreateBinOp(Opcode, TruncC, X);
995 return new ZExtInst(NarrowOp, Ty);
996 }
997
998 return nullptr;
999}
1000
1001Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) {
1002 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
1003 SQ.getWithInstruction(&I)))
1004 return replaceInstUsesWith(I, V);
1005
1006 if (Instruction *X = foldVectorBinop(I))
1007 return X;
1008
1009 // Handle the integer div common cases
1010 if (Instruction *Common = commonIDivTransforms(I))
1011 return Common;
1012
1013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1014 Value *X;
1015 const APInt *C1, *C2;
1016 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1017 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1018 bool Overflow;
1019 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1020 if (!Overflow) {
1021 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1022 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1023 X, ConstantInt::get(X->getType(), C2ShlC1));
1024 if (IsExact)
1025 BO->setIsExact();
1026 return BO;
1027 }
1028 }
1029
1030 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1031 // TODO: Could use isKnownNegative() to handle non-constant values.
1032 Type *Ty = I.getType();
1033 if (match(Op1, m_Negative())) {
1034 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1035 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1036 }
1037 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1038 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1039 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1040 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1041 }
1042
1043 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1044 return NarrowDiv;
1045
1046 // If the udiv operands are non-overflowing multiplies with a common operand,
1047 // then eliminate the common factor:
1048 // (A * B) / (A * X) --> B / X (and commuted variants)
1049 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1050 // TODO: If -reassociation handled this generally, we could remove this.
1051 Value *A, *B;
1052 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1053 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1054 match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1055 return BinaryOperator::CreateUDiv(B, X);
1056 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1057 match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1058 return BinaryOperator::CreateUDiv(A, X);
1059 }
1060
1061 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1062 SmallVector<UDivFoldAction, 6> UDivActions;
1063 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1064 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1065 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1066 Value *ActionOp1 = UDivActions[i].OperandToFold;
1067 Instruction *Inst;
1068 if (Action)
1069 Inst = Action(Op0, ActionOp1, I, *this);
1070 else {
1071 // This action joins two actions together. The RHS of this action is
1072 // simply the last action we processed, we saved the LHS action index in
1073 // the joining action.
1074 size_t SelectRHSIdx = i - 1;
1075 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1076 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1077 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1078 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1079 SelectLHS, SelectRHS);
1080 }
1081
1082 // If this is the last action to process, return it to the InstCombiner.
1083 // Otherwise, we insert it before the UDiv and record it so that we may
1084 // use it as part of a joining action (i.e., a SelectInst).
1085 if (e - i != 1) {
1086 Inst->insertBefore(&I);
1087 UDivActions[i].FoldResult = Inst;
1088 } else
1089 return Inst;
1090 }
1091
1092 return nullptr;
1093}
1094
1095Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
1096 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1097 SQ.getWithInstruction(&I)))
1098 return replaceInstUsesWith(I, V);
1099
1100 if (Instruction *X = foldVectorBinop(I))
1101 return X;
1102
1103 // Handle the integer div common cases
1104 if (Instruction *Common = commonIDivTransforms(I))
1105 return Common;
1106
1107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1108 Type *Ty = I.getType();
1109 Value *X;
1110 // sdiv Op0, -1 --> -Op0
1111 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1112 if (match(Op1, m_AllOnes()) ||
1113 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1114 return BinaryOperator::CreateNeg(Op0);
1115
1116 // X / INT_MIN --> X == INT_MIN
1117 if (match(Op1, m_SignMask()))
1118 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1119
1120 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1121 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1122 if (I.isExact() && ((match(Op1, m_Power2()) && match(Op1, m_NonNegative())) ||
1123 match(Op1, m_NegatedPower2()))) {
1124 bool DivisorWasNegative = match(Op1, m_NegatedPower2());
1125 if (DivisorWasNegative)
1126 Op1 = ConstantExpr::getNeg(cast<Constant>(Op1));
1127 auto *AShr = BinaryOperator::CreateExactAShr(
1128 Op0, ConstantExpr::getExactLogBase2(cast<Constant>(Op1)), I.getName());
1129 if (!DivisorWasNegative)
1130 return AShr;
1131 Builder.Insert(AShr);
1132 AShr->setName(I.getName() + ".neg");
1133 return BinaryOperator::CreateNeg(AShr, I.getName());
1134 }
1135
1136 const APInt *Op1C;
1137 if (match(Op1, m_APInt(Op1C))) {
1138 // If the dividend is sign-extended and the constant divisor is small enough
1139 // to fit in the source type, shrink the division to the narrower type:
1140 // (sext X) sdiv C --> sext (X sdiv C)
1141 Value *Op0Src;
1142 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1143 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1144
1145 // In the general case, we need to make sure that the dividend is not the
1146 // minimum signed value because dividing that by -1 is UB. But here, we
1147 // know that the -1 divisor case is already handled above.
1148
1149 Constant *NarrowDivisor =
1150 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1151 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1152 return new SExtInst(NarrowOp, Ty);
1153 }
1154
1155 // -X / C --> X / -C (if the negation doesn't overflow).
1156 // TODO: This could be enhanced to handle arbitrary vector constants by
1157 // checking if all elements are not the min-signed-val.
1158 if (!Op1C->isMinSignedValue() &&
1159 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1160 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1161 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1162 BO->setIsExact(I.isExact());
1163 return BO;
1164 }
1165 }
1166
1167 // -X / Y --> -(X / Y)
1168 Value *Y;
1169 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1170 return BinaryOperator::CreateNSWNeg(
1171 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1172
1173 // abs(X) / X --> X > -1 ? 1 : -1
1174 // X / abs(X) --> X > -1 ? 1 : -1
1175 if (match(&I, m_c_BinOp(
1176 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1177 m_Deferred(X)))) {
1178 Constant *NegOne = ConstantInt::getAllOnesValue(Ty);
1179 Value *Cond = Builder.CreateICmpSGT(X, NegOne);
1180 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1), NegOne);
1181 }
1182
1183 // If the sign bits of both operands are zero (i.e. we can prove they are
1184 // unsigned inputs), turn this into a udiv.
1185 APInt Mask(APInt::getSignMask(Ty->getScalarSizeInBits()));
1186 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1187 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1188 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1189 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1190 BO->setIsExact(I.isExact());
1191 return BO;
1192 }
1193
1194 if (match(Op1, m_NegatedPower2())) {
1195 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1196 // -> -(X udiv (1 << C)) -> -(X u>> C)
1197 return BinaryOperator::CreateNeg(Builder.Insert(foldUDivPow2Cst(
1198 Op0, ConstantExpr::getNeg(cast<Constant>(Op1)), I, *this)));
1199 }
1200
1201 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1202 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1203 // Safe because the only negative value (1 << Y) can take on is
1204 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1205 // the sign bit set.
1206 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1207 BO->setIsExact(I.isExact());
1208 return BO;
1209 }
1210 }
1211
1212 return nullptr;
1213}
1214
1215/// Remove negation and try to convert division into multiplication.
1216static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1217 Constant *C;
1218 if (!match(I.getOperand(1), m_Constant(C)))
1219 return nullptr;
1220
1221 // -X / C --> X / -C
1222 Value *X;
1223 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1224 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
1225
1226 // If the constant divisor has an exact inverse, this is always safe. If not,
1227 // then we can still create a reciprocal if fast-math-flags allow it and the
1228 // constant is a regular number (not zero, infinite, or denormal).
1229 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1230 return nullptr;
1231
1232 // Disallow denormal constants because we don't know what would happen
1233 // on all targets.
1234 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1235 // denorms are flushed?
1236 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1237 if (!RecipC->isNormalFP())
1238 return nullptr;
1239
1240 // X / C --> X * (1 / C)
1241 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1242}
1243
1244/// Remove negation and try to reassociate constant math.
1245static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
1246 Constant *C;
1247 if (!match(I.getOperand(0), m_Constant(C)))
1248 return nullptr;
1249
1250 // C / -X --> -C / X
1251 Value *X;
1252 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1253 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
1254
1255 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1256 return nullptr;
1257
1258 // Try to reassociate C / X expressions where X includes another constant.
1259 Constant *C2, *NewC = nullptr;
1260 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1261 // C / (X * C2) --> (C / C2) / X
1262 NewC = ConstantExpr::getFDiv(C, C2);
1263 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1264 // C / (X / C2) --> (C * C2) / X
1265 NewC = ConstantExpr::getFMul(C, C2);
1266 }
1267 // Disallow denormal constants because we don't know what would happen
1268 // on all targets.
1269 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1270 // denorms are flushed?
1271 if (!NewC || !NewC->isNormalFP())
1272 return nullptr;
1273
1274 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1275}
1276
1277/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1278static Instruction *foldFDivPowDivisor(BinaryOperator &I,
1279 InstCombiner::BuilderTy &Builder) {
1280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1281 auto *II = dyn_cast<IntrinsicInst>(Op1);
1282 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1283 !I.hasAllowReciprocal())
1284 return nullptr;
1285
1286 // Z / pow(X, Y) --> Z * pow(X, -Y)
1287 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1288 // In the general case, this creates an extra instruction, but fmul allows
1289 // for better canonicalization and optimization than fdiv.
1290 Intrinsic::ID IID = II->getIntrinsicID();
1291 SmallVector<Value *> Args;
1292 switch (IID) {
1293 case Intrinsic::pow:
1294 Args.push_back(II->getArgOperand(0));
1295 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1296 break;
1297 case Intrinsic::powi:
1298 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1299 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1300 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1301 // non-standard results, so this corner case should be acceptable if the
1302 // code rules out INF values.
1303 if (!I.hasNoInfs())
1304 return nullptr;
1305 Args.push_back(II->getArgOperand(0));
1306 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1307 break;
1308 case Intrinsic::exp:
1309 case Intrinsic::exp2:
1310 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1311 break;
1312 default:
1313 return nullptr;
1314 }
1315 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1316 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1317}
1318
1319Instruction *InstCombinerImpl::visitFDiv(BinaryOperator &I) {
1320 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1321 I.getFastMathFlags(),
1322 SQ.getWithInstruction(&I)))
1323 return replaceInstUsesWith(I, V);
1324
1325 if (Instruction *X = foldVectorBinop(I))
1326 return X;
1327
1328 if (Instruction *R = foldFDivConstantDivisor(I))
1329 return R;
1330
1331 if (Instruction *R = foldFDivConstantDividend(I))
1332 return R;
1333
1334 if (Instruction *R = foldFPSignBitOps(I))
1335 return R;
1336
1337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1338 if (isa<Constant>(Op0))
1339 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1340 if (Instruction *R = FoldOpIntoSelect(I, SI))
1341 return R;
1342
1343 if (isa<Constant>(Op1))
1344 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1345 if (Instruction *R = FoldOpIntoSelect(I, SI))
1346 return R;
1347
1348 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1349 Value *X, *Y;
1350 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1351 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1352 // (X / Y) / Z => X / (Y * Z)
1353 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1354 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1355 }
1356 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1357 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1358 // Z / (X / Y) => (Y * Z) / X
1359 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1360 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1361 }
1362 // Z / (1.0 / Y) => (Y * Z)
1363 //
1364 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1365 // m_OneUse check is avoided because even in the case of the multiple uses
1366 // for 1.0/Y, the number of instructions remain the same and a division is
1367 // replaced by a multiplication.
1368 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1369 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1370 }
1371
1372 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1373 // sin(X) / cos(X) -> tan(X)
1374 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1375 Value *X;
1376 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1377 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1378 bool IsCot =
1379 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1380 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1381
1382 if ((IsTan || IsCot) &&
1383 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
1384 IRBuilder<> B(&I);
1385 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1386 B.setFastMathFlags(I.getFastMathFlags());
1387 AttributeList Attrs =
1388 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1389 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1390 LibFunc_tanl, B, Attrs);
1391 if (IsCot)
1392 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1393 return replaceInstUsesWith(I, Res);
1394 }
1395 }
1396
1397 // X / (X * Y) --> 1.0 / Y
1398 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1399 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1400 Value *X, *Y;
1401 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1402 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1403 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1404 replaceOperand(I, 1, Y);
1405 return &I;
1406 }
1407
1408 // X / fabs(X) -> copysign(1.0, X)
1409 // fabs(X) / X -> copysign(1.0, X)
1410 if (I.hasNoNaNs() && I.hasNoInfs() &&
1411 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1412 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1413 Value *V = Builder.CreateBinaryIntrinsic(
1414 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1415 return replaceInstUsesWith(I, V);
1416 }
1417
1418 if (Instruction *Mul = foldFDivPowDivisor(I, Builder))
1419 return Mul;
1420
1421 return nullptr;
1422}
1423
1424/// This function implements the transforms common to both integer remainder
1425/// instructions (urem and srem). It is called by the visitors to those integer
1426/// remainder instructions.
1427/// Common integer remainder transforms
1428Instruction *InstCombinerImpl::commonIRemTransforms(BinaryOperator &I) {
1429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1430
1431 // The RHS is known non-zero.
1432 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
6
Assuming 'V' is null
7
Taking false branch
1433 return replaceOperand(I, 1, V);
1434
1435 // Handle cases involving: rem X, (select Cond, Y, Z)
1436 if (simplifyDivRemOfSelectWithZeroOp(I))
8
Calling 'InstCombinerImpl::simplifyDivRemOfSelectWithZeroOp'
1437 return &I;
1438
1439 if (isa<Constant>(Op1)) {
1440 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1441 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1442 if (Instruction *R = FoldOpIntoSelect(I, SI))
1443 return R;
1444 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1445 const APInt *Op1Int;
1446 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1447 (I.getOpcode() == Instruction::URem ||
1448 !Op1Int->isMinSignedValue())) {
1449 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1450 // predecessor blocks, so do this only if we know the srem or urem
1451 // will not fault.
1452 if (Instruction *NV = foldOpIntoPhi(I, PN))
1453 return NV;
1454 }
1455 }
1456
1457 // See if we can fold away this rem instruction.
1458 if (SimplifyDemandedInstructionBits(I))
1459 return &I;
1460 }
1461 }
1462
1463 return nullptr;
1464}
1465
1466Instruction *InstCombinerImpl::visitURem(BinaryOperator &I) {
1467 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1
Assuming 'V' is null
2
Taking false branch
1468 SQ.getWithInstruction(&I)))
1469 return replaceInstUsesWith(I, V);
1470
1471 if (Instruction *X = foldVectorBinop(I))
3
Assuming 'X' is null
4
Taking false branch
1472 return X;
1473
1474 if (Instruction *common = commonIRemTransforms(I))
5
Calling 'InstCombinerImpl::commonIRemTransforms'
1475 return common;
1476
1477 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1478 return NarrowRem;
1479
1480 // X urem Y -> X and Y-1, where Y is a power of 2,
1481 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1482 Type *Ty = I.getType();
1483 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1484 // This may increase instruction count, we don't enforce that Y is a
1485 // constant.
1486 Constant *N1 = Constant::getAllOnesValue(Ty);
1487 Value *Add = Builder.CreateAdd(Op1, N1);
1488 return BinaryOperator::CreateAnd(Op0, Add);
1489 }
1490
1491 // 1 urem X -> zext(X != 1)
1492 if (match(Op0, m_One())) {
1493 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1494 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1495 }
1496
1497 // X urem C -> X < C ? X : X - C, where C >= signbit.
1498 if (match(Op1, m_Negative())) {
1499 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1500 Value *Sub = Builder.CreateSub(Op0, Op1);
1501 return SelectInst::Create(Cmp, Op0, Sub);
1502 }
1503
1504 // If the divisor is a sext of a boolean, then the divisor must be max
1505 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1506 // max unsigned value. In that case, the remainder is 0:
1507 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1508 Value *X;
1509 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1510 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1511 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1512 }
1513
1514 return nullptr;
1515}
1516
1517Instruction *InstCombinerImpl::visitSRem(BinaryOperator &I) {
1518 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1519 SQ.getWithInstruction(&I)))
1520 return replaceInstUsesWith(I, V);
1521
1522 if (Instruction *X = foldVectorBinop(I))
1523 return X;
1524
1525 // Handle the integer rem common cases
1526 if (Instruction *Common = commonIRemTransforms(I))
1527 return Common;
1528
1529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1530 {
1531 const APInt *Y;
1532 // X % -Y -> X % Y
1533 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1534 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
1535 }
1536
1537 // -X srem Y --> -(X srem Y)
1538 Value *X, *Y;
1539 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1540 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1541
1542 // If the sign bits of both operands are zero (i.e. we can prove they are
1543 // unsigned inputs), turn this into a urem.
1544 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1545 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1546 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1547 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1548 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1549 }
1550
1551 // If it's a constant vector, flip any negative values positive.
1552 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1553 Constant *C = cast<Constant>(Op1);
1554 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
1555
1556 bool hasNegative = false;
1557 bool hasMissing = false;
1558 for (unsigned i = 0; i != VWidth; ++i) {
1559 Constant *Elt = C->getAggregateElement(i);
1560 if (!Elt) {
1561 hasMissing = true;
1562 break;
1563 }
1564
1565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1566 if (RHS->isNegative())
1567 hasNegative = true;
1568 }
1569
1570 if (hasNegative && !hasMissing) {
1571 SmallVector<Constant *, 16> Elts(VWidth);
1572 for (unsigned i = 0; i != VWidth; ++i) {
1573 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1574 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1575 if (RHS->isNegative())
1576 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1577 }
1578 }
1579
1580 Constant *NewRHSV = ConstantVector::get(Elts);
1581 if (NewRHSV != C) // Don't loop on -MININT
1582 return replaceOperand(I, 1, NewRHSV);
1583 }
1584 }
1585
1586 return nullptr;
1587}
1588
1589Instruction *InstCombinerImpl::visitFRem(BinaryOperator &I) {
1590 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1591 I.getFastMathFlags(),
1592 SQ.getWithInstruction(&I)))
1593 return replaceInstUsesWith(I, V);
1594
1595 if (Instruction *X = foldVectorBinop(I))
1596 return X;
1597
1598 return nullptr;
1599}

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

/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h

1//===- llvm/Value.h - Definition of the Value class -------------*- 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 declares the Value class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_IR_VALUE_H
14#define LLVM_IR_VALUE_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/iterator_range.h"
20#include "llvm/IR/Use.h"
21#include "llvm/Support/Alignment.h"
22#include "llvm/Support/CBindingWrapping.h"
23#include "llvm/Support/Casting.h"
24#include <cassert>
25#include <iterator>
26#include <memory>
27
28namespace llvm {
29
30class APInt;
31class Argument;
32class BasicBlock;
33class Constant;
34class ConstantData;
35class ConstantAggregate;
36class DataLayout;
37class Function;
38class GlobalAlias;
39class GlobalIFunc;
40class GlobalIndirectSymbol;
41class GlobalObject;
42class GlobalValue;
43class GlobalVariable;
44class InlineAsm;
45class Instruction;
46class LLVMContext;
47class MDNode;
48class Module;
49class ModuleSlotTracker;
50class raw_ostream;
51template<typename ValueTy> class StringMapEntry;
52class Twine;
53class Type;
54class User;
55
56using ValueName = StringMapEntry<Value *>;
57
58//===----------------------------------------------------------------------===//
59// Value Class
60//===----------------------------------------------------------------------===//
61
62/// LLVM Value Representation
63///
64/// This is a very important LLVM class. It is the base class of all values
65/// computed by a program that may be used as operands to other values. Value is
66/// the super class of other important classes such as Instruction and Function.
67/// All Values have a Type. Type is not a subclass of Value. Some values can
68/// have a name and they belong to some Module. Setting the name on the Value
69/// automatically updates the module's symbol table.
70///
71/// Every value has a "use list" that keeps track of which other Values are
72/// using this Value. A Value can also have an arbitrary number of ValueHandle
73/// objects that watch it and listen to RAUW and Destroy events. See
74/// llvm/IR/ValueHandle.h for details.
75class Value {
76 Type *VTy;
77 Use *UseList;
78
79 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
80 friend class ValueHandleBase;
81
82 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
83 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
84
85protected:
86 /// Hold subclass data that can be dropped.
87 ///
88 /// This member is similar to SubclassData, however it is for holding
89 /// information which may be used to aid optimization, but which may be
90 /// cleared to zero without affecting conservative interpretation.
91 unsigned char SubclassOptionalData : 7;
92
93private:
94 /// Hold arbitrary subclass data.
95 ///
96 /// This member is defined by this class, but is not used for anything.
97 /// Subclasses can use it to hold whatever state they find useful. This
98 /// field is initialized to zero by the ctor.
99 unsigned short SubclassData;
100
101protected:
102 /// The number of operands in the subclass.
103 ///
104 /// This member is defined by this class, but not used for anything.
105 /// Subclasses can use it to store their number of operands, if they have
106 /// any.
107 ///
108 /// This is stored here to save space in User on 64-bit hosts. Since most
109 /// instances of Value have operands, 32-bit hosts aren't significantly
110 /// affected.
111 ///
112 /// Note, this should *NOT* be used directly by any class other than User.
113 /// User uses this value to find the Use list.
114 enum : unsigned { NumUserOperandsBits = 27 };
115 unsigned NumUserOperands : NumUserOperandsBits;
116
117 // Use the same type as the bitfield above so that MSVC will pack them.
118 unsigned IsUsedByMD : 1;
119 unsigned HasName : 1;
120 unsigned HasMetadata : 1; // Has metadata attached to this?
121 unsigned HasHungOffUses : 1;
122 unsigned HasDescriptor : 1;
123
124private:
125 template <typename UseT> // UseT == 'Use' or 'const Use'
126 class use_iterator_impl
127 : public std::iterator<std::forward_iterator_tag, UseT *> {
128 friend class Value;
129
130 UseT *U;
131
132 explicit use_iterator_impl(UseT *u) : U(u) {}
133
134 public:
135 use_iterator_impl() : U() {}
136
137 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
138 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
139
140 use_iterator_impl &operator++() { // Preincrement
141 assert(U && "Cannot increment end iterator!")((U && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 141, __PRETTY_FUNCTION__))
;
142 U = U->getNext();
143 return *this;
144 }
145
146 use_iterator_impl operator++(int) { // Postincrement
147 auto tmp = *this;
148 ++*this;
149 return tmp;
150 }
151
152 UseT &operator*() const {
153 assert(U && "Cannot dereference end iterator!")((U && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 153, __PRETTY_FUNCTION__))
;
154 return *U;
155 }
156
157 UseT *operator->() const { return &operator*(); }
158
159 operator use_iterator_impl<const UseT>() const {
160 return use_iterator_impl<const UseT>(U);
161 }
162 };
163
164 template <typename UserTy> // UserTy == 'User' or 'const User'
165 class user_iterator_impl
166 : public std::iterator<std::forward_iterator_tag, UserTy *> {
167 use_iterator_impl<Use> UI;
168 explicit user_iterator_impl(Use *U) : UI(U) {}
169 friend class Value;
170
171 public:
172 user_iterator_impl() = default;
173
174 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
175 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
176
177 /// Returns true if this iterator is equal to user_end() on the value.
178 bool atEnd() const { return *this == user_iterator_impl(); }
179
180 user_iterator_impl &operator++() { // Preincrement
181 ++UI;
182 return *this;
183 }
184
185 user_iterator_impl operator++(int) { // Postincrement
186 auto tmp = *this;
187 ++*this;
188 return tmp;
189 }
190
191 // Retrieve a pointer to the current User.
192 UserTy *operator*() const {
193 return UI->getUser();
194 }
195
196 UserTy *operator->() const { return operator*(); }
197
198 operator user_iterator_impl<const UserTy>() const {
199 return user_iterator_impl<const UserTy>(*UI);
200 }
201
202 Use &getUse() const { return *UI; }
203 };
204
205protected:
206 Value(Type *Ty, unsigned scid);
207
208 /// Value's destructor should be virtual by design, but that would require
209 /// that Value and all of its subclasses have a vtable that effectively
210 /// duplicates the information in the value ID. As a size optimization, the
211 /// destructor has been protected, and the caller should manually call
212 /// deleteValue.
213 ~Value(); // Use deleteValue() to delete a generic Value.
214
215public:
216 Value(const Value &) = delete;
217 Value &operator=(const Value &) = delete;
218
219 /// Delete a pointer to a generic Value.
220 void deleteValue();
221
222 /// Support for debugging, callable in GDB: V->dump()
223 void dump() const;
224
225 /// Implement operator<< on Value.
226 /// @{
227 void print(raw_ostream &O, bool IsForDebug = false) const;
228 void print(raw_ostream &O, ModuleSlotTracker &MST,
229 bool IsForDebug = false) const;
230 /// @}
231
232 /// Print the name of this Value out to the specified raw_ostream.
233 ///
234 /// This is useful when you just want to print 'int %reg126', not the
235 /// instruction that generated it. If you specify a Module for context, then
236 /// even constanst get pretty-printed; for example, the type of a null
237 /// pointer is printed symbolically.
238 /// @{
239 void printAsOperand(raw_ostream &O, bool PrintType = true,
240 const Module *M = nullptr) const;
241 void printAsOperand(raw_ostream &O, bool PrintType,
242 ModuleSlotTracker &MST) const;
243 /// @}
244
245 /// All values are typed, get the type of this value.
246 Type *getType() const { return VTy; }
247
248 /// All values hold a context through their type.
249 LLVMContext &getContext() const;
250
251 // All values can potentially be named.
252 bool hasName() const { return HasName; }
253 ValueName *getValueName() const;
254 void setValueName(ValueName *VN);
255
256private:
257 void destroyValueName();
258 enum class ReplaceMetadataUses { No, Yes };
259 void doRAUW(Value *New, ReplaceMetadataUses);
260 void setNameImpl(const Twine &Name);
261
262public:
263 /// Return a constant reference to the value's name.
264 ///
265 /// This guaranteed to return the same reference as long as the value is not
266 /// modified. If the value has a name, this does a hashtable lookup, so it's
267 /// not free.
268 StringRef getName() const;
269
270 /// Change the name of the value.
271 ///
272 /// Choose a new unique name if the provided name is taken.
273 ///
274 /// \param Name The new name; or "" if the value's name should be removed.
275 void setName(const Twine &Name);
276
277 /// Transfer the name from V to this value.
278 ///
279 /// After taking V's name, sets V's name to empty.
280 ///
281 /// \note It is an error to call V->takeName(V).
282 void takeName(Value *V);
283
284#ifndef NDEBUG
285 std::string getNameOrAsOperand() const;
286#endif
287
288 /// Change all uses of this to point to a new Value.
289 ///
290 /// Go through the uses list for this definition and make each use point to
291 /// "V" instead of "this". After this completes, 'this's use list is
292 /// guaranteed to be empty.
293 void replaceAllUsesWith(Value *V);
294
295 /// Change non-metadata uses of this to point to a new Value.
296 ///
297 /// Go through the uses list for this definition and make each use point to
298 /// "V" instead of "this". This function skips metadata entries in the list.
299 void replaceNonMetadataUsesWith(Value *V);
300
301 /// Go through the uses list for this definition and make each use point
302 /// to "V" if the callback ShouldReplace returns true for the given Use.
303 /// Unlike replaceAllUsesWith() this function does not support basic block
304 /// values or constant users.
305 void replaceUsesWithIf(Value *New,
306 llvm::function_ref<bool(Use &U)> ShouldReplace) {
307 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!")((New && "Value::replaceUsesWithIf(<null>) is invalid!"
) ? static_cast<void> (0) : __assert_fail ("New && \"Value::replaceUsesWithIf(<null>) is invalid!\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 307, __PRETTY_FUNCTION__))
;
308 assert(New->getType() == getType() &&((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 309, __PRETTY_FUNCTION__))
309 "replaceUses of value with new value of different type!")((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 309, __PRETTY_FUNCTION__))
;
310
311 for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
312 Use &U = *UI;
313 ++UI;
314 if (!ShouldReplace(U))
315 continue;
316 U.set(New);
317 }
318 }
319
320 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
321 /// make each use point to "V" instead of "this" when the use is outside the
322 /// block. 'This's use list is expected to have at least one element.
323 /// Unlike replaceAllUsesWith() this function does not support basic block
324 /// values or constant users.
325 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
326
327 //----------------------------------------------------------------------
328 // Methods for handling the chain of uses of this Value.
329 //
330 // Materializing a function can introduce new uses, so these methods come in
331 // two variants:
332 // The methods that start with materialized_ check the uses that are
333 // currently known given which functions are materialized. Be very careful
334 // when using them since you might not get all uses.
335 // The methods that don't start with materialized_ assert that modules is
336 // fully materialized.
337 void assertModuleIsMaterializedImpl() const;
338 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
339 // around in release builds of Value.cpp to be linked with other code built
340 // in debug mode. But this avoids calling it in any of the release built code.
341 void assertModuleIsMaterialized() const {
342#ifndef NDEBUG
343 assertModuleIsMaterializedImpl();
344#endif
345 }
346
347 bool use_empty() const {
348 assertModuleIsMaterialized();
349 return UseList == nullptr;
22
Assuming the condition is false
23
Returning zero, which participates in a condition later
350 }
351
352 bool materialized_use_empty() const {
353 return UseList == nullptr;
354 }
355
356 using use_iterator = use_iterator_impl<Use>;
357 using const_use_iterator = use_iterator_impl<const Use>;
358
359 use_iterator materialized_use_begin() { return use_iterator(UseList); }
360 const_use_iterator materialized_use_begin() const {
361 return const_use_iterator(UseList);
362 }
363 use_iterator use_begin() {
364 assertModuleIsMaterialized();
365 return materialized_use_begin();
366 }
367 const_use_iterator use_begin() const {
368 assertModuleIsMaterialized();
369 return materialized_use_begin();
370 }
371 use_iterator use_end() { return use_iterator(); }
372 const_use_iterator use_end() const { return const_use_iterator(); }
373 iterator_range<use_iterator> materialized_uses() {
374 return make_range(materialized_use_begin(), use_end());
375 }
376 iterator_range<const_use_iterator> materialized_uses() const {
377 return make_range(materialized_use_begin(), use_end());
378 }
379 iterator_range<use_iterator> uses() {
380 assertModuleIsMaterialized();
381 return materialized_uses();
382 }
383 iterator_range<const_use_iterator> uses() const {
384 assertModuleIsMaterialized();
385 return materialized_uses();
386 }
387
388 bool user_empty() const {
389 assertModuleIsMaterialized();
390 return UseList == nullptr;
391 }
392
393 using user_iterator = user_iterator_impl<User>;
394 using const_user_iterator = user_iterator_impl<const User>;
395
396 user_iterator materialized_user_begin() { return user_iterator(UseList); }
397 const_user_iterator materialized_user_begin() const {
398 return const_user_iterator(UseList);
399 }
400 user_iterator user_begin() {
401 assertModuleIsMaterialized();
402 return materialized_user_begin();
403 }
404 const_user_iterator user_begin() const {
405 assertModuleIsMaterialized();
406 return materialized_user_begin();
407 }
408 user_iterator user_end() { return user_iterator(); }
409 const_user_iterator user_end() const { return const_user_iterator(); }
410 User *user_back() {
411 assertModuleIsMaterialized();
412 return *materialized_user_begin();
413 }
414 const User *user_back() const {
415 assertModuleIsMaterialized();
416 return *materialized_user_begin();
417 }
418 iterator_range<user_iterator> materialized_users() {
419 return make_range(materialized_user_begin(), user_end());
420 }
421 iterator_range<const_user_iterator> materialized_users() const {
422 return make_range(materialized_user_begin(), user_end());
423 }
424 iterator_range<user_iterator> users() {
425 assertModuleIsMaterialized();
426 return materialized_users();
427 }
428 iterator_range<const_user_iterator> users() const {
429 assertModuleIsMaterialized();
430 return materialized_users();
431 }
432
433 /// Return true if there is exactly one use of this value.
434 ///
435 /// This is specialized because it is a common request and does not require
436 /// traversing the whole use list.
437 bool hasOneUse() const { return hasSingleElement(uses()); }
438
439 /// Return true if this Value has exactly N uses.
440 bool hasNUses(unsigned N) const;
441
442 /// Return true if this value has N uses or more.
443 ///
444 /// This is logically equivalent to getNumUses() >= N.
445 bool hasNUsesOrMore(unsigned N) const;
446
447 /// Return true if there is exactly one user of this value.
448 ///
449 /// Note that this is not the same as "has one use". If a value has one use,
450 /// then there certainly is a single user. But if value has several uses,
451 /// it is possible that all uses are in a single user, or not.
452 ///
453 /// This check is potentially costly, since it requires traversing,
454 /// in the worst case, the whole use list of a value.
455 bool hasOneUser() const;
456
457 /// Return true if there is exactly one use of this value that cannot be
458 /// dropped.
459 ///
460 /// This is specialized because it is a common request and does not require
461 /// traversing the whole use list.
462 Use *getSingleUndroppableUse();
463 const Use *getSingleUndroppableUse() const {
464 return const_cast<Value *>(this)->getSingleUndroppableUse();
465 }
466
467 /// Return true if there this value.
468 ///
469 /// This is specialized because it is a common request and does not require
470 /// traversing the whole use list.
471 bool hasNUndroppableUses(unsigned N) const;
472
473 /// Return true if this value has N uses or more.
474 ///
475 /// This is logically equivalent to getNumUses() >= N.
476 bool hasNUndroppableUsesOrMore(unsigned N) const;
477
478 /// Remove every uses that can safely be removed.
479 ///
480 /// This will remove for example uses in llvm.assume.
481 /// This should be used when performing want to perform a tranformation but
482 /// some Droppable uses pervent it.
483 /// This function optionally takes a filter to only remove some droppable
484 /// uses.
485 void dropDroppableUses(llvm::function_ref<bool(const Use *)> ShouldDrop =
486 [](const Use *) { return true; });
487
488 /// Remove every use of this value in \p User that can safely be removed.
489 void dropDroppableUsesIn(User &Usr);
490
491 /// Remove the droppable use \p U.
492 static void dropDroppableUse(Use &U);
493
494 /// Check if this value is used in the specified basic block.
495 bool isUsedInBasicBlock(const BasicBlock *BB) const;
496
497 /// This method computes the number of uses of this Value.
498 ///
499 /// This is a linear time operation. Use hasOneUse, hasNUses, or
500 /// hasNUsesOrMore to check for specific values.
501 unsigned getNumUses() const;
502
503 /// This method should only be used by the Use class.
504 void addUse(Use &U) { U.addToList(&UseList); }
505
506 /// Concrete subclass of this.
507 ///
508 /// An enumeration for keeping track of the concrete subclass of Value that
509 /// is actually instantiated. Values of this enumeration are kept in the
510 /// Value classes SubclassID field. They are used for concrete type
511 /// identification.
512 enum ValueTy {
513#define HANDLE_VALUE(Name) Name##Val,
514#include "llvm/IR/Value.def"
515
516 // Markers:
517#define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
518#include "llvm/IR/Value.def"
519 };
520
521 /// Return an ID for the concrete type of this object.
522 ///
523 /// This is used to implement the classof checks. This should not be used
524 /// for any other purpose, as the values may change as LLVM evolves. Also,
525 /// note that for instructions, the Instruction's opcode is added to
526 /// InstructionVal. So this means three things:
527 /// # there is no value with code InstructionVal (no opcode==0).
528 /// # there are more possible values for the value type than in ValueTy enum.
529 /// # the InstructionVal enumerator must be the highest valued enumerator in
530 /// the ValueTy enum.
531 unsigned getValueID() const {
532 return SubclassID;
533 }
534
535 /// Return the raw optional flags value contained in this value.
536 ///
537 /// This should only be used when testing two Values for equivalence.
538 unsigned getRawSubclassOptionalData() const {
539 return SubclassOptionalData;
540 }
541
542 /// Clear the optional flags contained in this value.
543 void clearSubclassOptionalData() {
544 SubclassOptionalData = 0;
545 }
546
547 /// Check the optional flags for equality.
548 bool hasSameSubclassOptionalData(const Value *V) const {
549 return SubclassOptionalData == V->SubclassOptionalData;
550 }
551
552 /// Return true if there is a value handle associated with this value.
553 bool hasValueHandle() const { return HasValueHandle; }
554
555 /// Return true if there is metadata referencing this value.
556 bool isUsedByMetadata() const { return IsUsedByMD; }
557
558protected:
559 /// Get the current metadata attachments for the given kind, if any.
560 ///
561 /// These functions require that the value have at most a single attachment
562 /// of the given kind, and return \c nullptr if such an attachment is missing.
563 /// @{
564 MDNode *getMetadata(unsigned KindID) const;
565 MDNode *getMetadata(StringRef Kind) const;
566 /// @}
567
568 /// Appends all attachments with the given ID to \c MDs in insertion order.
569 /// If the Value has no attachments with the given ID, or if ID is invalid,
570 /// leaves MDs unchanged.
571 /// @{
572 void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const;
573 void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const;
574 /// @}
575
576 /// Appends all metadata attached to this value to \c MDs, sorting by
577 /// KindID. The first element of each pair returned is the KindID, the second
578 /// element is the metadata value. Attachments with the same ID appear in
579 /// insertion order.
580 void
581 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
582
583 /// Return true if this value has any metadata attached to it.
584 bool hasMetadata() const { return (bool)HasMetadata; }
585
586 /// Return true if this value has the given type of metadata attached.
587 /// @{
588 bool hasMetadata(unsigned KindID) const {
589 return getMetadata(KindID) != nullptr;
590 }
591 bool hasMetadata(StringRef Kind) const {
592 return getMetadata(Kind) != nullptr;
593 }
594 /// @}
595
596 /// Set a particular kind of metadata attachment.
597 ///
598 /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
599 /// replacing it if it already exists.
600 /// @{
601 void setMetadata(unsigned KindID, MDNode *Node);
602 void setMetadata(StringRef Kind, MDNode *Node);
603 /// @}
604
605 /// Add a metadata attachment.
606 /// @{
607 void addMetadata(unsigned KindID, MDNode &MD);
608 void addMetadata(StringRef Kind, MDNode &MD);
609 /// @}
610
611 /// Erase all metadata attachments with the given kind.
612 ///
613 /// \returns true if any metadata was removed.
614 bool eraseMetadata(unsigned KindID);
615
616 /// Erase all metadata attached to this Value.
617 void clearMetadata();
618
619public:
620 /// Return true if this value is a swifterror value.
621 ///
622 /// swifterror values can be either a function argument or an alloca with a
623 /// swifterror attribute.
624 bool isSwiftError() const;
625
626 /// Strip off pointer casts, all-zero GEPs and address space casts.
627 ///
628 /// Returns the original uncasted value. If this is called on a non-pointer
629 /// value, it returns 'this'.
630 const Value *stripPointerCasts() const;
631 Value *stripPointerCasts() {
632 return const_cast<Value *>(
633 static_cast<const Value *>(this)->stripPointerCasts());
634 }
635
636 /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
637 ///
638 /// Returns the original uncasted value. If this is called on a non-pointer
639 /// value, it returns 'this'.
640 const Value *stripPointerCastsAndAliases() const;
641 Value *stripPointerCastsAndAliases() {
642 return const_cast<Value *>(
643 static_cast<const Value *>(this)->stripPointerCastsAndAliases());
644 }
645
646 /// Strip off pointer casts, all-zero GEPs and address space casts
647 /// but ensures the representation of the result stays the same.
648 ///
649 /// Returns the original uncasted value with the same representation. If this
650 /// is called on a non-pointer value, it returns 'this'.
651 const Value *stripPointerCastsSameRepresentation() const;
652 Value *stripPointerCastsSameRepresentation() {
653 return const_cast<Value *>(static_cast<const Value *>(this)
654 ->stripPointerCastsSameRepresentation());
655 }
656
657 /// Strip off pointer casts, all-zero GEPs, single-argument phi nodes and
658 /// invariant group info.
659 ///
660 /// Returns the original uncasted value. If this is called on a non-pointer
661 /// value, it returns 'this'. This function should be used only in
662 /// Alias analysis.
663 const Value *stripPointerCastsForAliasAnalysis() const;
664 Value *stripPointerCastsForAliasAnalysis() {
665 return const_cast<Value *>(static_cast<const Value *>(this)
666 ->stripPointerCastsForAliasAnalysis());
667 }
668
669 /// Strip off pointer casts and all-constant inbounds GEPs.
670 ///
671 /// Returns the original pointer value. If this is called on a non-pointer
672 /// value, it returns 'this'.
673 const Value *stripInBoundsConstantOffsets() const;
674 Value *stripInBoundsConstantOffsets() {
675 return const_cast<Value *>(
676 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
677 }
678
679 /// Accumulate the constant offset this value has compared to a base pointer.
680 /// Only 'getelementptr' instructions (GEPs) are accumulated but other
681 /// instructions, e.g., casts, are stripped away as well.
682 /// The accumulated constant offset is added to \p Offset and the base
683 /// pointer is returned.
684 ///
685 /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
686 /// the address space of 'this' pointer value, e.g., use
687 /// DataLayout::getIndexTypeSizeInBits(Ty).
688 ///
689 /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and
690 /// accumulated even if the GEP is not "inbounds".
691 ///
692 /// If \p ExternalAnalysis is provided it will be used to calculate a offset
693 /// when a operand of GEP is not constant.
694 /// For example, for a value \p ExternalAnalysis might try to calculate a
695 /// lower bound. If \p ExternalAnalysis is successful, it should return true.
696 ///
697 /// If this is called on a non-pointer value, it returns 'this' and the
698 /// \p Offset is not modified.
699 ///
700 /// Note that this function will never return a nullptr. It will also never
701 /// manipulate the \p Offset in a way that would not match the difference
702 /// between the underlying value and the returned one. Thus, if no constant
703 /// offset was found, the returned value is the underlying one and \p Offset
704 /// is unchanged.
705 const Value *stripAndAccumulateConstantOffsets(
706 const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
707 function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
708 nullptr) const;
709 Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
710 bool AllowNonInbounds) {
711 return const_cast<Value *>(
712 static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
713 DL, Offset, AllowNonInbounds));
714 }
715
716 /// This is a wrapper around stripAndAccumulateConstantOffsets with the
717 /// in-bounds requirement set to false.
718 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
719 APInt &Offset) const {
720 return stripAndAccumulateConstantOffsets(DL, Offset,
721 /* AllowNonInbounds */ false);
722 }
723 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
724 APInt &Offset) {
725 return stripAndAccumulateConstantOffsets(DL, Offset,
726 /* AllowNonInbounds */ false);
727 }
728
729 /// Strip off pointer casts and inbounds GEPs.
730 ///
731 /// Returns the original pointer value. If this is called on a non-pointer
732 /// value, it returns 'this'.
733 const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
734 [](const Value *) {}) const;
735 inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
736 [](const Value *) {}) {
737 return const_cast<Value *>(
738 static_cast<const Value *>(this)->stripInBoundsOffsets(Func));
739 }
740
741 /// Returns the number of bytes known to be dereferenceable for the
742 /// pointer value.
743 ///
744 /// If CanBeNull is set by this function the pointer can either be null or be
745 /// dereferenceable up to the returned number of bytes.
746 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
747 bool &CanBeNull) const;
748
749 /// Returns an alignment of the pointer value.
750 ///
751 /// Returns an alignment which is either specified explicitly, e.g. via
752 /// align attribute of a function argument, or guaranteed by DataLayout.
753 Align getPointerAlignment(const DataLayout &DL) const;
754
755 /// Translate PHI node to its predecessor from the given basic block.
756 ///
757 /// If this value is a PHI node with CurBB as its parent, return the value in
758 /// the PHI node corresponding to PredBB. If not, return ourself. This is
759 /// useful if you want to know the value something has in a predecessor
760 /// block.
761 const Value *DoPHITranslation(const BasicBlock *CurBB,
762 const BasicBlock *PredBB) const;
763 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
764 return const_cast<Value *>(
765 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
766 }
767
768 /// The maximum alignment for instructions.
769 ///
770 /// This is the greatest alignment value supported by load, store, and alloca
771 /// instructions, and global values.
772 static const unsigned MaxAlignmentExponent = 29;
773 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
774
775 /// Mutate the type of this Value to be of the specified type.
776 ///
777 /// Note that this is an extremely dangerous operation which can create
778 /// completely invalid IR very easily. It is strongly recommended that you
779 /// recreate IR objects with the right types instead of mutating them in
780 /// place.
781 void mutateType(Type *Ty) {
782 VTy = Ty;
783 }
784
785 /// Sort the use-list.
786 ///
787 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
788 /// expected to compare two \a Use references.
789 template <class Compare> void sortUseList(Compare Cmp);
790
791 /// Reverse the use-list.
792 void reverseUseList();
793
794private:
795 /// Merge two lists together.
796 ///
797 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
798 /// "equal" items from L before items from R.
799 ///
800 /// \return the first element in the list.
801 ///
802 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
803 template <class Compare>
804 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
805 Use *Merged;
806 Use **Next = &Merged;
807
808 while (true) {
809 if (!L) {
810 *Next = R;
811 break;
812 }
813 if (!R) {
814 *Next = L;
815 break;
816 }
817 if (Cmp(*R, *L)) {
818 *Next = R;
819 Next = &R->Next;
820 R = R->Next;
821 } else {
822 *Next = L;
823 Next = &L->Next;
824 L = L->Next;
825 }
826 }
827
828 return Merged;
829 }
830
831protected:
832 unsigned short getSubclassDataFromValue() const { return SubclassData; }
833 void setValueSubclassData(unsigned short D) { SubclassData = D; }
834};
835
836struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
837
838/// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
839/// Those don't work because Value and Instruction's destructors are protected,
840/// aren't virtual, and won't destroy the complete object.
841using unique_value = std::unique_ptr<Value, ValueDeleter>;
842
843inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
844 V.print(OS);
845 return OS;
846}
847
848void Use::set(Value *V) {
849 if (Val) removeFromList();
850 Val = V;
851 if (V) V->addUse(*this);
852}
853
854Value *Use::operator=(Value *RHS) {
855 set(RHS);
856 return RHS;
857}
858
859const Use &Use::operator=(const Use &RHS) {
860 set(RHS.Val);
861 return *this;
862}
863
864template <class Compare> void Value::sortUseList(Compare Cmp) {
865 if (!UseList || !UseList->Next)
866 // No need to sort 0 or 1 uses.
867 return;
868
869 // Note: this function completely ignores Prev pointers until the end when
870 // they're fixed en masse.
871
872 // Create a binomial vector of sorted lists, visiting uses one at a time and
873 // merging lists as necessary.
874 const unsigned MaxSlots = 32;
875 Use *Slots[MaxSlots];
876
877 // Collect the first use, turning it into a single-item list.
878 Use *Next = UseList->Next;
879 UseList->Next = nullptr;
880 unsigned NumSlots = 1;
881 Slots[0] = UseList;
882
883 // Collect all but the last use.
884 while (Next->Next) {
885 Use *Current = Next;
886 Next = Current->Next;
887
888 // Turn Current into a single-item list.
889 Current->Next = nullptr;
890
891 // Save Current in the first available slot, merging on collisions.
892 unsigned I;
893 for (I = 0; I < NumSlots; ++I) {
894 if (!Slots[I])
895 break;
896
897 // Merge two lists, doubling the size of Current and emptying slot I.
898 //
899 // Since the uses in Slots[I] originally preceded those in Current, send
900 // Slots[I] in as the left parameter to maintain a stable sort.
901 Current = mergeUseLists(Slots[I], Current, Cmp);
902 Slots[I] = nullptr;
903 }
904 // Check if this is a new slot.
905 if (I == NumSlots) {
906 ++NumSlots;
907 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32")((NumSlots <= MaxSlots && "Use list bigger than 2^32"
) ? static_cast<void> (0) : __assert_fail ("NumSlots <= MaxSlots && \"Use list bigger than 2^32\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 907, __PRETTY_FUNCTION__))
;
908 }
909
910 // Found an open slot.
911 Slots[I] = Current;
912 }
913
914 // Merge all the lists together.
915 assert(Next && "Expected one more Use")((Next && "Expected one more Use") ? static_cast<void
> (0) : __assert_fail ("Next && \"Expected one more Use\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 915, __PRETTY_FUNCTION__))
;
916 assert(!Next->Next && "Expected only one Use")((!Next->Next && "Expected only one Use") ? static_cast
<void> (0) : __assert_fail ("!Next->Next && \"Expected only one Use\""
, "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/IR/Value.h"
, 916, __PRETTY_FUNCTION__))
;
917 UseList = Next;
918 for (unsigned I = 0; I < NumSlots; ++I)
919 if (Slots[I])
920 // Since the uses in Slots[I] originally preceded those in UseList, send
921 // Slots[I] in as the left parameter to maintain a stable sort.
922 UseList = mergeUseLists(Slots[I], UseList, Cmp);
923
924 // Fix the Prev pointers.
925 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
926 I->Prev = Prev;
927 Prev = &I->Next;
928 }
929}
930
931// isa - Provide some specializations of isa so that we don't have to include
932// the subtype header files to test to see if the value is a subclass...
933//
934template <> struct isa_impl<Constant, Value> {
935 static inline bool doit(const Value &Val) {
936 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
937 return Val.getValueID() <= Value::ConstantLastVal;
938 }
939};
940
941template <> struct isa_impl<ConstantData, Value> {
942 static inline bool doit(const Value &Val) {
943 return Val.getValueID() >= Value::ConstantDataFirstVal &&
944 Val.getValueID() <= Value::ConstantDataLastVal;
945 }
946};
947
948template <> struct isa_impl<ConstantAggregate, Value> {
949 static inline bool doit(const Value &Val) {
950 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
951 Val.getValueID() <= Value::ConstantAggregateLastVal;
952 }
953};
954
955template <> struct isa_impl<Argument, Value> {
956 static inline bool doit (const Value &Val) {
957 return Val.getValueID() == Value::ArgumentVal;
958 }
959};
960
961template <> struct isa_impl<InlineAsm, Value> {
962 static inline bool doit(const Value &Val) {
963 return Val.getValueID() == Value::InlineAsmVal;
964 }
965};
966
967template <> struct isa_impl<Instruction, Value> {
968 static inline bool doit(const Value &Val) {
969 return Val.getValueID() >= Value::InstructionVal;
970 }
971};
972
973template <> struct isa_impl<BasicBlock, Value> {
974 static inline bool doit(const Value &Val) {
975 return Val.getValueID() == Value::BasicBlockVal;
976 }
977};
978
979template <> struct isa_impl<Function, Value> {
980 static inline bool doit(const Value &Val) {
981 return Val.getValueID() == Value::FunctionVal;
982 }
983};
984
985template <> struct isa_impl<GlobalVariable, Value> {
986 static inline bool doit(const Value &Val) {
987 return Val.getValueID() == Value::GlobalVariableVal;
988 }
989};
990
991template <> struct isa_impl<GlobalAlias, Value> {
992 static inline bool doit(const Value &Val) {
993 return Val.getValueID() == Value::GlobalAliasVal;
994 }
995};
996
997template <> struct isa_impl<GlobalIFunc, Value> {
998 static inline bool doit(const Value &Val) {
999 return Val.getValueID() == Value::GlobalIFuncVal;
1000 }
1001};
1002
1003template <> struct isa_impl<GlobalIndirectSymbol, Value> {
1004 static inline bool doit(const Value &Val) {
1005 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
1006 }
1007};
1008
1009template <> struct isa_impl<GlobalValue, Value> {
1010 static inline bool doit(const Value &Val) {
1011 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
1012 }
1013};
1014
1015template <> struct isa_impl<GlobalObject, Value> {
1016 static inline bool doit(const Value &Val) {
1017 return isa<GlobalVariable>(Val) || isa<Function>(Val);
1018 }
1019};
1020
1021// Create wrappers for C Binding types (see CBindingWrapping.h).
1022DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)inline Value *unwrap(LLVMValueRef P) { return reinterpret_cast
<Value*>(P); } inline LLVMValueRef wrap(const Value *P)
{ return reinterpret_cast<LLVMValueRef>(const_cast<
Value*>(P)); } template<typename T> inline T *unwrap
(LLVMValueRef P) { return cast<T>(unwrap(P)); }
1023
1024// Specialized opaque value conversions.
1025inline Value **unwrap(LLVMValueRef *Vals) {
1026 return reinterpret_cast<Value**>(Vals);
1027}
1028
1029template<typename T>
1030inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
1031#ifndef NDEBUG
1032 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
1033 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
1034#endif
1035 (void)Length;
1036 return reinterpret_cast<T**>(Vals);
1037}
1038
1039inline LLVMValueRef *wrap(const Value **Vals) {
1040 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
1041}
1042
1043} // end namespace llvm
1044
1045#endif // LLVM_IR_VALUE_H

/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/ADT/ilist_iterator.h

1//===- llvm/ADT/ilist_iterator.h - Intrusive List Iterator ------*- 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#ifndef LLVM_ADT_ILIST_ITERATOR_H
10#define LLVM_ADT_ILIST_ITERATOR_H
11
12#include "llvm/ADT/ilist_node.h"
13#include <cassert>
14#include <cstddef>
15#include <iterator>
16#include <type_traits>
17
18namespace llvm {
19
20namespace ilist_detail {
21
22/// Find const-correct node types.
23template <class OptionsT, bool IsConst> struct IteratorTraits;
24template <class OptionsT> struct IteratorTraits<OptionsT, false> {
25 using value_type = typename OptionsT::value_type;
26 using pointer = typename OptionsT::pointer;
27 using reference = typename OptionsT::reference;
28 using node_pointer = ilist_node_impl<OptionsT> *;
29 using node_reference = ilist_node_impl<OptionsT> &;
30};
31template <class OptionsT> struct IteratorTraits<OptionsT, true> {
32 using value_type = const typename OptionsT::value_type;
33 using pointer = typename OptionsT::const_pointer;
34 using reference = typename OptionsT::const_reference;
35 using node_pointer = const ilist_node_impl<OptionsT> *;
36 using node_reference = const ilist_node_impl<OptionsT> &;
37};
38
39template <bool IsReverse> struct IteratorHelper;
40template <> struct IteratorHelper<false> : ilist_detail::NodeAccess {
41 using Access = ilist_detail::NodeAccess;
42
43 template <class T> static void increment(T *&I) { I = Access::getNext(*I); }
44 template <class T> static void decrement(T *&I) { I = Access::getPrev(*I); }
45};
46template <> struct IteratorHelper<true> : ilist_detail::NodeAccess {
47 using Access = ilist_detail::NodeAccess;
48
49 template <class T> static void increment(T *&I) { I = Access::getPrev(*I); }
50 template <class T> static void decrement(T *&I) { I = Access::getNext(*I); }
51};
52
53} // end namespace ilist_detail
54
55/// Iterator for intrusive lists based on ilist_node.
56template <class OptionsT, bool IsReverse, bool IsConst>
57class ilist_iterator : ilist_detail::SpecificNodeAccess<OptionsT> {
58 friend ilist_iterator<OptionsT, IsReverse, !IsConst>;
59 friend ilist_iterator<OptionsT, !IsReverse, IsConst>;
60 friend ilist_iterator<OptionsT, !IsReverse, !IsConst>;
61
62 using Traits = ilist_detail::IteratorTraits<OptionsT, IsConst>;
63 using Access = ilist_detail::SpecificNodeAccess<OptionsT>;
64
65public:
66 using value_type = typename Traits::value_type;
67 using pointer = typename Traits::pointer;
68 using reference = typename Traits::reference;
69 using difference_type = ptrdiff_t;
70 using iterator_category = std::bidirectional_iterator_tag;
71 using const_pointer = typename OptionsT::const_pointer;
72 using const_reference = typename OptionsT::const_reference;
73
74private:
75 using node_pointer = typename Traits::node_pointer;
76 using node_reference = typename Traits::node_reference;
77
78 node_pointer NodePtr = nullptr;
79
80public:
81 /// Create from an ilist_node.
82 explicit ilist_iterator(node_reference N) : NodePtr(&N) {}
83
84 explicit ilist_iterator(pointer NP) : NodePtr(Access::getNodePtr(NP)) {}
85 explicit ilist_iterator(reference NR) : NodePtr(Access::getNodePtr(&NR)) {}
86 ilist_iterator() = default;
87
88 // This is templated so that we can allow constructing a const iterator from
89 // a nonconst iterator...
90 template <bool RHSIsConst>
91 ilist_iterator(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS,
92 std::enable_if_t<IsConst || !RHSIsConst, void *> = nullptr)
93 : NodePtr(RHS.NodePtr) {}
94
95 // This is templated so that we can allow assigning to a const iterator from
96 // a nonconst iterator...
97 template <bool RHSIsConst>
98 std::enable_if_t<IsConst || !RHSIsConst, ilist_iterator &>
99 operator=(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS) {
100 NodePtr = RHS.NodePtr;
101 return *this;
102 }
103
104 /// Explicit conversion between forward/reverse iterators.
105 ///
106 /// Translate between forward and reverse iterators without changing range
107 /// boundaries. The resulting iterator will dereference (and have a handle)
108 /// to the previous node, which is somewhat unexpected; but converting the
109 /// two endpoints in a range will give the same range in reverse.
110 ///
111 /// This matches std::reverse_iterator conversions.
112 explicit ilist_iterator(
113 const ilist_iterator<OptionsT, !IsReverse, IsConst> &RHS)
114 : ilist_iterator(++RHS.getReverse()) {}
115
116 /// Get a reverse iterator to the same node.
117 ///
118 /// Gives a reverse iterator that will dereference (and have a handle) to the
119 /// same node. Converting the endpoint iterators in a range will give a
120 /// different range; for range operations, use the explicit conversions.
121 ilist_iterator<OptionsT, !IsReverse, IsConst> getReverse() const {
122 if (NodePtr)
123 return ilist_iterator<OptionsT, !IsReverse, IsConst>(*NodePtr);
124 return ilist_iterator<OptionsT, !IsReverse, IsConst>();
125 }
126
127 /// Const-cast.
128 ilist_iterator<OptionsT, IsReverse, false> getNonConst() const {
129 if (NodePtr)
130 return ilist_iterator<OptionsT, IsReverse, false>(
131 const_cast<typename ilist_iterator<OptionsT, IsReverse,
132 false>::node_reference>(*NodePtr));
133 return ilist_iterator<OptionsT, IsReverse, false>();
134 }
135
136 // Accessors...
137 reference operator*() const {
138 assert(!NodePtr->isKnownSentinel())((!NodePtr->isKnownSentinel()) ? static_cast<void> (
0) : __assert_fail ("!NodePtr->isKnownSentinel()", "/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include/llvm/ADT/ilist_iterator.h"
, 138, __PRETTY_FUNCTION__))
;
139 return *Access::getValuePtr(NodePtr);
140 }
141 pointer operator->() const { return &operator*(); }
142
143 // Comparison operators
144 friend bool operator==(const ilist_iterator &LHS, const ilist_iterator &RHS) {
145 return LHS.NodePtr == RHS.NodePtr;
146 }
147 friend bool operator!=(const ilist_iterator &LHS, const ilist_iterator &RHS) {
148 return LHS.NodePtr != RHS.NodePtr;
26
Assuming 'LHS.NodePtr' is not equal to 'RHS.NodePtr'
27
Returning the value 1, which participates in a condition later
39
Assuming 'LHS.NodePtr' is not equal to 'RHS.NodePtr'
40
Returning the value 1, which participates in a condition later
149 }
150
151 // Increment and decrement operators...
152 ilist_iterator &operator--() {
153 NodePtr = IsReverse ? NodePtr->getNext() : NodePtr->getPrev();
154 return *this;
155 }
156 ilist_iterator &operator++() {
157 NodePtr = IsReverse ? NodePtr->getPrev() : NodePtr->getNext();
158 return *this;
159 }
160 ilist_iterator operator--(int) {
161 ilist_iterator tmp = *this;
162 --*this;
163 return tmp;
164 }
165 ilist_iterator operator++(int) {
166 ilist_iterator tmp = *this;
167 ++*this;
168 return tmp;
169 }
170
171 /// Get the underlying ilist_node.
172 node_pointer getNodePtr() const { return static_cast<node_pointer>(NodePtr); }
173
174 /// Check for end. Only valid if ilist_sentinel_tracking<true>.
175 bool isEnd() const { return NodePtr ? NodePtr->isSentinel() : false; }
176};
177
178template <typename From> struct simplify_type;
179
180/// Allow ilist_iterators to convert into pointers to a node automatically when
181/// used by the dyn_cast, cast, isa mechanisms...
182///
183/// FIXME: remove this, since there is no implicit conversion to NodeTy.
184template <class OptionsT, bool IsConst>
185struct simplify_type<ilist_iterator<OptionsT, false, IsConst>> {
186 using iterator = ilist_iterator<OptionsT, false, IsConst>;
187 using SimpleType = typename iterator::pointer;
188
189 static SimpleType getSimplifiedValue(const iterator &Node) { return &*Node; }
190};
191template <class OptionsT, bool IsConst>
192struct simplify_type<const ilist_iterator<OptionsT, false, IsConst>>
193 : simplify_type<ilist_iterator<OptionsT, false, IsConst>> {};
194
195} // end namespace llvm
196
197#endif // LLVM_ADT_ILIST_ITERATOR_H