Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ValueTracking.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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp

1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/Analysis/AssumptionCache.h"
29#include "llvm/Analysis/GuardUtils.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/Loads.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/OptimizationRemarkEmitter.h"
34#include "llvm/Analysis/TargetLibraryInfo.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/CallSite.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/ConstantRange.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/DiagnosticInfo.h"
45#include "llvm/IR/Dominators.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/GetElementPtrTypeIterator.h"
48#include "llvm/IR/GlobalAlias.h"
49#include "llvm/IR/GlobalValue.h"
50#include "llvm/IR/GlobalVariable.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/Intrinsics.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Metadata.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/Operator.h"
60#include "llvm/IR/PatternMatch.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/User.h"
63#include "llvm/IR/Value.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/KnownBits.h"
69#include "llvm/Support/MathExtras.h"
70#include <algorithm>
71#include <array>
72#include <cassert>
73#include <cstdint>
74#include <iterator>
75#include <utility>
76
77using namespace llvm;
78using namespace llvm::PatternMatch;
79
80const unsigned MaxDepth = 6;
81
82// Controls the number of uses of the value searched for possible
83// dominating comparisons.
84static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
85 cl::Hidden, cl::init(20));
86
87/// Returns the bitwidth of the given scalar or pointer type. For vector types,
88/// returns the element type's bitwidth.
89static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
90 if (unsigned BitWidth = Ty->getScalarSizeInBits())
91 return BitWidth;
92
93 return DL.getIndexTypeSizeInBits(Ty);
94}
95
96namespace {
97
98// Simplifying using an assume can only be done in a particular control-flow
99// context (the context instruction provides that context). If an assume and
100// the context instruction are not in the same block then the DT helps in
101// figuring out if we can use it.
102struct Query {
103 const DataLayout &DL;
104 AssumptionCache *AC;
105 const Instruction *CxtI;
106 const DominatorTree *DT;
107
108 // Unlike the other analyses, this may be a nullptr because not all clients
109 // provide it currently.
110 OptimizationRemarkEmitter *ORE;
111
112 /// Set of assumptions that should be excluded from further queries.
113 /// This is because of the potential for mutual recursion to cause
114 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
115 /// classic case of this is assume(x = y), which will attempt to determine
116 /// bits in x from bits in y, which will attempt to determine bits in y from
117 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
118 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
119 /// (all of which can call computeKnownBits), and so on.
120 std::array<const Value *, MaxDepth> Excluded;
121
122 /// If true, it is safe to use metadata during simplification.
123 InstrInfoQuery IIQ;
124
125 unsigned NumExcluded = 0;
126
127 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
128 const DominatorTree *DT, bool UseInstrInfo,
129 OptimizationRemarkEmitter *ORE = nullptr)
130 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
131
132 Query(const Query &Q, const Value *NewExcl)
133 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE), IIQ(Q.IIQ),
134 NumExcluded(Q.NumExcluded) {
135 Excluded = Q.Excluded;
136 Excluded[NumExcluded++] = NewExcl;
137 assert(NumExcluded <= Excluded.size())((NumExcluded <= Excluded.size()) ? static_cast<void>
(0) : __assert_fail ("NumExcluded <= Excluded.size()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 137, __PRETTY_FUNCTION__))
;
138 }
139
140 bool isExcluded(const Value *Value) const {
141 if (NumExcluded == 0)
142 return false;
143 auto End = Excluded.begin() + NumExcluded;
144 return std::find(Excluded.begin(), End, Value) != End;
145 }
146};
147
148} // end anonymous namespace
149
150// Given the provided Value and, potentially, a context instruction, return
151// the preferred context instruction (if any).
152static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
153 // If we've been provided with a context instruction, then use that (provided
154 // it has been inserted).
155 if (CxtI && CxtI->getParent())
156 return CxtI;
157
158 // If the value is really an already-inserted instruction, then use that.
159 CxtI = dyn_cast<Instruction>(V);
160 if (CxtI && CxtI->getParent())
161 return CxtI;
162
163 return nullptr;
164}
165
166static void computeKnownBits(const Value *V, KnownBits &Known,
167 unsigned Depth, const Query &Q);
168
169void llvm::computeKnownBits(const Value *V, KnownBits &Known,
170 const DataLayout &DL, unsigned Depth,
171 AssumptionCache *AC, const Instruction *CxtI,
172 const DominatorTree *DT,
173 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
174 ::computeKnownBits(V, Known, Depth,
175 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
176}
177
178static KnownBits computeKnownBits(const Value *V, unsigned Depth,
179 const Query &Q);
180
181KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
182 unsigned Depth, AssumptionCache *AC,
183 const Instruction *CxtI,
184 const DominatorTree *DT,
185 OptimizationRemarkEmitter *ORE,
186 bool UseInstrInfo) {
187 return ::computeKnownBits(
188 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
189}
190
191bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
192 const DataLayout &DL, AssumptionCache *AC,
193 const Instruction *CxtI, const DominatorTree *DT,
194 bool UseInstrInfo) {
195 assert(LHS->getType() == RHS->getType() &&((LHS->getType() == RHS->getType() && "LHS and RHS should have the same type"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS should have the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 196, __PRETTY_FUNCTION__))
196 "LHS and RHS should have the same type")((LHS->getType() == RHS->getType() && "LHS and RHS should have the same type"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS should have the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 196, __PRETTY_FUNCTION__))
;
197 assert(LHS->getType()->isIntOrIntVectorTy() &&((LHS->getType()->isIntOrIntVectorTy() && "LHS and RHS should be integers"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType()->isIntOrIntVectorTy() && \"LHS and RHS should be integers\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 198, __PRETTY_FUNCTION__))
198 "LHS and RHS should be integers")((LHS->getType()->isIntOrIntVectorTy() && "LHS and RHS should be integers"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType()->isIntOrIntVectorTy() && \"LHS and RHS should be integers\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 198, __PRETTY_FUNCTION__))
;
199 // Look for an inverted mask: (X & ~M) op (Y & M).
200 Value *M;
201 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
202 match(RHS, m_c_And(m_Specific(M), m_Value())))
203 return true;
204 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
205 match(LHS, m_c_And(m_Specific(M), m_Value())))
206 return true;
207 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
208 KnownBits LHSKnown(IT->getBitWidth());
209 KnownBits RHSKnown(IT->getBitWidth());
210 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
211 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
212 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
213}
214
215bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
216 for (const User *U : CxtI->users()) {
217 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
218 if (IC->isEquality())
219 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
220 if (C->isNullValue())
221 continue;
222 return false;
223 }
224 return true;
225}
226
227static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
228 const Query &Q);
229
230bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
231 bool OrZero, unsigned Depth,
232 AssumptionCache *AC, const Instruction *CxtI,
233 const DominatorTree *DT, bool UseInstrInfo) {
234 return ::isKnownToBeAPowerOfTwo(
235 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
236}
237
238static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
239
240bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
241 AssumptionCache *AC, const Instruction *CxtI,
242 const DominatorTree *DT, bool UseInstrInfo) {
243 return ::isKnownNonZero(V, Depth,
244 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
245}
246
247bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
248 unsigned Depth, AssumptionCache *AC,
249 const Instruction *CxtI, const DominatorTree *DT,
250 bool UseInstrInfo) {
251 KnownBits Known =
252 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
253 return Known.isNonNegative();
254}
255
256bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
257 AssumptionCache *AC, const Instruction *CxtI,
258 const DominatorTree *DT, bool UseInstrInfo) {
259 if (auto *CI = dyn_cast<ConstantInt>(V))
260 return CI->getValue().isStrictlyPositive();
261
262 // TODO: We'd doing two recursive queries here. We should factor this such
263 // that only a single query is needed.
264 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
265 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
266}
267
268bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
269 AssumptionCache *AC, const Instruction *CxtI,
270 const DominatorTree *DT, bool UseInstrInfo) {
271 KnownBits Known =
272 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
273 return Known.isNegative();
274}
275
276static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
277
278bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
279 const DataLayout &DL, AssumptionCache *AC,
280 const Instruction *CxtI, const DominatorTree *DT,
281 bool UseInstrInfo) {
282 return ::isKnownNonEqual(V1, V2,
283 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
284 UseInstrInfo, /*ORE=*/nullptr));
285}
286
287static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
288 const Query &Q);
289
290bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
291 const DataLayout &DL, unsigned Depth,
292 AssumptionCache *AC, const Instruction *CxtI,
293 const DominatorTree *DT, bool UseInstrInfo) {
294 return ::MaskedValueIsZero(
295 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
296}
297
298static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
299 const Query &Q);
300
301unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
302 unsigned Depth, AssumptionCache *AC,
303 const Instruction *CxtI,
304 const DominatorTree *DT, bool UseInstrInfo) {
305 return ::ComputeNumSignBits(
306 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
307}
308
309static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
310 bool NSW,
311 KnownBits &KnownOut, KnownBits &Known2,
312 unsigned Depth, const Query &Q) {
313 unsigned BitWidth = KnownOut.getBitWidth();
314
315 // If an initial sequence of bits in the result is not needed, the
316 // corresponding bits in the operands are not needed.
317 KnownBits LHSKnown(BitWidth);
318 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
319 computeKnownBits(Op1, Known2, Depth + 1, Q);
320
321 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
322}
323
324static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
325 KnownBits &Known, KnownBits &Known2,
326 unsigned Depth, const Query &Q) {
327 unsigned BitWidth = Known.getBitWidth();
328 computeKnownBits(Op1, Known, Depth + 1, Q);
329 computeKnownBits(Op0, Known2, Depth + 1, Q);
330
331 bool isKnownNegative = false;
332 bool isKnownNonNegative = false;
333 // If the multiplication is known not to overflow, compute the sign bit.
334 if (NSW) {
335 if (Op0 == Op1) {
336 // The product of a number with itself is non-negative.
337 isKnownNonNegative = true;
338 } else {
339 bool isKnownNonNegativeOp1 = Known.isNonNegative();
340 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
341 bool isKnownNegativeOp1 = Known.isNegative();
342 bool isKnownNegativeOp0 = Known2.isNegative();
343 // The product of two numbers with the same sign is non-negative.
344 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
345 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
346 // The product of a negative number and a non-negative number is either
347 // negative or zero.
348 if (!isKnownNonNegative)
349 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
350 isKnownNonZero(Op0, Depth, Q)) ||
351 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
352 isKnownNonZero(Op1, Depth, Q));
353 }
354 }
355
356 assert(!Known.hasConflict() && !Known2.hasConflict())((!Known.hasConflict() && !Known2.hasConflict()) ? static_cast
<void> (0) : __assert_fail ("!Known.hasConflict() && !Known2.hasConflict()"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 356, __PRETTY_FUNCTION__))
;
357 // Compute a conservative estimate for high known-0 bits.
358 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
359 Known2.countMinLeadingZeros(),
360 BitWidth) - BitWidth;
361 LeadZ = std::min(LeadZ, BitWidth);
362
363 // The result of the bottom bits of an integer multiply can be
364 // inferred by looking at the bottom bits of both operands and
365 // multiplying them together.
366 // We can infer at least the minimum number of known trailing bits
367 // of both operands. Depending on number of trailing zeros, we can
368 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
369 // a and b are divisible by m and n respectively.
370 // We then calculate how many of those bits are inferrable and set
371 // the output. For example, the i8 mul:
372 // a = XXXX1100 (12)
373 // b = XXXX1110 (14)
374 // We know the bottom 3 bits are zero since the first can be divided by
375 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
376 // Applying the multiplication to the trimmed arguments gets:
377 // XX11 (3)
378 // X111 (7)
379 // -------
380 // XX11
381 // XX11
382 // XX11
383 // XX11
384 // -------
385 // XXXXX01
386 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
387 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
388 // The proof for this can be described as:
389 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
390 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
391 // umin(countTrailingZeros(C2), C6) +
392 // umin(C5 - umin(countTrailingZeros(C1), C5),
393 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
394 // %aa = shl i8 %a, C5
395 // %bb = shl i8 %b, C6
396 // %aaa = or i8 %aa, C1
397 // %bbb = or i8 %bb, C2
398 // %mul = mul i8 %aaa, %bbb
399 // %mask = and i8 %mul, C7
400 // =>
401 // %mask = i8 ((C1*C2)&C7)
402 // Where C5, C6 describe the known bits of %a, %b
403 // C1, C2 describe the known bottom bits of %a, %b.
404 // C7 describes the mask of the known bits of the result.
405 APInt Bottom0 = Known.One;
406 APInt Bottom1 = Known2.One;
407
408 // How many times we'd be able to divide each argument by 2 (shr by 1).
409 // This gives us the number of trailing zeros on the multiplication result.
410 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
411 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
412 unsigned TrailZero0 = Known.countMinTrailingZeros();
413 unsigned TrailZero1 = Known2.countMinTrailingZeros();
414 unsigned TrailZ = TrailZero0 + TrailZero1;
415
416 // Figure out the fewest known-bits operand.
417 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
418 TrailBitsKnown1 - TrailZero1);
419 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
420
421 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
422 Bottom1.getLoBits(TrailBitsKnown1);
423
424 Known.resetAll();
425 Known.Zero.setHighBits(LeadZ);
426 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
427 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
428
429 // Only make use of no-wrap flags if we failed to compute the sign bit
430 // directly. This matters if the multiplication always overflows, in
431 // which case we prefer to follow the result of the direct computation,
432 // though as the program is invoking undefined behaviour we can choose
433 // whatever we like here.
434 if (isKnownNonNegative && !Known.isNegative())
435 Known.makeNonNegative();
436 else if (isKnownNegative && !Known.isNonNegative())
437 Known.makeNegative();
438}
439
440void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
441 KnownBits &Known) {
442 unsigned BitWidth = Known.getBitWidth();
443 unsigned NumRanges = Ranges.getNumOperands() / 2;
444 assert(NumRanges >= 1)((NumRanges >= 1) ? static_cast<void> (0) : __assert_fail
("NumRanges >= 1", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 444, __PRETTY_FUNCTION__))
;
445
446 Known.Zero.setAllBits();
447 Known.One.setAllBits();
448
449 for (unsigned i = 0; i < NumRanges; ++i) {
450 ConstantInt *Lower =
451 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
452 ConstantInt *Upper =
453 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
454 ConstantRange Range(Lower->getValue(), Upper->getValue());
455
456 // The first CommonPrefixBits of all values in Range are equal.
457 unsigned CommonPrefixBits =
458 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
459
460 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
461 Known.One &= Range.getUnsignedMax() & Mask;
462 Known.Zero &= ~Range.getUnsignedMax() & Mask;
463 }
464}
465
466static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
467 SmallVector<const Value *, 16> WorkSet(1, I);
468 SmallPtrSet<const Value *, 32> Visited;
469 SmallPtrSet<const Value *, 16> EphValues;
470
471 // The instruction defining an assumption's condition itself is always
472 // considered ephemeral to that assumption (even if it has other
473 // non-ephemeral users). See r246696's test case for an example.
474 if (is_contained(I->operands(), E))
475 return true;
476
477 while (!WorkSet.empty()) {
478 const Value *V = WorkSet.pop_back_val();
479 if (!Visited.insert(V).second)
480 continue;
481
482 // If all uses of this value are ephemeral, then so is this value.
483 if (llvm::all_of(V->users(), [&](const User *U) {
484 return EphValues.count(U);
485 })) {
486 if (V == E)
487 return true;
488
489 if (V == I || isSafeToSpeculativelyExecute(V)) {
490 EphValues.insert(V);
491 if (const User *U = dyn_cast<User>(V))
492 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
493 J != JE; ++J)
494 WorkSet.push_back(*J);
495 }
496 }
497 }
498
499 return false;
500}
501
502// Is this an intrinsic that cannot be speculated but also cannot trap?
503bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
504 if (const CallInst *CI = dyn_cast<CallInst>(I))
505 if (Function *F = CI->getCalledFunction())
506 switch (F->getIntrinsicID()) {
507 default: break;
508 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
509 case Intrinsic::assume:
510 case Intrinsic::sideeffect:
511 case Intrinsic::dbg_declare:
512 case Intrinsic::dbg_value:
513 case Intrinsic::dbg_label:
514 case Intrinsic::invariant_start:
515 case Intrinsic::invariant_end:
516 case Intrinsic::lifetime_start:
517 case Intrinsic::lifetime_end:
518 case Intrinsic::objectsize:
519 case Intrinsic::ptr_annotation:
520 case Intrinsic::var_annotation:
521 return true;
522 }
523
524 return false;
525}
526
527bool llvm::isValidAssumeForContext(const Instruction *Inv,
528 const Instruction *CxtI,
529 const DominatorTree *DT) {
530 // There are two restrictions on the use of an assume:
531 // 1. The assume must dominate the context (or the control flow must
532 // reach the assume whenever it reaches the context).
533 // 2. The context must not be in the assume's set of ephemeral values
534 // (otherwise we will use the assume to prove that the condition
535 // feeding the assume is trivially true, thus causing the removal of
536 // the assume).
537
538 if (DT) {
539 if (DT->dominates(Inv, CxtI))
540 return true;
541 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
542 // We don't have a DT, but this trivially dominates.
543 return true;
544 }
545
546 // With or without a DT, the only remaining case we will check is if the
547 // instructions are in the same BB. Give up if that is not the case.
548 if (Inv->getParent() != CxtI->getParent())
549 return false;
550
551 // If we have a dom tree, then we now know that the assume doesn't dominate
552 // the other instruction. If we don't have a dom tree then we can check if
553 // the assume is first in the BB.
554 if (!DT) {
555 // Search forward from the assume until we reach the context (or the end
556 // of the block); the common case is that the assume will come first.
557 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
558 IE = Inv->getParent()->end(); I != IE; ++I)
559 if (&*I == CxtI)
560 return true;
561 }
562
563 // The context comes first, but they're both in the same block. Make sure
564 // there is nothing in between that might interrupt the control flow.
565 for (BasicBlock::const_iterator I =
566 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
567 I != IE; ++I)
568 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
569 return false;
570
571 return !isEphemeralValueOf(Inv, CxtI);
572}
573
574static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
575 unsigned Depth, const Query &Q) {
576 // Use of assumptions is context-sensitive. If we don't have a context, we
577 // cannot use them!
578 if (!Q.AC || !Q.CxtI)
579 return;
580
581 unsigned BitWidth = Known.getBitWidth();
582
583 // Note that the patterns below need to be kept in sync with the code
584 // in AssumptionCache::updateAffectedValues.
585
586 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
587 if (!AssumeVH)
588 continue;
589 CallInst *I = cast<CallInst>(AssumeVH);
590 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&((I->getParent()->getParent() == Q.CxtI->getParent()
->getParent() && "Got assumption for the wrong function!"
) ? static_cast<void> (0) : __assert_fail ("I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && \"Got assumption for the wrong function!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 591, __PRETTY_FUNCTION__))
591 "Got assumption for the wrong function!")((I->getParent()->getParent() == Q.CxtI->getParent()
->getParent() && "Got assumption for the wrong function!"
) ? static_cast<void> (0) : __assert_fail ("I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && \"Got assumption for the wrong function!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 591, __PRETTY_FUNCTION__))
;
592 if (Q.isExcluded(I))
593 continue;
594
595 // Warning: This loop can end up being somewhat performance sensitive.
596 // We're running this loop for once for each value queried resulting in a
597 // runtime of ~O(#assumes * #values).
598
599 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&((I->getCalledFunction()->getIntrinsicID() == Intrinsic
::assume && "must be an assume intrinsic") ? static_cast
<void> (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 600, __PRETTY_FUNCTION__))
600 "must be an assume intrinsic")((I->getCalledFunction()->getIntrinsicID() == Intrinsic
::assume && "must be an assume intrinsic") ? static_cast
<void> (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 600, __PRETTY_FUNCTION__))
;
601
602 Value *Arg = I->getArgOperand(0);
603
604 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
605 assert(BitWidth == 1 && "assume operand is not i1?")((BitWidth == 1 && "assume operand is not i1?") ? static_cast
<void> (0) : __assert_fail ("BitWidth == 1 && \"assume operand is not i1?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 605, __PRETTY_FUNCTION__))
;
606 Known.setAllOnes();
607 return;
608 }
609 if (match(Arg, m_Not(m_Specific(V))) &&
610 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
611 assert(BitWidth == 1 && "assume operand is not i1?")((BitWidth == 1 && "assume operand is not i1?") ? static_cast
<void> (0) : __assert_fail ("BitWidth == 1 && \"assume operand is not i1?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 611, __PRETTY_FUNCTION__))
;
612 Known.setAllZero();
613 return;
614 }
615
616 // The remaining tests are all recursive, so bail out if we hit the limit.
617 if (Depth == MaxDepth)
618 continue;
619
620 Value *A, *B;
621 auto m_V = m_CombineOr(m_Specific(V),
622 m_CombineOr(m_PtrToInt(m_Specific(V)),
623 m_BitCast(m_Specific(V))));
624
625 CmpInst::Predicate Pred;
626 uint64_t C;
627 // assume(v = a)
628 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
629 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
630 KnownBits RHSKnown(BitWidth);
631 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
632 Known.Zero |= RHSKnown.Zero;
633 Known.One |= RHSKnown.One;
634 // assume(v & b = a)
635 } else if (match(Arg,
636 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
637 Pred == ICmpInst::ICMP_EQ &&
638 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
639 KnownBits RHSKnown(BitWidth);
640 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
641 KnownBits MaskKnown(BitWidth);
642 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
643
644 // For those bits in the mask that are known to be one, we can propagate
645 // known bits from the RHS to V.
646 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
647 Known.One |= RHSKnown.One & MaskKnown.One;
648 // assume(~(v & b) = a)
649 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
650 m_Value(A))) &&
651 Pred == ICmpInst::ICMP_EQ &&
652 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
653 KnownBits RHSKnown(BitWidth);
654 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
655 KnownBits MaskKnown(BitWidth);
656 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
657
658 // For those bits in the mask that are known to be one, we can propagate
659 // inverted known bits from the RHS to V.
660 Known.Zero |= RHSKnown.One & MaskKnown.One;
661 Known.One |= RHSKnown.Zero & MaskKnown.One;
662 // assume(v | b = a)
663 } else if (match(Arg,
664 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
665 Pred == ICmpInst::ICMP_EQ &&
666 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
667 KnownBits RHSKnown(BitWidth);
668 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
669 KnownBits BKnown(BitWidth);
670 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
671
672 // For those bits in B that are known to be zero, we can propagate known
673 // bits from the RHS to V.
674 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
675 Known.One |= RHSKnown.One & BKnown.Zero;
676 // assume(~(v | b) = a)
677 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
678 m_Value(A))) &&
679 Pred == ICmpInst::ICMP_EQ &&
680 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
681 KnownBits RHSKnown(BitWidth);
682 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
683 KnownBits BKnown(BitWidth);
684 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
685
686 // For those bits in B that are known to be zero, we can propagate
687 // inverted known bits from the RHS to V.
688 Known.Zero |= RHSKnown.One & BKnown.Zero;
689 Known.One |= RHSKnown.Zero & BKnown.Zero;
690 // assume(v ^ b = a)
691 } else if (match(Arg,
692 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
693 Pred == ICmpInst::ICMP_EQ &&
694 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
695 KnownBits RHSKnown(BitWidth);
696 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
697 KnownBits BKnown(BitWidth);
698 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
699
700 // For those bits in B that are known to be zero, we can propagate known
701 // bits from the RHS to V. For those bits in B that are known to be one,
702 // we can propagate inverted known bits from the RHS to V.
703 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
704 Known.One |= RHSKnown.One & BKnown.Zero;
705 Known.Zero |= RHSKnown.One & BKnown.One;
706 Known.One |= RHSKnown.Zero & BKnown.One;
707 // assume(~(v ^ b) = a)
708 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
709 m_Value(A))) &&
710 Pred == ICmpInst::ICMP_EQ &&
711 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
712 KnownBits RHSKnown(BitWidth);
713 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
714 KnownBits BKnown(BitWidth);
715 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
716
717 // For those bits in B that are known to be zero, we can propagate
718 // inverted known bits from the RHS to V. For those bits in B that are
719 // known to be one, we can propagate known bits from the RHS to V.
720 Known.Zero |= RHSKnown.One & BKnown.Zero;
721 Known.One |= RHSKnown.Zero & BKnown.Zero;
722 Known.Zero |= RHSKnown.Zero & BKnown.One;
723 Known.One |= RHSKnown.One & BKnown.One;
724 // assume(v << c = a)
725 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
726 m_Value(A))) &&
727 Pred == ICmpInst::ICMP_EQ &&
728 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
729 C < BitWidth) {
730 KnownBits RHSKnown(BitWidth);
731 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
732 // For those bits in RHS that are known, we can propagate them to known
733 // bits in V shifted to the right by C.
734 RHSKnown.Zero.lshrInPlace(C);
735 Known.Zero |= RHSKnown.Zero;
736 RHSKnown.One.lshrInPlace(C);
737 Known.One |= RHSKnown.One;
738 // assume(~(v << c) = a)
739 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
740 m_Value(A))) &&
741 Pred == ICmpInst::ICMP_EQ &&
742 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
743 C < BitWidth) {
744 KnownBits RHSKnown(BitWidth);
745 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
746 // For those bits in RHS that are known, we can propagate them inverted
747 // to known bits in V shifted to the right by C.
748 RHSKnown.One.lshrInPlace(C);
749 Known.Zero |= RHSKnown.One;
750 RHSKnown.Zero.lshrInPlace(C);
751 Known.One |= RHSKnown.Zero;
752 // assume(v >> c = a)
753 } else if (match(Arg,
754 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
755 m_Value(A))) &&
756 Pred == ICmpInst::ICMP_EQ &&
757 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
758 C < BitWidth) {
759 KnownBits RHSKnown(BitWidth);
760 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
761 // For those bits in RHS that are known, we can propagate them to known
762 // bits in V shifted to the right by C.
763 Known.Zero |= RHSKnown.Zero << C;
764 Known.One |= RHSKnown.One << C;
765 // assume(~(v >> c) = a)
766 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
767 m_Value(A))) &&
768 Pred == ICmpInst::ICMP_EQ &&
769 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
770 C < BitWidth) {
771 KnownBits RHSKnown(BitWidth);
772 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
773 // For those bits in RHS that are known, we can propagate them inverted
774 // to known bits in V shifted to the right by C.
775 Known.Zero |= RHSKnown.One << C;
776 Known.One |= RHSKnown.Zero << C;
777 // assume(v >=_s c) where c is non-negative
778 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
779 Pred == ICmpInst::ICMP_SGE &&
780 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
781 KnownBits RHSKnown(BitWidth);
782 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
783
784 if (RHSKnown.isNonNegative()) {
785 // We know that the sign bit is zero.
786 Known.makeNonNegative();
787 }
788 // assume(v >_s c) where c is at least -1.
789 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
790 Pred == ICmpInst::ICMP_SGT &&
791 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
792 KnownBits RHSKnown(BitWidth);
793 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
794
795 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
796 // We know that the sign bit is zero.
797 Known.makeNonNegative();
798 }
799 // assume(v <=_s c) where c is negative
800 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
801 Pred == ICmpInst::ICMP_SLE &&
802 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
803 KnownBits RHSKnown(BitWidth);
804 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
805
806 if (RHSKnown.isNegative()) {
807 // We know that the sign bit is one.
808 Known.makeNegative();
809 }
810 // assume(v <_s c) where c is non-positive
811 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
812 Pred == ICmpInst::ICMP_SLT &&
813 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
814 KnownBits RHSKnown(BitWidth);
815 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
816
817 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
818 // We know that the sign bit is one.
819 Known.makeNegative();
820 }
821 // assume(v <=_u c)
822 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
823 Pred == ICmpInst::ICMP_ULE &&
824 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
825 KnownBits RHSKnown(BitWidth);
826 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
827
828 // Whatever high bits in c are zero are known to be zero.
829 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
830 // assume(v <_u c)
831 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
832 Pred == ICmpInst::ICMP_ULT &&
833 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
834 KnownBits RHSKnown(BitWidth);
835 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
836
837 // If the RHS is known zero, then this assumption must be wrong (nothing
838 // is unsigned less than zero). Signal a conflict and get out of here.
839 if (RHSKnown.isZero()) {
840 Known.Zero.setAllBits();
841 Known.One.setAllBits();
842 break;
843 }
844
845 // Whatever high bits in c are zero are known to be zero (if c is a power
846 // of 2, then one more).
847 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
848 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
849 else
850 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
851 }
852 }
853
854 // If assumptions conflict with each other or previous known bits, then we
855 // have a logical fallacy. It's possible that the assumption is not reachable,
856 // so this isn't a real bug. On the other hand, the program may have undefined
857 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
858 // clear out the known bits, try to warn the user, and hope for the best.
859 if (Known.Zero.intersects(Known.One)) {
860 Known.resetAll();
861
862 if (Q.ORE)
863 Q.ORE->emit([&]() {
864 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
865 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
866 CxtI)
867 << "Detected conflicting code assumptions. Program may "
868 "have undefined behavior, or compiler may have "
869 "internal error.";
870 });
871 }
872}
873
874/// Compute known bits from a shift operator, including those with a
875/// non-constant shift amount. Known is the output of this function. Known2 is a
876/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
877/// operator-specific functions that, given the known-zero or known-one bits
878/// respectively, and a shift amount, compute the implied known-zero or
879/// known-one bits of the shift operator's result respectively for that shift
880/// amount. The results from calling KZF and KOF are conservatively combined for
881/// all permitted shift amounts.
882static void computeKnownBitsFromShiftOperator(
883 const Operator *I, KnownBits &Known, KnownBits &Known2,
884 unsigned Depth, const Query &Q,
885 function_ref<APInt(const APInt &, unsigned)> KZF,
886 function_ref<APInt(const APInt &, unsigned)> KOF) {
887 unsigned BitWidth = Known.getBitWidth();
888
889 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
890 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
891
892 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
893 Known.Zero = KZF(Known.Zero, ShiftAmt);
894 Known.One = KOF(Known.One, ShiftAmt);
895 // If the known bits conflict, this must be an overflowing left shift, so
896 // the shift result is poison. We can return anything we want. Choose 0 for
897 // the best folding opportunity.
898 if (Known.hasConflict())
899 Known.setAllZero();
900
901 return;
902 }
903
904 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
905
906 // If the shift amount could be greater than or equal to the bit-width of the
907 // LHS, the value could be poison, but bail out because the check below is
908 // expensive. TODO: Should we just carry on?
909 if ((~Known.Zero).uge(BitWidth)) {
910 Known.resetAll();
911 return;
912 }
913
914 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
915 // BitWidth > 64 and any upper bits are known, we'll end up returning the
916 // limit value (which implies all bits are known).
917 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
918 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
919
920 // It would be more-clearly correct to use the two temporaries for this
921 // calculation. Reusing the APInts here to prevent unnecessary allocations.
922 Known.resetAll();
923
924 // If we know the shifter operand is nonzero, we can sometimes infer more
925 // known bits. However this is expensive to compute, so be lazy about it and
926 // only compute it when absolutely necessary.
927 Optional<bool> ShifterOperandIsNonZero;
928
929 // Early exit if we can't constrain any well-defined shift amount.
930 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
931 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
932 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
933 if (!*ShifterOperandIsNonZero)
934 return;
935 }
936
937 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
938
939 Known.Zero.setAllBits();
940 Known.One.setAllBits();
941 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
942 // Combine the shifted known input bits only for those shift amounts
943 // compatible with its known constraints.
944 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
945 continue;
946 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
947 continue;
948 // If we know the shifter is nonzero, we may be able to infer more known
949 // bits. This check is sunk down as far as possible to avoid the expensive
950 // call to isKnownNonZero if the cheaper checks above fail.
951 if (ShiftAmt == 0) {
952 if (!ShifterOperandIsNonZero.hasValue())
953 ShifterOperandIsNonZero =
954 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
955 if (*ShifterOperandIsNonZero)
956 continue;
957 }
958
959 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
960 Known.One &= KOF(Known2.One, ShiftAmt);
961 }
962
963 // If the known bits conflict, the result is poison. Return a 0 and hope the
964 // caller can further optimize that.
965 if (Known.hasConflict())
966 Known.setAllZero();
967}
968
969static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
970 unsigned Depth, const Query &Q) {
971 unsigned BitWidth = Known.getBitWidth();
972
973 KnownBits Known2(Known);
974 switch (I->getOpcode()) {
975 default: break;
976 case Instruction::Load:
977 if (MDNode *MD =
978 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
979 computeKnownBitsFromRangeMetadata(*MD, Known);
980 break;
981 case Instruction::And: {
982 // If either the LHS or the RHS are Zero, the result is zero.
983 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
984 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
985
986 // Output known-1 bits are only known if set in both the LHS & RHS.
987 Known.One &= Known2.One;
988 // Output known-0 are known to be clear if zero in either the LHS | RHS.
989 Known.Zero |= Known2.Zero;
990
991 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
992 // here we handle the more general case of adding any odd number by
993 // matching the form add(x, add(x, y)) where y is odd.
994 // TODO: This could be generalized to clearing any bit set in y where the
995 // following bit is known to be unset in y.
996 Value *X = nullptr, *Y = nullptr;
997 if (!Known.Zero[0] && !Known.One[0] &&
998 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
999 Known2.resetAll();
1000 computeKnownBits(Y, Known2, Depth + 1, Q);
1001 if (Known2.countMinTrailingOnes() > 0)
1002 Known.Zero.setBit(0);
1003 }
1004 break;
1005 }
1006 case Instruction::Or:
1007 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1008 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1009
1010 // Output known-0 bits are only known if clear in both the LHS & RHS.
1011 Known.Zero &= Known2.Zero;
1012 // Output known-1 are known to be set if set in either the LHS | RHS.
1013 Known.One |= Known2.One;
1014 break;
1015 case Instruction::Xor: {
1016 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1017 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1018
1019 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1020 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
1021 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1022 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1023 Known.Zero = std::move(KnownZeroOut);
1024 break;
1025 }
1026 case Instruction::Mul: {
1027 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1028 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1029 Known2, Depth, Q);
1030 break;
1031 }
1032 case Instruction::UDiv: {
1033 // For the purposes of computing leading zeros we can conservatively
1034 // treat a udiv as a logical right shift by the power of 2 known to
1035 // be less than the denominator.
1036 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1037 unsigned LeadZ = Known2.countMinLeadingZeros();
1038
1039 Known2.resetAll();
1040 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1041 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1042 if (RHSMaxLeadingZeros != BitWidth)
1043 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
1044
1045 Known.Zero.setHighBits(LeadZ);
1046 break;
1047 }
1048 case Instruction::Select: {
1049 const Value *LHS, *RHS;
1050 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1051 if (SelectPatternResult::isMinOrMax(SPF)) {
1052 computeKnownBits(RHS, Known, Depth + 1, Q);
1053 computeKnownBits(LHS, Known2, Depth + 1, Q);
1054 } else {
1055 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1056 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1057 }
1058
1059 unsigned MaxHighOnes = 0;
1060 unsigned MaxHighZeros = 0;
1061 if (SPF == SPF_SMAX) {
1062 // If both sides are negative, the result is negative.
1063 if (Known.isNegative() && Known2.isNegative())
1064 // We can derive a lower bound on the result by taking the max of the
1065 // leading one bits.
1066 MaxHighOnes =
1067 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
1068 // If either side is non-negative, the result is non-negative.
1069 else if (Known.isNonNegative() || Known2.isNonNegative())
1070 MaxHighZeros = 1;
1071 } else if (SPF == SPF_SMIN) {
1072 // If both sides are non-negative, the result is non-negative.
1073 if (Known.isNonNegative() && Known2.isNonNegative())
1074 // We can derive an upper bound on the result by taking the max of the
1075 // leading zero bits.
1076 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1077 Known2.countMinLeadingZeros());
1078 // If either side is negative, the result is negative.
1079 else if (Known.isNegative() || Known2.isNegative())
1080 MaxHighOnes = 1;
1081 } else if (SPF == SPF_UMAX) {
1082 // We can derive a lower bound on the result by taking the max of the
1083 // leading one bits.
1084 MaxHighOnes =
1085 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
1086 } else if (SPF == SPF_UMIN) {
1087 // We can derive an upper bound on the result by taking the max of the
1088 // leading zero bits.
1089 MaxHighZeros =
1090 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
1091 } else if (SPF == SPF_ABS) {
1092 // RHS from matchSelectPattern returns the negation part of abs pattern.
1093 // If the negate has an NSW flag we can assume the sign bit of the result
1094 // will be 0 because that makes abs(INT_MIN) undefined.
1095 if (Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
1096 MaxHighZeros = 1;
1097 }
1098
1099 // Only known if known in both the LHS and RHS.
1100 Known.One &= Known2.One;
1101 Known.Zero &= Known2.Zero;
1102 if (MaxHighOnes > 0)
1103 Known.One.setHighBits(MaxHighOnes);
1104 if (MaxHighZeros > 0)
1105 Known.Zero.setHighBits(MaxHighZeros);
1106 break;
1107 }
1108 case Instruction::FPTrunc:
1109 case Instruction::FPExt:
1110 case Instruction::FPToUI:
1111 case Instruction::FPToSI:
1112 case Instruction::SIToFP:
1113 case Instruction::UIToFP:
1114 break; // Can't work with floating point.
1115 case Instruction::PtrToInt:
1116 case Instruction::IntToPtr:
1117 // Fall through and handle them the same as zext/trunc.
1118 LLVM_FALLTHROUGH[[clang::fallthrough]];
1119 case Instruction::ZExt:
1120 case Instruction::Trunc: {
1121 Type *SrcTy = I->getOperand(0)->getType();
1122
1123 unsigned SrcBitWidth;
1124 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1125 // which fall through here.
1126 Type *ScalarTy = SrcTy->getScalarType();
1127 SrcBitWidth = ScalarTy->isPointerTy() ?
1128 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1129 Q.DL.getTypeSizeInBits(ScalarTy);
1130
1131 assert(SrcBitWidth && "SrcBitWidth can't be zero")((SrcBitWidth && "SrcBitWidth can't be zero") ? static_cast
<void> (0) : __assert_fail ("SrcBitWidth && \"SrcBitWidth can't be zero\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1131, __PRETTY_FUNCTION__))
;
1132 Known = Known.zextOrTrunc(SrcBitWidth);
1133 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1134 Known = Known.zextOrTrunc(BitWidth);
1135 // Any top bits are known to be zero.
1136 if (BitWidth > SrcBitWidth)
1137 Known.Zero.setBitsFrom(SrcBitWidth);
1138 break;
1139 }
1140 case Instruction::BitCast: {
1141 Type *SrcTy = I->getOperand(0)->getType();
1142 if (SrcTy->isIntOrPtrTy() &&
1143 // TODO: For now, not handling conversions like:
1144 // (bitcast i64 %x to <2 x i32>)
1145 !I->getType()->isVectorTy()) {
1146 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1147 break;
1148 }
1149 break;
1150 }
1151 case Instruction::SExt: {
1152 // Compute the bits in the result that are not present in the input.
1153 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1154
1155 Known = Known.trunc(SrcBitWidth);
1156 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1157 // If the sign bit of the input is known set or clear, then we know the
1158 // top bits of the result.
1159 Known = Known.sext(BitWidth);
1160 break;
1161 }
1162 case Instruction::Shl: {
1163 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1164 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1165 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1166 APInt KZResult = KnownZero << ShiftAmt;
1167 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
1168 // If this shift has "nsw" keyword, then the result is either a poison
1169 // value or has the same sign bit as the first operand.
1170 if (NSW && KnownZero.isSignBitSet())
1171 KZResult.setSignBit();
1172 return KZResult;
1173 };
1174
1175 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1176 APInt KOResult = KnownOne << ShiftAmt;
1177 if (NSW && KnownOne.isSignBitSet())
1178 KOResult.setSignBit();
1179 return KOResult;
1180 };
1181
1182 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1183 break;
1184 }
1185 case Instruction::LShr: {
1186 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1187 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1188 APInt KZResult = KnownZero.lshr(ShiftAmt);
1189 // High bits known zero.
1190 KZResult.setHighBits(ShiftAmt);
1191 return KZResult;
1192 };
1193
1194 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1195 return KnownOne.lshr(ShiftAmt);
1196 };
1197
1198 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1199 break;
1200 }
1201 case Instruction::AShr: {
1202 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1203 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1204 return KnownZero.ashr(ShiftAmt);
1205 };
1206
1207 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1208 return KnownOne.ashr(ShiftAmt);
1209 };
1210
1211 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1212 break;
1213 }
1214 case Instruction::Sub: {
1215 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1216 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1217 Known, Known2, Depth, Q);
1218 break;
1219 }
1220 case Instruction::Add: {
1221 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1222 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1223 Known, Known2, Depth, Q);
1224 break;
1225 }
1226 case Instruction::SRem:
1227 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1228 APInt RA = Rem->getValue().abs();
1229 if (RA.isPowerOf2()) {
1230 APInt LowBits = RA - 1;
1231 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1232
1233 // The low bits of the first operand are unchanged by the srem.
1234 Known.Zero = Known2.Zero & LowBits;
1235 Known.One = Known2.One & LowBits;
1236
1237 // If the first operand is non-negative or has all low bits zero, then
1238 // the upper bits are all zero.
1239 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
1240 Known.Zero |= ~LowBits;
1241
1242 // If the first operand is negative and not all low bits are zero, then
1243 // the upper bits are all one.
1244 if (Known2.isNegative() && LowBits.intersects(Known2.One))
1245 Known.One |= ~LowBits;
1246
1247 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?")(((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?"
) ? static_cast<void> (0) : __assert_fail ("(Known.Zero & Known.One) == 0 && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1247, __PRETTY_FUNCTION__))
;
1248 break;
1249 }
1250 }
1251
1252 // The sign bit is the LHS's sign bit, except when the result of the
1253 // remainder is zero.
1254 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1255 // If it's known zero, our sign bit is also zero.
1256 if (Known2.isNonNegative())
1257 Known.makeNonNegative();
1258
1259 break;
1260 case Instruction::URem: {
1261 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1262 const APInt &RA = Rem->getValue();
1263 if (RA.isPowerOf2()) {
1264 APInt LowBits = (RA - 1);
1265 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1266 Known.Zero |= ~LowBits;
1267 Known.One &= LowBits;
1268 break;
1269 }
1270 }
1271
1272 // Since the result is less than or equal to either operand, any leading
1273 // zero bits in either operand must also exist in the result.
1274 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1275 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1276
1277 unsigned Leaders =
1278 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
1279 Known.resetAll();
1280 Known.Zero.setHighBits(Leaders);
1281 break;
1282 }
1283
1284 case Instruction::Alloca: {
1285 const AllocaInst *AI = cast<AllocaInst>(I);
1286 unsigned Align = AI->getAlignment();
1287 if (Align == 0)
1288 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
1289
1290 if (Align > 0)
1291 Known.Zero.setLowBits(countTrailingZeros(Align));
1292 break;
1293 }
1294 case Instruction::GetElementPtr: {
1295 // Analyze all of the subscripts of this getelementptr instruction
1296 // to determine if we can prove known low zero bits.
1297 KnownBits LocalKnown(BitWidth);
1298 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
1299 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
1300
1301 gep_type_iterator GTI = gep_type_begin(I);
1302 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1303 Value *Index = I->getOperand(i);
1304 if (StructType *STy = GTI.getStructTypeOrNull()) {
1305 // Handle struct member offset arithmetic.
1306
1307 // Handle case when index is vector zeroinitializer
1308 Constant *CIndex = cast<Constant>(Index);
1309 if (CIndex->isZeroValue())
1310 continue;
1311
1312 if (CIndex->getType()->isVectorTy())
1313 Index = CIndex->getSplatValue();
1314
1315 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1316 const StructLayout *SL = Q.DL.getStructLayout(STy);
1317 uint64_t Offset = SL->getElementOffset(Idx);
1318 TrailZ = std::min<unsigned>(TrailZ,
1319 countTrailingZeros(Offset));
1320 } else {
1321 // Handle array index arithmetic.
1322 Type *IndexedTy = GTI.getIndexedType();
1323 if (!IndexedTy->isSized()) {
1324 TrailZ = 0;
1325 break;
1326 }
1327 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1328 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1329 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1330 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
1331 TrailZ = std::min(TrailZ,
1332 unsigned(countTrailingZeros(TypeSize) +
1333 LocalKnown.countMinTrailingZeros()));
1334 }
1335 }
1336
1337 Known.Zero.setLowBits(TrailZ);
1338 break;
1339 }
1340 case Instruction::PHI: {
1341 const PHINode *P = cast<PHINode>(I);
1342 // Handle the case of a simple two-predecessor recurrence PHI.
1343 // There's a lot more that could theoretically be done here, but
1344 // this is sufficient to catch some interesting cases.
1345 if (P->getNumIncomingValues() == 2) {
1346 for (unsigned i = 0; i != 2; ++i) {
1347 Value *L = P->getIncomingValue(i);
1348 Value *R = P->getIncomingValue(!i);
1349 Operator *LU = dyn_cast<Operator>(L);
1350 if (!LU)
1351 continue;
1352 unsigned Opcode = LU->getOpcode();
1353 // Check for operations that have the property that if
1354 // both their operands have low zero bits, the result
1355 // will have low zero bits.
1356 if (Opcode == Instruction::Add ||
1357 Opcode == Instruction::Sub ||
1358 Opcode == Instruction::And ||
1359 Opcode == Instruction::Or ||
1360 Opcode == Instruction::Mul) {
1361 Value *LL = LU->getOperand(0);
1362 Value *LR = LU->getOperand(1);
1363 // Find a recurrence.
1364 if (LL == I)
1365 L = LR;
1366 else if (LR == I)
1367 L = LL;
1368 else
1369 break;
1370 // Ok, we have a PHI of the form L op= R. Check for low
1371 // zero bits.
1372 computeKnownBits(R, Known2, Depth + 1, Q);
1373
1374 // We need to take the minimum number of known bits
1375 KnownBits Known3(Known);
1376 computeKnownBits(L, Known3, Depth + 1, Q);
1377
1378 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1379 Known3.countMinTrailingZeros()));
1380
1381 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1382 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
1383 // If initial value of recurrence is nonnegative, and we are adding
1384 // a nonnegative number with nsw, the result can only be nonnegative
1385 // or poison value regardless of the number of times we execute the
1386 // add in phi recurrence. If initial value is negative and we are
1387 // adding a negative number with nsw, the result can only be
1388 // negative or poison value. Similar arguments apply to sub and mul.
1389 //
1390 // (add non-negative, non-negative) --> non-negative
1391 // (add negative, negative) --> negative
1392 if (Opcode == Instruction::Add) {
1393 if (Known2.isNonNegative() && Known3.isNonNegative())
1394 Known.makeNonNegative();
1395 else if (Known2.isNegative() && Known3.isNegative())
1396 Known.makeNegative();
1397 }
1398
1399 // (sub nsw non-negative, negative) --> non-negative
1400 // (sub nsw negative, non-negative) --> negative
1401 else if (Opcode == Instruction::Sub && LL == I) {
1402 if (Known2.isNonNegative() && Known3.isNegative())
1403 Known.makeNonNegative();
1404 else if (Known2.isNegative() && Known3.isNonNegative())
1405 Known.makeNegative();
1406 }
1407
1408 // (mul nsw non-negative, non-negative) --> non-negative
1409 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1410 Known3.isNonNegative())
1411 Known.makeNonNegative();
1412 }
1413
1414 break;
1415 }
1416 }
1417 }
1418
1419 // Unreachable blocks may have zero-operand PHI nodes.
1420 if (P->getNumIncomingValues() == 0)
1421 break;
1422
1423 // Otherwise take the unions of the known bit sets of the operands,
1424 // taking conservative care to avoid excessive recursion.
1425 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
1426 // Skip if every incoming value references to ourself.
1427 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1428 break;
1429
1430 Known.Zero.setAllBits();
1431 Known.One.setAllBits();
1432 for (Value *IncValue : P->incoming_values()) {
1433 // Skip direct self references.
1434 if (IncValue == P) continue;
1435
1436 Known2 = KnownBits(BitWidth);
1437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
1439 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1440 Known.Zero &= Known2.Zero;
1441 Known.One &= Known2.One;
1442 // If all bits have been ruled out, there's no need to check
1443 // more operands.
1444 if (!Known.Zero && !Known.One)
1445 break;
1446 }
1447 }
1448 break;
1449 }
1450 case Instruction::Call:
1451 case Instruction::Invoke:
1452 // If range metadata is attached to this call, set known bits from that,
1453 // and then intersect with known bits based on other properties of the
1454 // function.
1455 if (MDNode *MD =
1456 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
1457 computeKnownBitsFromRangeMetadata(*MD, Known);
1458 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
1459 computeKnownBits(RV, Known2, Depth + 1, Q);
1460 Known.Zero |= Known2.Zero;
1461 Known.One |= Known2.One;
1462 }
1463 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1464 switch (II->getIntrinsicID()) {
1465 default: break;
1466 case Intrinsic::bitreverse:
1467 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1468 Known.Zero |= Known2.Zero.reverseBits();
1469 Known.One |= Known2.One.reverseBits();
1470 break;
1471 case Intrinsic::bswap:
1472 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1473 Known.Zero |= Known2.Zero.byteSwap();
1474 Known.One |= Known2.One.byteSwap();
1475 break;
1476 case Intrinsic::ctlz: {
1477 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1478 // If we have a known 1, its position is our upper bound.
1479 unsigned PossibleLZ = Known2.One.countLeadingZeros();
1480 // If this call is undefined for 0, the result will be less than 2^n.
1481 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1482 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1483 unsigned LowBits = Log2_32(PossibleLZ)+1;
1484 Known.Zero.setBitsFrom(LowBits);
1485 break;
1486 }
1487 case Intrinsic::cttz: {
1488 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1489 // If we have a known 1, its position is our upper bound.
1490 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1491 // If this call is undefined for 0, the result will be less than 2^n.
1492 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1493 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1494 unsigned LowBits = Log2_32(PossibleTZ)+1;
1495 Known.Zero.setBitsFrom(LowBits);
1496 break;
1497 }
1498 case Intrinsic::ctpop: {
1499 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1500 // We can bound the space the count needs. Also, bits known to be zero
1501 // can't contribute to the population.
1502 unsigned BitsPossiblySet = Known2.countMaxPopulation();
1503 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
1504 Known.Zero.setBitsFrom(LowBits);
1505 // TODO: we could bound KnownOne using the lower bound on the number
1506 // of bits which might be set provided by popcnt KnownOne2.
1507 break;
1508 }
1509 case Intrinsic::x86_sse42_crc32_64_64:
1510 Known.Zero.setBitsFrom(32);
1511 break;
1512 }
1513 }
1514 break;
1515 case Instruction::ExtractElement:
1516 // Look through extract element. At the moment we keep this simple and skip
1517 // tracking the specific element. But at least we might find information
1518 // valid for all elements of the vector (for example if vector is sign
1519 // extended, shifted, etc).
1520 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1521 break;
1522 case Instruction::ExtractValue:
1523 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1524 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1525 if (EVI->getNumIndices() != 1) break;
1526 if (EVI->getIndices()[0] == 0) {
1527 switch (II->getIntrinsicID()) {
1528 default: break;
1529 case Intrinsic::uadd_with_overflow:
1530 case Intrinsic::sadd_with_overflow:
1531 computeKnownBitsAddSub(true, II->getArgOperand(0),
1532 II->getArgOperand(1), false, Known, Known2,
1533 Depth, Q);
1534 break;
1535 case Intrinsic::usub_with_overflow:
1536 case Intrinsic::ssub_with_overflow:
1537 computeKnownBitsAddSub(false, II->getArgOperand(0),
1538 II->getArgOperand(1), false, Known, Known2,
1539 Depth, Q);
1540 break;
1541 case Intrinsic::umul_with_overflow:
1542 case Intrinsic::smul_with_overflow:
1543 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1544 Known, Known2, Depth, Q);
1545 break;
1546 }
1547 }
1548 }
1549 }
1550}
1551
1552/// Determine which bits of V are known to be either zero or one and return
1553/// them.
1554KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1555 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1556 computeKnownBits(V, Known, Depth, Q);
1557 return Known;
1558}
1559
1560/// Determine which bits of V are known to be either zero or one and return
1561/// them in the Known bit set.
1562///
1563/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1564/// we cannot optimize based on the assumption that it is zero without changing
1565/// it to be an explicit zero. If we don't change it to zero, other code could
1566/// optimized based on the contradictory assumption that it is non-zero.
1567/// Because instcombine aggressively folds operations with undef args anyway,
1568/// this won't lose us code quality.
1569///
1570/// This function is defined on values with integer type, values with pointer
1571/// type, and vectors of integers. In the case
1572/// where V is a vector, known zero, and known one values are the
1573/// same width as the vector element, and the bit is set only if it is true
1574/// for all of the elements in the vector.
1575void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1576 const Query &Q) {
1577 assert(V && "No Value?")((V && "No Value?") ? static_cast<void> (0) : __assert_fail
("V && \"No Value?\"", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1577, __PRETTY_FUNCTION__))
;
1578 assert(Depth <= MaxDepth && "Limit Search Depth")((Depth <= MaxDepth && "Limit Search Depth") ? static_cast
<void> (0) : __assert_fail ("Depth <= MaxDepth && \"Limit Search Depth\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1578, __PRETTY_FUNCTION__))
;
1579 unsigned BitWidth = Known.getBitWidth();
1580
1581 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||(((V->getType()->isIntOrIntVectorTy(BitWidth) || V->
getType()->isPtrOrPtrVectorTy()) && "Not integer or pointer type!"
) ? static_cast<void> (0) : __assert_fail ("(V->getType()->isIntOrIntVectorTy(BitWidth) || V->getType()->isPtrOrPtrVectorTy()) && \"Not integer or pointer type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1583, __PRETTY_FUNCTION__))
1582 V->getType()->isPtrOrPtrVectorTy()) &&(((V->getType()->isIntOrIntVectorTy(BitWidth) || V->
getType()->isPtrOrPtrVectorTy()) && "Not integer or pointer type!"
) ? static_cast<void> (0) : __assert_fail ("(V->getType()->isIntOrIntVectorTy(BitWidth) || V->getType()->isPtrOrPtrVectorTy()) && \"Not integer or pointer type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1583, __PRETTY_FUNCTION__))
1583 "Not integer or pointer type!")(((V->getType()->isIntOrIntVectorTy(BitWidth) || V->
getType()->isPtrOrPtrVectorTy()) && "Not integer or pointer type!"
) ? static_cast<void> (0) : __assert_fail ("(V->getType()->isIntOrIntVectorTy(BitWidth) || V->getType()->isPtrOrPtrVectorTy()) && \"Not integer or pointer type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1583, __PRETTY_FUNCTION__))
;
1584
1585 Type *ScalarTy = V->getType()->getScalarType();
1586 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1587 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1588 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth")((ExpectedWidth == BitWidth && "V and Known should have same BitWidth"
) ? static_cast<void> (0) : __assert_fail ("ExpectedWidth == BitWidth && \"V and Known should have same BitWidth\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1588, __PRETTY_FUNCTION__))
;
1589 (void)BitWidth;
1590 (void)ExpectedWidth;
1591
1592 const APInt *C;
1593 if (match(V, m_APInt(C))) {
1594 // We know all of the bits for a scalar constant or a splat vector constant!
1595 Known.One = *C;
1596 Known.Zero = ~Known.One;
1597 return;
1598 }
1599 // Null and aggregate-zero are all-zeros.
1600 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1601 Known.setAllZero();
1602 return;
1603 }
1604 // Handle a constant vector by taking the intersection of the known bits of
1605 // each element.
1606 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1607 // We know that CDS must be a vector of integers. Take the intersection of
1608 // each element.
1609 Known.Zero.setAllBits(); Known.One.setAllBits();
1610 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1611 APInt Elt = CDS->getElementAsAPInt(i);
1612 Known.Zero &= ~Elt;
1613 Known.One &= Elt;
1614 }
1615 return;
1616 }
1617
1618 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1619 // We know that CV must be a vector of integers. Take the intersection of
1620 // each element.
1621 Known.Zero.setAllBits(); Known.One.setAllBits();
1622 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1623 Constant *Element = CV->getAggregateElement(i);
1624 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1625 if (!ElementCI) {
1626 Known.resetAll();
1627 return;
1628 }
1629 const APInt &Elt = ElementCI->getValue();
1630 Known.Zero &= ~Elt;
1631 Known.One &= Elt;
1632 }
1633 return;
1634 }
1635
1636 // Start out not knowing anything.
1637 Known.resetAll();
1638
1639 // We can't imply anything about undefs.
1640 if (isa<UndefValue>(V))
1641 return;
1642
1643 // There's no point in looking through other users of ConstantData for
1644 // assumptions. Confirm that we've handled them all.
1645 assert(!isa<ConstantData>(V) && "Unhandled constant data!")((!isa<ConstantData>(V) && "Unhandled constant data!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantData>(V) && \"Unhandled constant data!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1645, __PRETTY_FUNCTION__))
;
1646
1647 // Limit search depth.
1648 // All recursive calls that increase depth must come after this.
1649 if (Depth == MaxDepth)
1650 return;
1651
1652 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1653 // the bits of its aliasee.
1654 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1655 if (!GA->isInterposable())
1656 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1657 return;
1658 }
1659
1660 if (const Operator *I = dyn_cast<Operator>(V))
1661 computeKnownBitsFromOperator(I, Known, Depth, Q);
1662
1663 // Aligned pointers have trailing zeros - refine Known.Zero set
1664 if (V->getType()->isPointerTy()) {
1665 unsigned Align = V->getPointerAlignment(Q.DL);
1666 if (Align)
1667 Known.Zero.setLowBits(countTrailingZeros(Align));
1668 }
1669
1670 // computeKnownBitsFromAssume strictly refines Known.
1671 // Therefore, we run them after computeKnownBitsFromOperator.
1672
1673 // Check whether a nearby assume intrinsic can determine some known bits.
1674 computeKnownBitsFromAssume(V, Known, Depth, Q);
1675
1676 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?")(((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?"
) ? static_cast<void> (0) : __assert_fail ("(Known.Zero & Known.One) == 0 && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1676, __PRETTY_FUNCTION__))
;
1677}
1678
1679/// Return true if the given value is known to have exactly one
1680/// bit set when defined. For vectors return true if every element is known to
1681/// be a power of two when defined. Supports values with integer or pointer
1682/// types and vectors of integers.
1683bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1684 const Query &Q) {
1685 assert(Depth <= MaxDepth && "Limit Search Depth")((Depth <= MaxDepth && "Limit Search Depth") ? static_cast
<void> (0) : __assert_fail ("Depth <= MaxDepth && \"Limit Search Depth\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1685, __PRETTY_FUNCTION__))
;
1686
1687 // Attempt to match against constants.
1688 if (OrZero && match(V, m_Power2OrZero()))
1689 return true;
1690 if (match(V, m_Power2()))
1691 return true;
1692
1693 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1694 // it is shifted off the end then the result is undefined.
1695 if (match(V, m_Shl(m_One(), m_Value())))
1696 return true;
1697
1698 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1699 // the bottom. If it is shifted off the bottom then the result is undefined.
1700 if (match(V, m_LShr(m_SignMask(), m_Value())))
1701 return true;
1702
1703 // The remaining tests are all recursive, so bail out if we hit the limit.
1704 if (Depth++ == MaxDepth)
1705 return false;
1706
1707 Value *X = nullptr, *Y = nullptr;
1708 // A shift left or a logical shift right of a power of two is a power of two
1709 // or zero.
1710 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1711 match(V, m_LShr(m_Value(X), m_Value()))))
1712 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
1713
1714 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1715 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1716
1717 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
1718 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1719 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1720
1721 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1722 // A power of two and'd with anything is a power of two or zero.
1723 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1724 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
1725 return true;
1726 // X & (-X) is always a power of two or zero.
1727 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1728 return true;
1729 return false;
1730 }
1731
1732 // Adding a power-of-two or zero to the same power-of-two or zero yields
1733 // either the original power-of-two, a larger power-of-two or zero.
1734 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1735 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1736 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1737 Q.IIQ.hasNoSignedWrap(VOBO)) {
1738 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1739 match(X, m_And(m_Value(), m_Specific(Y))))
1740 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1741 return true;
1742 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1743 match(Y, m_And(m_Value(), m_Specific(X))))
1744 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1745 return true;
1746
1747 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1748 KnownBits LHSBits(BitWidth);
1749 computeKnownBits(X, LHSBits, Depth, Q);
1750
1751 KnownBits RHSBits(BitWidth);
1752 computeKnownBits(Y, RHSBits, Depth, Q);
1753 // If i8 V is a power of two or zero:
1754 // ZeroBits: 1 1 1 0 1 1 1 1
1755 // ~ZeroBits: 0 0 0 1 0 0 0 0
1756 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
1757 // If OrZero isn't set, we cannot give back a zero result.
1758 // Make sure either the LHS or RHS has a bit set.
1759 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
1760 return true;
1761 }
1762 }
1763
1764 // An exact divide or right shift can only shift off zero bits, so the result
1765 // is a power of two only if the first operand is a power of two and not
1766 // copying a sign bit (sdiv int_min, 2).
1767 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1768 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1769 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1770 Depth, Q);
1771 }
1772
1773 return false;
1774}
1775
1776/// Test whether a GEP's result is known to be non-null.
1777///
1778/// Uses properties inherent in a GEP to try to determine whether it is known
1779/// to be non-null.
1780///
1781/// Currently this routine does not support vector GEPs.
1782static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
1783 const Query &Q) {
1784 const Function *F = nullptr;
1785 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1786 F = I->getFunction();
1787
1788 if (!GEP->isInBounds() ||
1789 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
1790 return false;
1791
1792 // FIXME: Support vector-GEPs.
1793 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP")((GEP->getType()->isPointerTy() && "We only support plain pointer GEP"
) ? static_cast<void> (0) : __assert_fail ("GEP->getType()->isPointerTy() && \"We only support plain pointer GEP\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1793, __PRETTY_FUNCTION__))
;
1794
1795 // If the base pointer is non-null, we cannot walk to a null address with an
1796 // inbounds GEP in address space zero.
1797 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
1798 return true;
1799
1800 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1801 // If so, then the GEP cannot produce a null pointer, as doing so would
1802 // inherently violate the inbounds contract within address space zero.
1803 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1804 GTI != GTE; ++GTI) {
1805 // Struct types are easy -- they must always be indexed by a constant.
1806 if (StructType *STy = GTI.getStructTypeOrNull()) {
1807 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1808 unsigned ElementIdx = OpC->getZExtValue();
1809 const StructLayout *SL = Q.DL.getStructLayout(STy);
1810 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1811 if (ElementOffset > 0)
1812 return true;
1813 continue;
1814 }
1815
1816 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1817 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1818 continue;
1819
1820 // Fast path the constant operand case both for efficiency and so we don't
1821 // increment Depth when just zipping down an all-constant GEP.
1822 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1823 if (!OpC->isZero())
1824 return true;
1825 continue;
1826 }
1827
1828 // We post-increment Depth here because while isKnownNonZero increments it
1829 // as well, when we pop back up that increment won't persist. We don't want
1830 // to recurse 10k times just because we have 10k GEP operands. We don't
1831 // bail completely out because we want to handle constant GEPs regardless
1832 // of depth.
1833 if (Depth++ >= MaxDepth)
1834 continue;
1835
1836 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
1837 return true;
1838 }
1839
1840 return false;
1841}
1842
1843static bool isKnownNonNullFromDominatingCondition(const Value *V,
1844 const Instruction *CtxI,
1845 const DominatorTree *DT) {
1846 assert(V->getType()->isPointerTy() && "V must be pointer type")((V->getType()->isPointerTy() && "V must be pointer type"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isPointerTy() && \"V must be pointer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1846, __PRETTY_FUNCTION__))
;
1847 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull")((!isa<ConstantData>(V) && "Did not expect ConstantPointerNull"
) ? static_cast<void> (0) : __assert_fail ("!isa<ConstantData>(V) && \"Did not expect ConstantPointerNull\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1847, __PRETTY_FUNCTION__))
;
1848
1849 if (!CtxI || !DT)
1850 return false;
1851
1852 unsigned NumUsesExplored = 0;
1853 for (auto *U : V->users()) {
1854 // Avoid massive lists
1855 if (NumUsesExplored >= DomConditionsMaxUses)
1856 break;
1857 NumUsesExplored++;
1858
1859 // If the value is used as an argument to a call or invoke, then argument
1860 // attributes may provide an answer about null-ness.
1861 if (auto CS = ImmutableCallSite(U))
1862 if (auto *CalledFunc = CS.getCalledFunction())
1863 for (const Argument &Arg : CalledFunc->args())
1864 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1865 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1866 return true;
1867
1868 // Consider only compare instructions uniquely controlling a branch
1869 CmpInst::Predicate Pred;
1870 if (!match(const_cast<User *>(U),
1871 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1872 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1873 continue;
1874
1875 SmallVector<const User *, 4> WorkList;
1876 SmallPtrSet<const User *, 4> Visited;
1877 for (auto *CmpU : U->users()) {
1878 assert(WorkList.empty() && "Should be!")((WorkList.empty() && "Should be!") ? static_cast<
void> (0) : __assert_fail ("WorkList.empty() && \"Should be!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1878, __PRETTY_FUNCTION__))
;
1879 if (Visited.insert(CmpU).second)
1880 WorkList.push_back(CmpU);
1881
1882 while (!WorkList.empty()) {
1883 auto *Curr = WorkList.pop_back_val();
1884
1885 // If a user is an AND, add all its users to the work list. We only
1886 // propagate "pred != null" condition through AND because it is only
1887 // correct to assume that all conditions of AND are met in true branch.
1888 // TODO: Support similar logic of OR and EQ predicate?
1889 if (Pred == ICmpInst::ICMP_NE)
1890 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1891 if (BO->getOpcode() == Instruction::And) {
1892 for (auto *BOU : BO->users())
1893 if (Visited.insert(BOU).second)
1894 WorkList.push_back(BOU);
1895 continue;
1896 }
1897
1898 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1899 assert(BI->isConditional() && "uses a comparison!")((BI->isConditional() && "uses a comparison!") ? static_cast
<void> (0) : __assert_fail ("BI->isConditional() && \"uses a comparison!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1899, __PRETTY_FUNCTION__))
;
1900
1901 BasicBlock *NonNullSuccessor =
1902 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1903 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1904 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1905 return true;
1906 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
1907 DT->dominates(cast<Instruction>(Curr), CtxI)) {
1908 return true;
1909 }
1910 }
1911 }
1912 }
1913
1914 return false;
1915}
1916
1917/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1918/// ensure that the value it's attached to is never Value? 'RangeType' is
1919/// is the type of the value described by the range.
1920static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
1921 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1922 assert(NumRanges >= 1)((NumRanges >= 1) ? static_cast<void> (0) : __assert_fail
("NumRanges >= 1", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 1922, __PRETTY_FUNCTION__))
;
1923 for (unsigned i = 0; i < NumRanges; ++i) {
1924 ConstantInt *Lower =
1925 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1926 ConstantInt *Upper =
1927 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1928 ConstantRange Range(Lower->getValue(), Upper->getValue());
1929 if (Range.contains(Value))
1930 return false;
1931 }
1932 return true;
1933}
1934
1935/// Return true if the given value is known to be non-zero when defined. For
1936/// vectors, return true if every element is known to be non-zero when
1937/// defined. For pointers, if the context instruction and dominator tree are
1938/// specified, perform context-sensitive analysis and return true if the
1939/// pointer couldn't possibly be null at the specified instruction.
1940/// Supports values with integer or pointer type and vectors of integers.
1941bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
1942 if (auto *C = dyn_cast<Constant>(V)) {
1943 if (C->isNullValue())
1944 return false;
1945 if (isa<ConstantInt>(C))
1946 // Must be non-zero due to null test above.
1947 return true;
1948
1949 // For constant vectors, check that all elements are undefined or known
1950 // non-zero to determine that the whole vector is known non-zero.
1951 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1952 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1953 Constant *Elt = C->getAggregateElement(i);
1954 if (!Elt || Elt->isNullValue())
1955 return false;
1956 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1957 return false;
1958 }
1959 return true;
1960 }
1961
1962 // A global variable in address space 0 is non null unless extern weak
1963 // or an absolute symbol reference. Other address spaces may have null as a
1964 // valid address for a global, so we can't assume anything.
1965 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1966 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1967 GV->getType()->getAddressSpace() == 0)
1968 return true;
1969 } else
1970 return false;
1971 }
1972
1973 if (auto *I = dyn_cast<Instruction>(V)) {
1974 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
1975 // If the possible ranges don't contain zero, then the value is
1976 // definitely non-zero.
1977 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
1978 const APInt ZeroValue(Ty->getBitWidth(), 0);
1979 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1980 return true;
1981 }
1982 }
1983 }
1984
1985 // Some of the tests below are recursive, so bail out if we hit the limit.
1986 if (Depth++ >= MaxDepth)
1987 return false;
1988
1989 // Check for pointer simplifications.
1990 if (V->getType()->isPointerTy()) {
1991 // Alloca never returns null, malloc might.
1992 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1993 return true;
1994
1995 // A byval, inalloca, or nonnull argument is never null.
1996 if (const Argument *A = dyn_cast<Argument>(V))
1997 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1998 return true;
1999
2000 // A Load tagged with nonnull metadata is never null.
2001 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2002 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
2003 return true;
2004
2005 if (auto CS = ImmutableCallSite(V)) {
2006 if (CS.isReturnNonNull())
2007 return true;
2008 if (const auto *RP = getArgumentAliasingToReturnedPointer(CS))
2009 return isKnownNonZero(RP, Depth, Q);
2010 }
2011 }
2012
2013
2014 // Check for recursive pointer simplifications.
2015 if (V->getType()->isPointerTy()) {
2016 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2017 return true;
2018
2019 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
2020 if (isGEPKnownNonNull(GEP, Depth, Q))
2021 return true;
2022 }
2023
2024 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
2025
2026 // X | Y != 0 if X != 0 or Y != 0.
2027 Value *X = nullptr, *Y = nullptr;
2028 if (match(V, m_Or(m_Value(X), m_Value(Y))))
2029 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
2030
2031 // ext X != 0 if X != 0.
2032 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
2033 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
2034
2035 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
2036 // if the lowest bit is shifted off the end.
2037 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
2038 // shl nuw can't remove any non-zero bits.
2039 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2040 if (Q.IIQ.hasNoUnsignedWrap(BO))
2041 return isKnownNonZero(X, Depth, Q);
2042
2043 KnownBits Known(BitWidth);
2044 computeKnownBits(X, Known, Depth, Q);
2045 if (Known.One[0])
2046 return true;
2047 }
2048 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
2049 // defined if the sign bit is shifted off the end.
2050 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
2051 // shr exact can only shift out zero bits.
2052 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
2053 if (BO->isExact())
2054 return isKnownNonZero(X, Depth, Q);
2055
2056 KnownBits Known = computeKnownBits(X, Depth, Q);
2057 if (Known.isNegative())
2058 return true;
2059
2060 // If the shifter operand is a constant, and all of the bits shifted
2061 // out are known to be zero, and X is known non-zero then at least one
2062 // non-zero bit must remain.
2063 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
2064 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2065 // Is there a known one in the portion not shifted out?
2066 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
2067 return true;
2068 // Are all the bits to be shifted out known zero?
2069 if (Known.countMinTrailingZeros() >= ShiftVal)
2070 return isKnownNonZero(X, Depth, Q);
2071 }
2072 }
2073 // div exact can only produce a zero if the dividend is zero.
2074 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
2075 return isKnownNonZero(X, Depth, Q);
2076 }
2077 // X + Y.
2078 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2079 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2080 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
2081
2082 // If X and Y are both non-negative (as signed values) then their sum is not
2083 // zero unless both X and Y are zero.
2084 if (XKnown.isNonNegative() && YKnown.isNonNegative())
2085 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
2086 return true;
2087
2088 // If X and Y are both negative (as signed values) then their sum is not
2089 // zero unless both X and Y equal INT_MIN.
2090 if (XKnown.isNegative() && YKnown.isNegative()) {
2091 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2092 // The sign bit of X is set. If some other bit is set then X is not equal
2093 // to INT_MIN.
2094 if (XKnown.One.intersects(Mask))
2095 return true;
2096 // The sign bit of Y is set. If some other bit is set then Y is not equal
2097 // to INT_MIN.
2098 if (YKnown.One.intersects(Mask))
2099 return true;
2100 }
2101
2102 // The sum of a non-negative number and a power of two is not zero.
2103 if (XKnown.isNonNegative() &&
2104 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2105 return true;
2106 if (YKnown.isNonNegative() &&
2107 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2108 return true;
2109 }
2110 // X * Y.
2111 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2112 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2113 // If X and Y are non-zero then so is X * Y as long as the multiplication
2114 // does not overflow.
2115 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2116 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
2117 return true;
2118 }
2119 // (C ? X : Y) != 0 if X != 0 and Y != 0.
2120 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
2121 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2122 isKnownNonZero(SI->getFalseValue(), Depth, Q))
2123 return true;
2124 }
2125 // PHI
2126 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2127 // Try and detect a recurrence that monotonically increases from a
2128 // starting value, as these are common as induction variables.
2129 if (PN->getNumIncomingValues() == 2) {
2130 Value *Start = PN->getIncomingValue(0);
2131 Value *Induction = PN->getIncomingValue(1);
2132 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2133 std::swap(Start, Induction);
2134 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2135 if (!C->isZero() && !C->isNegative()) {
2136 ConstantInt *X;
2137 if (Q.IIQ.UseInstrInfo &&
2138 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2139 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2140 !X->isNegative())
2141 return true;
2142 }
2143 }
2144 }
2145 // Check if all incoming values are non-zero constant.
2146 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
2147 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
2148 });
2149 if (AllNonZeroConstants)
2150 return true;
2151 }
2152
2153 KnownBits Known(BitWidth);
2154 computeKnownBits(V, Known, Depth, Q);
2155 return Known.One != 0;
2156}
2157
2158/// Return true if V2 == V1 + X, where X is known non-zero.
2159static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2160 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2161 if (!BO || BO->getOpcode() != Instruction::Add)
2162 return false;
2163 Value *Op = nullptr;
2164 if (V2 == BO->getOperand(0))
2165 Op = BO->getOperand(1);
2166 else if (V2 == BO->getOperand(1))
2167 Op = BO->getOperand(0);
2168 else
2169 return false;
2170 return isKnownNonZero(Op, 0, Q);
2171}
2172
2173/// Return true if it is known that V1 != V2.
2174static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
2175 if (V1 == V2)
2176 return false;
2177 if (V1->getType() != V2->getType())
2178 // We can't look through casts yet.
2179 return false;
2180 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
2181 return true;
2182
2183 if (V1->getType()->isIntOrIntVectorTy()) {
2184 // Are any known bits in V1 contradictory to known bits in V2? If V1
2185 // has a known zero where V2 has a known one, they must not be equal.
2186 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2187 KnownBits Known2 = computeKnownBits(V2, 0, Q);
2188
2189 if (Known1.Zero.intersects(Known2.One) ||
2190 Known2.Zero.intersects(Known1.One))
2191 return true;
2192 }
2193 return false;
2194}
2195
2196/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2197/// simplify operations downstream. Mask is known to be zero for bits that V
2198/// cannot have.
2199///
2200/// This function is defined on values with integer type, values with pointer
2201/// type, and vectors of integers. In the case
2202/// where V is a vector, the mask, known zero, and known one values are the
2203/// same width as the vector element, and the bit is set only if it is true
2204/// for all of the elements in the vector.
2205bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2206 const Query &Q) {
2207 KnownBits Known(Mask.getBitWidth());
2208 computeKnownBits(V, Known, Depth, Q);
2209 return Mask.isSubsetOf(Known.Zero);
2210}
2211
2212// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2213// Returns the input and lower/upper bounds.
2214static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2215 const APInt *&CLow, const APInt *&CHigh) {
2216 assert(isa<Operator>(Select) &&((isa<Operator>(Select) && cast<Operator>
(Select)->getOpcode() == Instruction::Select && "Input should be a Select!"
) ? static_cast<void> (0) : __assert_fail ("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2218, __PRETTY_FUNCTION__))
2217 cast<Operator>(Select)->getOpcode() == Instruction::Select &&((isa<Operator>(Select) && cast<Operator>
(Select)->getOpcode() == Instruction::Select && "Input should be a Select!"
) ? static_cast<void> (0) : __assert_fail ("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2218, __PRETTY_FUNCTION__))
2218 "Input should be a Select!")((isa<Operator>(Select) && cast<Operator>
(Select)->getOpcode() == Instruction::Select && "Input should be a Select!"
) ? static_cast<void> (0) : __assert_fail ("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2218, __PRETTY_FUNCTION__))
;
2219
2220 const Value *LHS, *RHS, *LHS2, *RHS2;
2221 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2222 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2223 return false;
2224
2225 if (!match(RHS, m_APInt(CLow)))
2226 return false;
2227
2228 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2229 if (getInverseMinMaxFlavor(SPF) != SPF2)
2230 return false;
2231
2232 if (!match(RHS2, m_APInt(CHigh)))
2233 return false;
2234
2235 if (SPF == SPF_SMIN)
2236 std::swap(CLow, CHigh);
2237
2238 In = LHS2;
2239 return CLow->sle(*CHigh);
2240}
2241
2242/// For vector constants, loop over the elements and find the constant with the
2243/// minimum number of sign bits. Return 0 if the value is not a vector constant
2244/// or if any element was not analyzed; otherwise, return the count for the
2245/// element with the minimum number of sign bits.
2246static unsigned computeNumSignBitsVectorConstant(const Value *V,
2247 unsigned TyBits) {
2248 const auto *CV = dyn_cast<Constant>(V);
2249 if (!CV || !CV->getType()->isVectorTy())
2250 return 0;
2251
2252 unsigned MinSignBits = TyBits;
2253 unsigned NumElts = CV->getType()->getVectorNumElements();
2254 for (unsigned i = 0; i != NumElts; ++i) {
2255 // If we find a non-ConstantInt, bail out.
2256 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2257 if (!Elt)
2258 return 0;
2259
2260 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
2261 }
2262
2263 return MinSignBits;
2264}
2265
2266static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2267 const Query &Q);
2268
2269static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2270 const Query &Q) {
2271 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2272 assert(Result > 0 && "At least one sign bit needs to be present!")((Result > 0 && "At least one sign bit needs to be present!"
) ? static_cast<void> (0) : __assert_fail ("Result > 0 && \"At least one sign bit needs to be present!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2272, __PRETTY_FUNCTION__))
;
2273 return Result;
2274}
2275
2276/// Return the number of times the sign bit of the register is replicated into
2277/// the other bits. We know that at least 1 bit is always equal to the sign bit
2278/// (itself), but other cases can give us information. For example, immediately
2279/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2280/// other, so we return 3. For vectors, return the number of sign bits for the
2281/// vector element with the minimum number of known sign bits.
2282static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2283 const Query &Q) {
2284 assert(Depth <= MaxDepth && "Limit Search Depth")((Depth <= MaxDepth && "Limit Search Depth") ? static_cast
<void> (0) : __assert_fail ("Depth <= MaxDepth && \"Limit Search Depth\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2284, __PRETTY_FUNCTION__))
;
2285
2286 // We return the minimum number of sign bits that are guaranteed to be present
2287 // in V, so for undef we have to conservatively return 1. We don't have the
2288 // same behavior for poison though -- that's a FIXME today.
2289
2290 Type *ScalarTy = V->getType()->getScalarType();
2291 unsigned TyBits = ScalarTy->isPointerTy() ?
2292 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2293 Q.DL.getTypeSizeInBits(ScalarTy);
2294
2295 unsigned Tmp, Tmp2;
2296 unsigned FirstAnswer = 1;
2297
2298 // Note that ConstantInt is handled by the general computeKnownBits case
2299 // below.
2300
2301 if (Depth == MaxDepth)
2302 return 1; // Limit search depth.
2303
2304 const Operator *U = dyn_cast<Operator>(V);
2305 switch (Operator::getOpcode(V)) {
2306 default: break;
2307 case Instruction::SExt:
2308 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2309 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2310
2311 case Instruction::SDiv: {
2312 const APInt *Denominator;
2313 // sdiv X, C -> adds log(C) sign bits.
2314 if (match(U->getOperand(1), m_APInt(Denominator))) {
2315
2316 // Ignore non-positive denominator.
2317 if (!Denominator->isStrictlyPositive())
2318 break;
2319
2320 // Calculate the incoming numerator bits.
2321 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2322
2323 // Add floor(log(C)) bits to the numerator bits.
2324 return std::min(TyBits, NumBits + Denominator->logBase2());
2325 }
2326 break;
2327 }
2328
2329 case Instruction::SRem: {
2330 const APInt *Denominator;
2331 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2332 // positive constant. This let us put a lower bound on the number of sign
2333 // bits.
2334 if (match(U->getOperand(1), m_APInt(Denominator))) {
2335
2336 // Ignore non-positive denominator.
2337 if (!Denominator->isStrictlyPositive())
2338 break;
2339
2340 // Calculate the incoming numerator bits. SRem by a positive constant
2341 // can't lower the number of sign bits.
2342 unsigned NumrBits =
2343 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2344
2345 // Calculate the leading sign bit constraints by examining the
2346 // denominator. Given that the denominator is positive, there are two
2347 // cases:
2348 //
2349 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2350 // (1 << ceilLogBase2(C)).
2351 //
2352 // 2. the numerator is negative. Then the result range is (-C,0] and
2353 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2354 //
2355 // Thus a lower bound on the number of sign bits is `TyBits -
2356 // ceilLogBase2(C)`.
2357
2358 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2359 return std::max(NumrBits, ResBits);
2360 }
2361 break;
2362 }
2363
2364 case Instruction::AShr: {
2365 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2366 // ashr X, C -> adds C sign bits. Vectors too.
2367 const APInt *ShAmt;
2368 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2369 if (ShAmt->uge(TyBits))
2370 break; // Bad shift.
2371 unsigned ShAmtLimited = ShAmt->getZExtValue();
2372 Tmp += ShAmtLimited;
2373 if (Tmp > TyBits) Tmp = TyBits;
2374 }
2375 return Tmp;
2376 }
2377 case Instruction::Shl: {
2378 const APInt *ShAmt;
2379 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2380 // shl destroys sign bits.
2381 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2382 if (ShAmt->uge(TyBits) || // Bad shift.
2383 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
2384 Tmp2 = ShAmt->getZExtValue();
2385 return Tmp - Tmp2;
2386 }
2387 break;
2388 }
2389 case Instruction::And:
2390 case Instruction::Or:
2391 case Instruction::Xor: // NOT is handled here.
2392 // Logical binary ops preserve the number of sign bits at the worst.
2393 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2394 if (Tmp != 1) {
2395 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2396 FirstAnswer = std::min(Tmp, Tmp2);
2397 // We computed what we know about the sign bits as our first
2398 // answer. Now proceed to the generic code that uses
2399 // computeKnownBits, and pick whichever answer is better.
2400 }
2401 break;
2402
2403 case Instruction::Select: {
2404 // If we have a clamp pattern, we know that the number of sign bits will be
2405 // the minimum of the clamp min/max range.
2406 const Value *X;
2407 const APInt *CLow, *CHigh;
2408 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2409 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2410
2411 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2412 if (Tmp == 1) break;
2413 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
2414 return std::min(Tmp, Tmp2);
2415 }
2416
2417 case Instruction::Add:
2418 // Add can have at most one carry bit. Thus we know that the output
2419 // is, at worst, one more bit than the inputs.
2420 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2421 if (Tmp == 1) break;
2422
2423 // Special case decrementing a value (ADD X, -1):
2424 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2425 if (CRHS->isAllOnesValue()) {
2426 KnownBits Known(TyBits);
2427 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
2428
2429 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2430 // sign bits set.
2431 if ((Known.Zero | 1).isAllOnesValue())
2432 return TyBits;
2433
2434 // If we are subtracting one from a positive number, there is no carry
2435 // out of the result.
2436 if (Known.isNonNegative())
2437 return Tmp;
2438 }
2439
2440 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2441 if (Tmp2 == 1) break;
2442 return std::min(Tmp, Tmp2)-1;
2443
2444 case Instruction::Sub:
2445 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2446 if (Tmp2 == 1) break;
2447
2448 // Handle NEG.
2449 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2450 if (CLHS->isNullValue()) {
2451 KnownBits Known(TyBits);
2452 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
2453 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2454 // sign bits set.
2455 if ((Known.Zero | 1).isAllOnesValue())
2456 return TyBits;
2457
2458 // If the input is known to be positive (the sign bit is known clear),
2459 // the output of the NEG has the same number of sign bits as the input.
2460 if (Known.isNonNegative())
2461 return Tmp2;
2462
2463 // Otherwise, we treat this like a SUB.
2464 }
2465
2466 // Sub can have at most one carry bit. Thus we know that the output
2467 // is, at worst, one more bit than the inputs.
2468 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2469 if (Tmp == 1) break;
2470 return std::min(Tmp, Tmp2)-1;
2471
2472 case Instruction::Mul: {
2473 // The output of the Mul can be at most twice the valid bits in the inputs.
2474 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2475 if (SignBitsOp0 == 1) break;
2476 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2477 if (SignBitsOp1 == 1) break;
2478 unsigned OutValidBits =
2479 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2480 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2481 }
2482
2483 case Instruction::PHI: {
2484 const PHINode *PN = cast<PHINode>(U);
2485 unsigned NumIncomingValues = PN->getNumIncomingValues();
2486 // Don't analyze large in-degree PHIs.
2487 if (NumIncomingValues > 4) break;
2488 // Unreachable blocks may have zero-operand PHI nodes.
2489 if (NumIncomingValues == 0) break;
2490
2491 // Take the minimum of all incoming values. This can't infinitely loop
2492 // because of our depth threshold.
2493 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
2494 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2495 if (Tmp == 1) return Tmp;
2496 Tmp = std::min(
2497 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
2498 }
2499 return Tmp;
2500 }
2501
2502 case Instruction::Trunc:
2503 // FIXME: it's tricky to do anything useful for this, but it is an important
2504 // case for targets like X86.
2505 break;
2506
2507 case Instruction::ExtractElement:
2508 // Look through extract element. At the moment we keep this simple and skip
2509 // tracking the specific element. But at least we might find information
2510 // valid for all elements of the vector (for example if vector is sign
2511 // extended, shifted, etc).
2512 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2513
2514 case Instruction::ShuffleVector:
2515 // If the shuffle mask contains any undefined elements, that element of the
2516 // result is undefined. Propagating information from a source operand may
2517 // not be correct in that case, so just bail out.
2518 if (cast<ShuffleVectorInst>(U)->getMask()->containsUndefElement())
2519 break;
2520
2521 assert((!isa<UndefValue>(U->getOperand(0)) ||(((!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue
>(U->getOperand(1))) && "Should have simplified shuffle with 2 undef inputs"
) ? static_cast<void> (0) : __assert_fail ("(!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue>(U->getOperand(1))) && \"Should have simplified shuffle with 2 undef inputs\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2523, __PRETTY_FUNCTION__))
2522 !isa<UndefValue>(U->getOperand(1)))(((!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue
>(U->getOperand(1))) && "Should have simplified shuffle with 2 undef inputs"
) ? static_cast<void> (0) : __assert_fail ("(!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue>(U->getOperand(1))) && \"Should have simplified shuffle with 2 undef inputs\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2523, __PRETTY_FUNCTION__))
2523 && "Should have simplified shuffle with 2 undef inputs")(((!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue
>(U->getOperand(1))) && "Should have simplified shuffle with 2 undef inputs"
) ? static_cast<void> (0) : __assert_fail ("(!isa<UndefValue>(U->getOperand(0)) || !isa<UndefValue>(U->getOperand(1))) && \"Should have simplified shuffle with 2 undef inputs\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2523, __PRETTY_FUNCTION__))
;
2524
2525 // Look through shuffle of 1 source vector.
2526 if (isa<UndefValue>(U->getOperand(0)))
2527 return ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2528 if (isa<UndefValue>(U->getOperand(1)))
2529 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2530
2531 // TODO: We can look through shuffles of 2 sources by computing the minimum
2532 // sign bits for each operand (similar to what we do for binops).
2533 break;
2534 }
2535
2536 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2537 // use this information.
2538
2539 // If we can examine all elements of a vector constant successfully, we're
2540 // done (we can't do any better than that). If not, keep trying.
2541 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2542 return VecSignBits;
2543
2544 KnownBits Known(TyBits);
2545 computeKnownBits(V, Known, Depth, Q);
2546
2547 // If we know that the sign bit is either zero or one, determine the number of
2548 // identical bits in the top of the input value.
2549 return std::max(FirstAnswer, Known.countMinSignBits());
2550}
2551
2552/// This function computes the integer multiple of Base that equals V.
2553/// If successful, it returns true and returns the multiple in
2554/// Multiple. If unsuccessful, it returns false. It looks
2555/// through SExt instructions only if LookThroughSExt is true.
2556bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2557 bool LookThroughSExt, unsigned Depth) {
2558 const unsigned MaxDepth = 6;
2559
2560 assert(V && "No Value?")((V && "No Value?") ? static_cast<void> (0) : __assert_fail
("V && \"No Value?\"", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2560, __PRETTY_FUNCTION__))
;
2561 assert(Depth <= MaxDepth && "Limit Search Depth")((Depth <= MaxDepth && "Limit Search Depth") ? static_cast
<void> (0) : __assert_fail ("Depth <= MaxDepth && \"Limit Search Depth\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2561, __PRETTY_FUNCTION__))
;
2562 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!")((V->getType()->isIntegerTy() && "Not integer or pointer type!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntegerTy() && \"Not integer or pointer type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2562, __PRETTY_FUNCTION__))
;
2563
2564 Type *T = V->getType();
2565
2566 ConstantInt *CI = dyn_cast<ConstantInt>(V);
2567
2568 if (Base == 0)
2569 return false;
2570
2571 if (Base == 1) {
2572 Multiple = V;
2573 return true;
2574 }
2575
2576 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2577 Constant *BaseVal = ConstantInt::get(T, Base);
2578 if (CO && CO == BaseVal) {
2579 // Multiple is 1.
2580 Multiple = ConstantInt::get(T, 1);
2581 return true;
2582 }
2583
2584 if (CI && CI->getZExtValue() % Base == 0) {
2585 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2586 return true;
2587 }
2588
2589 if (Depth == MaxDepth) return false; // Limit search depth.
2590
2591 Operator *I = dyn_cast<Operator>(V);
2592 if (!I) return false;
2593
2594 switch (I->getOpcode()) {
2595 default: break;
2596 case Instruction::SExt:
2597 if (!LookThroughSExt) return false;
2598 // otherwise fall through to ZExt
2599 LLVM_FALLTHROUGH[[clang::fallthrough]];
2600 case Instruction::ZExt:
2601 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2602 LookThroughSExt, Depth+1);
2603 case Instruction::Shl:
2604 case Instruction::Mul: {
2605 Value *Op0 = I->getOperand(0);
2606 Value *Op1 = I->getOperand(1);
2607
2608 if (I->getOpcode() == Instruction::Shl) {
2609 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2610 if (!Op1CI) return false;
2611 // Turn Op0 << Op1 into Op0 * 2^Op1
2612 APInt Op1Int = Op1CI->getValue();
2613 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2614 APInt API(Op1Int.getBitWidth(), 0);
2615 API.setBit(BitToSet);
2616 Op1 = ConstantInt::get(V->getContext(), API);
2617 }
2618
2619 Value *Mul0 = nullptr;
2620 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2621 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2622 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2623 if (Op1C->getType()->getPrimitiveSizeInBits() <
2624 MulC->getType()->getPrimitiveSizeInBits())
2625 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2626 if (Op1C->getType()->getPrimitiveSizeInBits() >
2627 MulC->getType()->getPrimitiveSizeInBits())
2628 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2629
2630 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2631 Multiple = ConstantExpr::getMul(MulC, Op1C);
2632 return true;
2633 }
2634
2635 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2636 if (Mul0CI->getValue() == 1) {
2637 // V == Base * Op1, so return Op1
2638 Multiple = Op1;
2639 return true;
2640 }
2641 }
2642
2643 Value *Mul1 = nullptr;
2644 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2645 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2646 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2647 if (Op0C->getType()->getPrimitiveSizeInBits() <
2648 MulC->getType()->getPrimitiveSizeInBits())
2649 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2650 if (Op0C->getType()->getPrimitiveSizeInBits() >
2651 MulC->getType()->getPrimitiveSizeInBits())
2652 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2653
2654 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2655 Multiple = ConstantExpr::getMul(MulC, Op0C);
2656 return true;
2657 }
2658
2659 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2660 if (Mul1CI->getValue() == 1) {
2661 // V == Base * Op0, so return Op0
2662 Multiple = Op0;
2663 return true;
2664 }
2665 }
2666 }
2667 }
2668
2669 // We could not determine if V is a multiple of Base.
2670 return false;
2671}
2672
2673Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2674 const TargetLibraryInfo *TLI) {
2675 const Function *F = ICS.getCalledFunction();
2676 if (!F)
2677 return Intrinsic::not_intrinsic;
2678
2679 if (F->isIntrinsic())
2680 return F->getIntrinsicID();
2681
2682 if (!TLI)
2683 return Intrinsic::not_intrinsic;
2684
2685 LibFunc Func;
2686 // We're going to make assumptions on the semantics of the functions, check
2687 // that the target knows that it's available in this environment and it does
2688 // not have local linkage.
2689 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2690 return Intrinsic::not_intrinsic;
2691
2692 if (!ICS.onlyReadsMemory())
2693 return Intrinsic::not_intrinsic;
2694
2695 // Otherwise check if we have a call to a function that can be turned into a
2696 // vector intrinsic.
2697 switch (Func) {
2698 default:
2699 break;
2700 case LibFunc_sin:
2701 case LibFunc_sinf:
2702 case LibFunc_sinl:
2703 return Intrinsic::sin;
2704 case LibFunc_cos:
2705 case LibFunc_cosf:
2706 case LibFunc_cosl:
2707 return Intrinsic::cos;
2708 case LibFunc_exp:
2709 case LibFunc_expf:
2710 case LibFunc_expl:
2711 return Intrinsic::exp;
2712 case LibFunc_exp2:
2713 case LibFunc_exp2f:
2714 case LibFunc_exp2l:
2715 return Intrinsic::exp2;
2716 case LibFunc_log:
2717 case LibFunc_logf:
2718 case LibFunc_logl:
2719 return Intrinsic::log;
2720 case LibFunc_log10:
2721 case LibFunc_log10f:
2722 case LibFunc_log10l:
2723 return Intrinsic::log10;
2724 case LibFunc_log2:
2725 case LibFunc_log2f:
2726 case LibFunc_log2l:
2727 return Intrinsic::log2;
2728 case LibFunc_fabs:
2729 case LibFunc_fabsf:
2730 case LibFunc_fabsl:
2731 return Intrinsic::fabs;
2732 case LibFunc_fmin:
2733 case LibFunc_fminf:
2734 case LibFunc_fminl:
2735 return Intrinsic::minnum;
2736 case LibFunc_fmax:
2737 case LibFunc_fmaxf:
2738 case LibFunc_fmaxl:
2739 return Intrinsic::maxnum;
2740 case LibFunc_copysign:
2741 case LibFunc_copysignf:
2742 case LibFunc_copysignl:
2743 return Intrinsic::copysign;
2744 case LibFunc_floor:
2745 case LibFunc_floorf:
2746 case LibFunc_floorl:
2747 return Intrinsic::floor;
2748 case LibFunc_ceil:
2749 case LibFunc_ceilf:
2750 case LibFunc_ceill:
2751 return Intrinsic::ceil;
2752 case LibFunc_trunc:
2753 case LibFunc_truncf:
2754 case LibFunc_truncl:
2755 return Intrinsic::trunc;
2756 case LibFunc_rint:
2757 case LibFunc_rintf:
2758 case LibFunc_rintl:
2759 return Intrinsic::rint;
2760 case LibFunc_nearbyint:
2761 case LibFunc_nearbyintf:
2762 case LibFunc_nearbyintl:
2763 return Intrinsic::nearbyint;
2764 case LibFunc_round:
2765 case LibFunc_roundf:
2766 case LibFunc_roundl:
2767 return Intrinsic::round;
2768 case LibFunc_pow:
2769 case LibFunc_powf:
2770 case LibFunc_powl:
2771 return Intrinsic::pow;
2772 case LibFunc_sqrt:
2773 case LibFunc_sqrtf:
2774 case LibFunc_sqrtl:
2775 return Intrinsic::sqrt;
2776 }
2777
2778 return Intrinsic::not_intrinsic;
2779}
2780
2781/// Return true if we can prove that the specified FP value is never equal to
2782/// -0.0.
2783///
2784/// NOTE: this function will need to be revisited when we support non-default
2785/// rounding modes!
2786bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2787 unsigned Depth) {
2788 if (auto *CFP = dyn_cast<ConstantFP>(V))
2789 return !CFP->getValueAPF().isNegZero();
2790
2791 // Limit search depth.
2792 if (Depth == MaxDepth)
2793 return false;
2794
2795 auto *Op = dyn_cast<Operator>(V);
2796 if (!Op)
2797 return false;
2798
2799 // Check if the nsz fast-math flag is set.
2800 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
2801 if (FPO->hasNoSignedZeros())
2802 return true;
2803
2804 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
2805 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
2806 return true;
2807
2808 // sitofp and uitofp turn into +0.0 for zero.
2809 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
2810 return true;
2811
2812 if (auto *Call = dyn_cast<CallInst>(Op)) {
2813 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
2814 switch (IID) {
2815 default:
2816 break;
2817 // sqrt(-0.0) = -0.0, no other negative results are possible.
2818 case Intrinsic::sqrt:
2819 case Intrinsic::canonicalize:
2820 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
2821 // fabs(x) != -0.0
2822 case Intrinsic::fabs:
2823 return true;
2824 }
2825 }
2826
2827 return false;
2828}
2829
2830/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2831/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2832/// bit despite comparing equal.
2833static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2834 const TargetLibraryInfo *TLI,
2835 bool SignBitOnly,
2836 unsigned Depth) {
2837 // TODO: This function does not do the right thing when SignBitOnly is true
2838 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2839 // which flips the sign bits of NaNs. See
2840 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2841
2842 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2843 return !CFP->getValueAPF().isNegative() ||
2844 (!SignBitOnly && CFP->getValueAPF().isZero());
2845 }
2846
2847 // Handle vector of constants.
2848 if (auto *CV = dyn_cast<Constant>(V)) {
2849 if (CV->getType()->isVectorTy()) {
2850 unsigned NumElts = CV->getType()->getVectorNumElements();
2851 for (unsigned i = 0; i != NumElts; ++i) {
2852 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2853 if (!CFP)
2854 return false;
2855 if (CFP->getValueAPF().isNegative() &&
2856 (SignBitOnly || !CFP->getValueAPF().isZero()))
2857 return false;
2858 }
2859
2860 // All non-negative ConstantFPs.
2861 return true;
2862 }
2863 }
2864
2865 if (Depth == MaxDepth)
2866 return false; // Limit search depth.
2867
2868 const Operator *I = dyn_cast<Operator>(V);
2869 if (!I)
2870 return false;
2871
2872 switch (I->getOpcode()) {
2873 default:
2874 break;
2875 // Unsigned integers are always nonnegative.
2876 case Instruction::UIToFP:
2877 return true;
2878 case Instruction::FMul:
2879 // x*x is always non-negative or a NaN.
2880 if (I->getOperand(0) == I->getOperand(1) &&
2881 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
2882 return true;
2883
2884 LLVM_FALLTHROUGH[[clang::fallthrough]];
2885 case Instruction::FAdd:
2886 case Instruction::FDiv:
2887 case Instruction::FRem:
2888 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2889 Depth + 1) &&
2890 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2891 Depth + 1);
2892 case Instruction::Select:
2893 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2894 Depth + 1) &&
2895 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2896 Depth + 1);
2897 case Instruction::FPExt:
2898 case Instruction::FPTrunc:
2899 // Widening/narrowing never change sign.
2900 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2901 Depth + 1);
2902 case Instruction::ExtractElement:
2903 // Look through extract element. At the moment we keep this simple and skip
2904 // tracking the specific element. But at least we might find information
2905 // valid for all elements of the vector.
2906 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2907 Depth + 1);
2908 case Instruction::Call:
2909 const auto *CI = cast<CallInst>(I);
2910 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
2911 switch (IID) {
2912 default:
2913 break;
2914 case Intrinsic::maxnum:
2915 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
2916 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
2917 SignBitOnly, Depth + 1)) ||
2918 (isKnownNeverNaN(I->getOperand(1), TLI) &&
2919 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
2920 SignBitOnly, Depth + 1));
2921
2922 case Intrinsic::maximum:
2923 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2924 Depth + 1) ||
2925 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2926 Depth + 1);
2927 case Intrinsic::minnum:
2928 case Intrinsic::minimum:
2929 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2930 Depth + 1) &&
2931 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2932 Depth + 1);
2933 case Intrinsic::exp:
2934 case Intrinsic::exp2:
2935 case Intrinsic::fabs:
2936 return true;
2937
2938 case Intrinsic::sqrt:
2939 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2940 if (!SignBitOnly)
2941 return true;
2942 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2943 CannotBeNegativeZero(CI->getOperand(0), TLI));
2944
2945 case Intrinsic::powi:
2946 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
2947 // powi(x,n) is non-negative if n is even.
2948 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
2949 return true;
2950 }
2951 // TODO: This is not correct. Given that exp is an integer, here are the
2952 // ways that pow can return a negative value:
2953 //
2954 // pow(x, exp) --> negative if exp is odd and x is negative.
2955 // pow(-0, exp) --> -inf if exp is negative odd.
2956 // pow(-0, exp) --> -0 if exp is positive odd.
2957 // pow(-inf, exp) --> -0 if exp is negative odd.
2958 // pow(-inf, exp) --> -inf if exp is positive odd.
2959 //
2960 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2961 // but we must return false if x == -0. Unfortunately we do not currently
2962 // have a way of expressing this constraint. See details in
2963 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2964 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2965 Depth + 1);
2966
2967 case Intrinsic::fma:
2968 case Intrinsic::fmuladd:
2969 // x*x+y is non-negative if y is non-negative.
2970 return I->getOperand(0) == I->getOperand(1) &&
2971 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2972 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2973 Depth + 1);
2974 }
2975 break;
2976 }
2977 return false;
2978}
2979
2980bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2981 const TargetLibraryInfo *TLI) {
2982 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2983}
2984
2985bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2986 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2987}
2988
2989bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
2990 unsigned Depth) {
2991 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type")((V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isFPOrFPVectorTy() && \"Querying for NaN on non-FP type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 2991, __PRETTY_FUNCTION__))
;
2992
2993 // If we're told that NaNs won't happen, assume they won't.
2994 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
2995 if (FPMathOp->hasNoNaNs())
2996 return true;
2997
2998 // Handle scalar constants.
2999 if (auto *CFP = dyn_cast<ConstantFP>(V))
3000 return !CFP->isNaN();
3001
3002 if (Depth == MaxDepth)
3003 return false;
3004
3005 if (auto *Inst = dyn_cast<Instruction>(V)) {
3006 switch (Inst->getOpcode()) {
3007 case Instruction::FAdd:
3008 case Instruction::FMul:
3009 case Instruction::FSub:
3010 case Instruction::FDiv:
3011 case Instruction::FRem: {
3012 // TODO: Need isKnownNeverInfinity
3013 return false;
3014 }
3015 case Instruction::Select: {
3016 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3017 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3018 }
3019 case Instruction::SIToFP:
3020 case Instruction::UIToFP:
3021 return true;
3022 case Instruction::FPTrunc:
3023 case Instruction::FPExt:
3024 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3025 default:
3026 break;
3027 }
3028 }
3029
3030 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3031 switch (II->getIntrinsicID()) {
3032 case Intrinsic::canonicalize:
3033 case Intrinsic::fabs:
3034 case Intrinsic::copysign:
3035 case Intrinsic::exp:
3036 case Intrinsic::exp2:
3037 case Intrinsic::floor:
3038 case Intrinsic::ceil:
3039 case Intrinsic::trunc:
3040 case Intrinsic::rint:
3041 case Intrinsic::nearbyint:
3042 case Intrinsic::round:
3043 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3044 case Intrinsic::sqrt:
3045 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3046 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3047 default:
3048 return false;
3049 }
3050 }
3051
3052 // Bail out for constant expressions, but try to handle vector constants.
3053 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3054 return false;
3055
3056 // For vectors, verify that each element is not NaN.
3057 unsigned NumElts = V->getType()->getVectorNumElements();
3058 for (unsigned i = 0; i != NumElts; ++i) {
3059 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3060 if (!Elt)
3061 return false;
3062 if (isa<UndefValue>(Elt))
3063 continue;
3064 auto *CElt = dyn_cast<ConstantFP>(Elt);
3065 if (!CElt || CElt->isNaN())
3066 return false;
3067 }
3068 // All elements were confirmed not-NaN or undefined.
3069 return true;
3070}
3071
3072Value *llvm::isBytewiseValue(Value *V) {
3073
3074 // All byte-wide stores are splatable, even of arbitrary variables.
3075 if (V->getType()->isIntegerTy(8))
3076 return V;
3077
3078 LLVMContext &Ctx = V->getContext();
3079
3080 // Undef don't care.
3081 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3082 if (isa<UndefValue>(V))
3083 return UndefInt8;
3084
3085 Constant *C = dyn_cast<Constant>(V);
3086 if (!C) {
3087 // Conceptually, we could handle things like:
3088 // %a = zext i8 %X to i16
3089 // %b = shl i16 %a, 8
3090 // %c = or i16 %a, %b
3091 // but until there is an example that actually needs this, it doesn't seem
3092 // worth worrying about.
3093 return nullptr;
3094 }
3095
3096 // Handle 'null' ConstantArrayZero etc.
3097 if (C->isNullValue())
3098 return Constant::getNullValue(Type::getInt8Ty(Ctx));
3099
3100 // Constant floating-point values can be handled as integer values if the
3101 // corresponding integer value is "byteable". An important case is 0.0.
3102 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3103 Type *Ty = nullptr;
3104 if (CFP->getType()->isHalfTy())
3105 Ty = Type::getInt16Ty(Ctx);
3106 else if (CFP->getType()->isFloatTy())
3107 Ty = Type::getInt32Ty(Ctx);
3108 else if (CFP->getType()->isDoubleTy())
3109 Ty = Type::getInt64Ty(Ctx);
3110 // Don't handle long double formats, which have strange constraints.
3111 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty)) : nullptr;
3112 }
3113
3114 // We can handle constant integers that are multiple of 8 bits.
3115 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
3116 if (CI->getBitWidth() % 8 == 0) {
3117 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!")((CI->getBitWidth() > 8 && "8 bits should be handled above!"
) ? static_cast<void> (0) : __assert_fail ("CI->getBitWidth() > 8 && \"8 bits should be handled above!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118 if (!CI->getValue().isSplat(8))
3119 return nullptr;
3120 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
3121 }
3122 }
3123
3124 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3125 if (LHS == RHS)
3126 return LHS;
3127 if (!LHS || !RHS)
3128 return nullptr;
3129 if (LHS == UndefInt8)
3130 return RHS;
3131 if (RHS == UndefInt8)
3132 return LHS;
3133 return nullptr;
3134 };
3135
3136 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3137 Value *Val = UndefInt8;
3138 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3139 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I)))))
3140 return nullptr;
3141 return Val;
3142 }
3143
3144 if (isa<ConstantVector>(C)) {
3145 Constant *Splat = cast<ConstantVector>(C)->getSplatValue();
3146 return Splat ? isBytewiseValue(Splat) : nullptr;
3147 }
3148
3149 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3150 Value *Val = UndefInt8;
3151 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3152 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I)))))
3153 return nullptr;
3154 return Val;
3155 }
3156
3157 // Don't try to handle the handful of other constants.
3158 return nullptr;
3159}
3160
3161// This is the recursive version of BuildSubAggregate. It takes a few different
3162// arguments. Idxs is the index within the nested struct From that we are
3163// looking at now (which is of type IndexedType). IdxSkip is the number of
3164// indices from Idxs that should be left out when inserting into the resulting
3165// struct. To is the result struct built so far, new insertvalue instructions
3166// build on that.
3167static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
3168 SmallVectorImpl<unsigned> &Idxs,
3169 unsigned IdxSkip,
3170 Instruction *InsertBefore) {
3171 StructType *STy = dyn_cast<StructType>(IndexedType);
3172 if (STy) {
3173 // Save the original To argument so we can modify it
3174 Value *OrigTo = To;
3175 // General case, the type indexed by Idxs is a struct
3176 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3177 // Process each struct element recursively
3178 Idxs.push_back(i);
3179 Value *PrevTo = To;
3180 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
3181 InsertBefore);
3182 Idxs.pop_back();
3183 if (!To) {
3184 // Couldn't find any inserted value for this index? Cleanup
3185 while (PrevTo != OrigTo) {
3186 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3187 PrevTo = Del->getAggregateOperand();
3188 Del->eraseFromParent();
3189 }
3190 // Stop processing elements
3191 break;
3192 }
3193 }
3194 // If we successfully found a value for each of our subaggregates
3195 if (To)
3196 return To;
3197 }
3198 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3199 // the struct's elements had a value that was inserted directly. In the latter
3200 // case, perhaps we can't determine each of the subelements individually, but
3201 // we might be able to find the complete struct somewhere.
3202
3203 // Find the value that is at that particular spot
3204 Value *V = FindInsertedValue(From, Idxs);
3205
3206 if (!V)
3207 return nullptr;
3208
3209 // Insert the value in the new (sub) aggregate
3210 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3211 "tmp", InsertBefore);
3212}
3213
3214// This helper takes a nested struct and extracts a part of it (which is again a
3215// struct) into a new value. For example, given the struct:
3216// { a, { b, { c, d }, e } }
3217// and the indices "1, 1" this returns
3218// { c, d }.
3219//
3220// It does this by inserting an insertvalue for each element in the resulting
3221// struct, as opposed to just inserting a single struct. This will only work if
3222// each of the elements of the substruct are known (ie, inserted into From by an
3223// insertvalue instruction somewhere).
3224//
3225// All inserted insertvalue instructions are inserted before InsertBefore
3226static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
3227 Instruction *InsertBefore) {
3228 assert(InsertBefore && "Must have someplace to insert!")((InsertBefore && "Must have someplace to insert!") ?
static_cast<void> (0) : __assert_fail ("InsertBefore && \"Must have someplace to insert!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3228, __PRETTY_FUNCTION__))
;
3229 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
3230 idx_range);
3231 Value *To = UndefValue::get(IndexedType);
3232 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
3233 unsigned IdxSkip = Idxs.size();
3234
3235 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
3236}
3237
3238/// Given an aggregate and a sequence of indices, see if the scalar value
3239/// indexed is already around as a register, for example if it was inserted
3240/// directly into the aggregate.
3241///
3242/// If InsertBefore is not null, this function will duplicate (modified)
3243/// insertvalues when a part of a nested struct is extracted.
3244Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3245 Instruction *InsertBefore) {
3246 // Nothing to index? Just return V then (this is useful at the end of our
3247 // recursion).
3248 if (idx_range.empty())
3249 return V;
3250 // We have indices, so V should have an indexable type.
3251 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&(((V->getType()->isStructTy() || V->getType()->isArrayTy
()) && "Not looking at a struct or array?") ? static_cast
<void> (0) : __assert_fail ("(V->getType()->isStructTy() || V->getType()->isArrayTy()) && \"Not looking at a struct or array?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3252, __PRETTY_FUNCTION__))
3252 "Not looking at a struct or array?")(((V->getType()->isStructTy() || V->getType()->isArrayTy
()) && "Not looking at a struct or array?") ? static_cast
<void> (0) : __assert_fail ("(V->getType()->isStructTy() || V->getType()->isArrayTy()) && \"Not looking at a struct or array?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3252, __PRETTY_FUNCTION__))
;
3253 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&((ExtractValueInst::getIndexedType(V->getType(), idx_range
) && "Invalid indices for type?") ? static_cast<void
> (0) : __assert_fail ("ExtractValueInst::getIndexedType(V->getType(), idx_range) && \"Invalid indices for type?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3254, __PRETTY_FUNCTION__))
3254 "Invalid indices for type?")((ExtractValueInst::getIndexedType(V->getType(), idx_range
) && "Invalid indices for type?") ? static_cast<void
> (0) : __assert_fail ("ExtractValueInst::getIndexedType(V->getType(), idx_range) && \"Invalid indices for type?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3254, __PRETTY_FUNCTION__))
;
3255
3256 if (Constant *C = dyn_cast<Constant>(V)) {
3257 C = C->getAggregateElement(idx_range[0]);
3258 if (!C) return nullptr;
3259 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3260 }
3261
3262 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
3263 // Loop the indices for the insertvalue instruction in parallel with the
3264 // requested indices
3265 const unsigned *req_idx = idx_range.begin();
3266 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3267 i != e; ++i, ++req_idx) {
3268 if (req_idx == idx_range.end()) {
3269 // We can't handle this without inserting insertvalues
3270 if (!InsertBefore)
3271 return nullptr;
3272
3273 // The requested index identifies a part of a nested aggregate. Handle
3274 // this specially. For example,
3275 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3276 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3277 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3278 // This can be changed into
3279 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3280 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3281 // which allows the unused 0,0 element from the nested struct to be
3282 // removed.
3283 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3284 InsertBefore);
3285 }
3286
3287 // This insert value inserts something else than what we are looking for.
3288 // See if the (aggregate) value inserted into has the value we are
3289 // looking for, then.
3290 if (*req_idx != *i)
3291 return FindInsertedValue(I->getAggregateOperand(), idx_range,
3292 InsertBefore);
3293 }
3294 // If we end up here, the indices of the insertvalue match with those
3295 // requested (though possibly only partially). Now we recursively look at
3296 // the inserted value, passing any remaining indices.
3297 return FindInsertedValue(I->getInsertedValueOperand(),
3298 makeArrayRef(req_idx, idx_range.end()),
3299 InsertBefore);
3300 }
3301
3302 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
3303 // If we're extracting a value from an aggregate that was extracted from
3304 // something else, we can extract from that something else directly instead.
3305 // However, we will need to chain I's indices with the requested indices.
3306
3307 // Calculate the number of indices required
3308 unsigned size = I->getNumIndices() + idx_range.size();
3309 // Allocate some space to put the new indices in
3310 SmallVector<unsigned, 5> Idxs;
3311 Idxs.reserve(size);
3312 // Add indices from the extract value instruction
3313 Idxs.append(I->idx_begin(), I->idx_end());
3314
3315 // Add requested indices
3316 Idxs.append(idx_range.begin(), idx_range.end());
3317
3318 assert(Idxs.size() == size((Idxs.size() == size && "Number of indices added not correct?"
) ? static_cast<void> (0) : __assert_fail ("Idxs.size() == size && \"Number of indices added not correct?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3319, __PRETTY_FUNCTION__))
3319 && "Number of indices added not correct?")((Idxs.size() == size && "Number of indices added not correct?"
) ? static_cast<void> (0) : __assert_fail ("Idxs.size() == size && \"Number of indices added not correct?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3319, __PRETTY_FUNCTION__))
;
3320
3321 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
3322 }
3323 // Otherwise, we don't know (such as, extracting from a function return value
3324 // or load instruction)
3325 return nullptr;
3326}
3327
3328/// Analyze the specified pointer to see if it can be expressed as a base
3329/// pointer plus a constant offset. Return the base and offset to the caller.
3330Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
3331 const DataLayout &DL) {
3332 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
3333 APInt ByteOffset(BitWidth, 0);
3334
3335 // We walk up the defs but use a visited set to handle unreachable code. In
3336 // that case, we stop after accumulating the cycle once (not that it
3337 // matters).
3338 SmallPtrSet<Value *, 16> Visited;
3339 while (Visited.insert(Ptr).second) {
3340 if (Ptr->getType()->isVectorTy())
3341 break;
3342
3343 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
3344 // If one of the values we have visited is an addrspacecast, then
3345 // the pointer type of this GEP may be different from the type
3346 // of the Ptr parameter which was passed to this function. This
3347 // means when we construct GEPOffset, we need to use the size
3348 // of GEP's pointer type rather than the size of the original
3349 // pointer type.
3350 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
3351 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3352 break;
3353
3354 ByteOffset += GEPOffset.getSExtValue();
3355
3356 Ptr = GEP->getPointerOperand();
3357 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3358 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
3359 Ptr = cast<Operator>(Ptr)->getOperand(0);
3360 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
3361 if (GA->isInterposable())
3362 break;
3363 Ptr = GA->getAliasee();
3364 } else {
3365 break;
3366 }
3367 }
3368 Offset = ByteOffset.getSExtValue();
3369 return Ptr;
3370}
3371
3372bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3373 unsigned CharSize) {
3374 // Make sure the GEP has exactly three arguments.
3375 if (GEP->getNumOperands() != 3)
3376 return false;
3377
3378 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3379 // CharSize.
3380 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
3381 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
3382 return false;
3383
3384 // Check to make sure that the first operand of the GEP is an integer and
3385 // has value 0 so that we are sure we're indexing into the initializer.
3386 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3387 if (!FirstIdx || !FirstIdx->isZero())
3388 return false;
3389
3390 return true;
3391}
3392
3393bool llvm::getConstantDataArrayInfo(const Value *V,
3394 ConstantDataArraySlice &Slice,
3395 unsigned ElementSize, uint64_t Offset) {
3396 assert(V)((V) ? static_cast<void> (0) : __assert_fail ("V", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3396, __PRETTY_FUNCTION__))
;
3397
3398 // Look through bitcast instructions and geps.
3399 V = V->stripPointerCasts();
3400
3401 // If the value is a GEP instruction or constant expression, treat it as an
3402 // offset.
3403 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3404 // The GEP operator should be based on a pointer to string constant, and is
3405 // indexing into the string constant.
3406 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
3407 return false;
3408
3409 // If the second index isn't a ConstantInt, then this is a variable index
3410 // into the array. If this occurs, we can't say anything meaningful about
3411 // the string.
3412 uint64_t StartIdx = 0;
3413 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
3414 StartIdx = CI->getZExtValue();
3415 else
3416 return false;
3417 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3418 StartIdx + Offset);
3419 }
3420
3421 // The GEP instruction, constant or instruction, must reference a global
3422 // variable that is a constant and is initialized. The referenced constant
3423 // initializer is the array that we'll use for optimization.
3424 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3425 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
3426 return false;
3427
3428 const ConstantDataArray *Array;
3429 ArrayType *ArrayTy;
3430 if (GV->getInitializer()->isNullValue()) {
3431 Type *GVTy = GV->getValueType();
3432 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
3433 // A zeroinitializer for the array; there is no ConstantDataArray.
3434 Array = nullptr;
3435 } else {
3436 const DataLayout &DL = GV->getParent()->getDataLayout();
3437 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3438 uint64_t Length = SizeInBytes / (ElementSize / 8);
3439 if (Length <= Offset)
3440 return false;
3441
3442 Slice.Array = nullptr;
3443 Slice.Offset = 0;
3444 Slice.Length = Length - Offset;
3445 return true;
3446 }
3447 } else {
3448 // This must be a ConstantDataArray.
3449 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3450 if (!Array)
3451 return false;
3452 ArrayTy = Array->getType();
3453 }
3454 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
3455 return false;
3456
3457 uint64_t NumElts = ArrayTy->getArrayNumElements();
3458 if (Offset > NumElts)
3459 return false;
3460
3461 Slice.Array = Array;
3462 Slice.Offset = Offset;
3463 Slice.Length = NumElts - Offset;
3464 return true;
3465}
3466
3467/// This function computes the length of a null-terminated C string pointed to
3468/// by V. If successful, it returns true and returns the string in Str.
3469/// If unsuccessful, it returns false.
3470bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3471 uint64_t Offset, bool TrimAtNul) {
3472 ConstantDataArraySlice Slice;
3473 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3474 return false;
3475
3476 if (Slice.Array == nullptr) {
3477 if (TrimAtNul) {
3478 Str = StringRef();
3479 return true;
3480 }
3481 if (Slice.Length == 1) {
3482 Str = StringRef("", 1);
3483 return true;
3484 }
3485 // We cannot instantiate a StringRef as we do not have an appropriate string
3486 // of 0s at hand.
3487 return false;
3488 }
3489
3490 // Start out with the entire array in the StringRef.
3491 Str = Slice.Array->getAsString();
3492 // Skip over 'offset' bytes.
3493 Str = Str.substr(Slice.Offset);
3494
3495 if (TrimAtNul) {
3496 // Trim off the \0 and anything after it. If the array is not nul
3497 // terminated, we just return the whole end of string. The client may know
3498 // some other way that the string is length-bound.
3499 Str = Str.substr(0, Str.find('\0'));
3500 }
3501 return true;
3502}
3503
3504// These next two are very similar to the above, but also look through PHI
3505// nodes.
3506// TODO: See if we can integrate these two together.
3507
3508/// If we can compute the length of the string pointed to by
3509/// the specified pointer, return 'len+1'. If we can't, return 0.
3510static uint64_t GetStringLengthH(const Value *V,
3511 SmallPtrSetImpl<const PHINode*> &PHIs,
3512 unsigned CharSize) {
3513 // Look through noop bitcast instructions.
3514 V = V->stripPointerCasts();
3515
3516 // If this is a PHI node, there are two cases: either we have already seen it
3517 // or we haven't.
3518 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
3519 if (!PHIs.insert(PN).second)
3520 return ~0ULL; // already in the set.
3521
3522 // If it was new, see if all the input strings are the same length.
3523 uint64_t LenSoFar = ~0ULL;
3524 for (Value *IncValue : PN->incoming_values()) {
3525 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
3526 if (Len == 0) return 0; // Unknown length -> unknown.
3527
3528 if (Len == ~0ULL) continue;
3529
3530 if (Len != LenSoFar && LenSoFar != ~0ULL)
3531 return 0; // Disagree -> unknown.
3532 LenSoFar = Len;
3533 }
3534
3535 // Success, all agree.
3536 return LenSoFar;
3537 }
3538
3539 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
3540 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
3541 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
3542 if (Len1 == 0) return 0;
3543 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
3544 if (Len2 == 0) return 0;
3545 if (Len1 == ~0ULL) return Len2;
3546 if (Len2 == ~0ULL) return Len1;
3547 if (Len1 != Len2) return 0;
3548 return Len1;
3549 }
3550
3551 // Otherwise, see if we can read the string.
3552 ConstantDataArraySlice Slice;
3553 if (!getConstantDataArrayInfo(V, Slice, CharSize))
3554 return 0;
3555
3556 if (Slice.Array == nullptr)
3557 return 1;
3558
3559 // Search for nul characters
3560 unsigned NullIndex = 0;
3561 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3562 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3563 break;
3564 }
3565
3566 return NullIndex + 1;
3567}
3568
3569/// If we can compute the length of the string pointed to by
3570/// the specified pointer, return 'len+1'. If we can't, return 0.
3571uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
3572 if (!V->getType()->isPointerTy())
3573 return 0;
3574
3575 SmallPtrSet<const PHINode*, 32> PHIs;
3576 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
3577 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3578 // an empty string as a length.
3579 return Len == ~0ULL ? 1 : Len;
3580}
3581
3582const Value *llvm::getArgumentAliasingToReturnedPointer(ImmutableCallSite CS) {
3583 assert(CS &&((CS && "getArgumentAliasingToReturnedPointer only works on nonnull CallSite"
) ? static_cast<void> (0) : __assert_fail ("CS && \"getArgumentAliasingToReturnedPointer only works on nonnull CallSite\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3584, __PRETTY_FUNCTION__))
3584 "getArgumentAliasingToReturnedPointer only works on nonnull CallSite")((CS && "getArgumentAliasingToReturnedPointer only works on nonnull CallSite"
) ? static_cast<void> (0) : __assert_fail ("CS && \"getArgumentAliasingToReturnedPointer only works on nonnull CallSite\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3584, __PRETTY_FUNCTION__))
;
3585 if (const Value *RV = CS.getReturnedArgOperand())
3586 return RV;
3587 // This can be used only as a aliasing property.
3588 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CS))
3589 return CS.getArgOperand(0);
3590 return nullptr;
3591}
3592
3593bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
3594 ImmutableCallSite CS) {
3595 return CS.getIntrinsicID() == Intrinsic::launder_invariant_group ||
3596 CS.getIntrinsicID() == Intrinsic::strip_invariant_group;
3597}
3598
3599/// \p PN defines a loop-variant pointer to an object. Check if the
3600/// previous iteration of the loop was referring to the same object as \p PN.
3601static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3602 const LoopInfo *LI) {
3603 // Find the loop-defined value.
3604 Loop *L = LI->getLoopFor(PN->getParent());
3605 if (PN->getNumIncomingValues() != 2)
3606 return true;
3607
3608 // Find the value from previous iteration.
3609 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3610 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3611 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3612 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3613 return true;
3614
3615 // If a new pointer is loaded in the loop, the pointer references a different
3616 // object in every iteration. E.g.:
3617 // for (i)
3618 // int *p = a[i];
3619 // ...
3620 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3621 if (!L->isLoopInvariant(Load->getPointerOperand()))
3622 return false;
3623 return true;
3624}
3625
3626Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3627 unsigned MaxLookup) {
3628 if (!V->getType()->isPointerTy())
3629 return V;
3630 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3631 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3632 V = GEP->getPointerOperand();
3633 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3634 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3635 V = cast<Operator>(V)->getOperand(0);
3636 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3637 if (GA->isInterposable())
3638 return V;
3639 V = GA->getAliasee();
3640 } else if (isa<AllocaInst>(V)) {
3641 // An alloca can't be further simplified.
3642 return V;
3643 } else {
3644 if (auto CS = CallSite(V)) {
3645 // CaptureTracking can know about special capturing properties of some
3646 // intrinsics like launder.invariant.group, that can't be expressed with
3647 // the attributes, but have properties like returning aliasing pointer.
3648 // Because some analysis may assume that nocaptured pointer is not
3649 // returned from some special intrinsic (because function would have to
3650 // be marked with returns attribute), it is crucial to use this function
3651 // because it should be in sync with CaptureTracking. Not using it may
3652 // cause weird miscompilations where 2 aliasing pointers are assumed to
3653 // noalias.
3654 if (auto *RP = getArgumentAliasingToReturnedPointer(CS)) {
3655 V = RP;
3656 continue;
3657 }
3658 }
3659
3660 // See if InstructionSimplify knows any relevant tricks.
3661 if (Instruction *I = dyn_cast<Instruction>(V))
3662 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3663 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
3664 V = Simplified;
3665 continue;
3666 }
3667
3668 return V;
3669 }
3670 assert(V->getType()->isPointerTy() && "Unexpected operand type!")((V->getType()->isPointerTy() && "Unexpected operand type!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isPointerTy() && \"Unexpected operand type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3670, __PRETTY_FUNCTION__))
;
3671 }
3672 return V;
3673}
3674
3675void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
3676 const DataLayout &DL, LoopInfo *LI,
3677 unsigned MaxLookup) {
3678 SmallPtrSet<Value *, 4> Visited;
3679 SmallVector<Value *, 4> Worklist;
3680 Worklist.push_back(V);
3681 do {
3682 Value *P = Worklist.pop_back_val();
3683 P = GetUnderlyingObject(P, DL, MaxLookup);
3684
3685 if (!Visited.insert(P).second)
3686 continue;
3687
3688 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3689 Worklist.push_back(SI->getTrueValue());
3690 Worklist.push_back(SI->getFalseValue());
3691 continue;
3692 }
3693
3694 if (PHINode *PN = dyn_cast<PHINode>(P)) {
3695 // If this PHI changes the underlying object in every iteration of the
3696 // loop, don't look through it. Consider:
3697 // int **A;
3698 // for (i) {
3699 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3700 // Curr = A[i];
3701 // *Prev, *Curr;
3702 //
3703 // Prev is tracking Curr one iteration behind so they refer to different
3704 // underlying objects.
3705 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3706 isSameUnderlyingObjectInLoop(PN, LI))
3707 for (Value *IncValue : PN->incoming_values())
3708 Worklist.push_back(IncValue);
3709 continue;
3710 }
3711
3712 Objects.push_back(P);
3713 } while (!Worklist.empty());
3714}
3715
3716/// This is the function that does the work of looking through basic
3717/// ptrtoint+arithmetic+inttoptr sequences.
3718static const Value *getUnderlyingObjectFromInt(const Value *V) {
3719 do {
3720 if (const Operator *U = dyn_cast<Operator>(V)) {
3721 // If we find a ptrtoint, we can transfer control back to the
3722 // regular getUnderlyingObjectFromInt.
3723 if (U->getOpcode() == Instruction::PtrToInt)
3724 return U->getOperand(0);
3725 // If we find an add of a constant, a multiplied value, or a phi, it's
3726 // likely that the other operand will lead us to the base
3727 // object. We don't have to worry about the case where the
3728 // object address is somehow being computed by the multiply,
3729 // because our callers only care when the result is an
3730 // identifiable object.
3731 if (U->getOpcode() != Instruction::Add ||
3732 (!isa<ConstantInt>(U->getOperand(1)) &&
3733 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3734 !isa<PHINode>(U->getOperand(1))))
3735 return V;
3736 V = U->getOperand(0);
3737 } else {
3738 return V;
3739 }
3740 assert(V->getType()->isIntegerTy() && "Unexpected operand type!")((V->getType()->isIntegerTy() && "Unexpected operand type!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntegerTy() && \"Unexpected operand type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 3740, __PRETTY_FUNCTION__))
;
3741 } while (true);
3742}
3743
3744/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3745/// ptrtoint+arithmetic+inttoptr sequences.
3746/// It returns false if unidentified object is found in GetUnderlyingObjects.
3747bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
3748 SmallVectorImpl<Value *> &Objects,
3749 const DataLayout &DL) {
3750 SmallPtrSet<const Value *, 16> Visited;
3751 SmallVector<const Value *, 4> Working(1, V);
3752 do {
3753 V = Working.pop_back_val();
3754
3755 SmallVector<Value *, 4> Objs;
3756 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3757
3758 for (Value *V : Objs) {
3759 if (!Visited.insert(V).second)
3760 continue;
3761 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3762 const Value *O =
3763 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3764 if (O->getType()->isPointerTy()) {
3765 Working.push_back(O);
3766 continue;
3767 }
3768 }
3769 // If GetUnderlyingObjects fails to find an identifiable object,
3770 // getUnderlyingObjectsForCodeGen also fails for safety.
3771 if (!isIdentifiedObject(V)) {
3772 Objects.clear();
3773 return false;
3774 }
3775 Objects.push_back(const_cast<Value *>(V));
3776 }
3777 } while (!Working.empty());
3778 return true;
3779}
3780
3781/// Return true if the only users of this pointer are lifetime markers.
3782bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3783 for (const User *U : V->users()) {
3784 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3785 if (!II) return false;
3786
3787 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3788 II->getIntrinsicID() != Intrinsic::lifetime_end)
3789 return false;
3790 }
3791 return true;
3792}
3793
3794bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3795 const Instruction *CtxI,
3796 const DominatorTree *DT) {
3797 const Operator *Inst = dyn_cast<Operator>(V);
3798 if (!Inst)
3799 return false;
3800
3801 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3802 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3803 if (C->canTrap())
3804 return false;
3805
3806 switch (Inst->getOpcode()) {
3807 default:
3808 return true;
3809 case Instruction::UDiv:
3810 case Instruction::URem: {
3811 // x / y is undefined if y == 0.
3812 const APInt *V;
3813 if (match(Inst->getOperand(1), m_APInt(V)))
3814 return *V != 0;
3815 return false;
3816 }
3817 case Instruction::SDiv:
3818 case Instruction::SRem: {
3819 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3820 const APInt *Numerator, *Denominator;
3821 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3822 return false;
3823 // We cannot hoist this division if the denominator is 0.
3824 if (*Denominator == 0)
3825 return false;
3826 // It's safe to hoist if the denominator is not 0 or -1.
3827 if (*Denominator != -1)
3828 return true;
3829 // At this point we know that the denominator is -1. It is safe to hoist as
3830 // long we know that the numerator is not INT_MIN.
3831 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3832 return !Numerator->isMinSignedValue();
3833 // The numerator *might* be MinSignedValue.
3834 return false;
3835 }
3836 case Instruction::Load: {
3837 const LoadInst *LI = cast<LoadInst>(Inst);
3838 if (!LI->isUnordered() ||
3839 // Speculative load may create a race that did not exist in the source.
3840 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
3841 // Speculative load may load data from dirty regions.
3842 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3843 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3844 return false;
3845 const DataLayout &DL = LI->getModule()->getDataLayout();
3846 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3847 LI->getAlignment(), DL, CtxI, DT);
3848 }
3849 case Instruction::Call: {
3850 auto *CI = cast<const CallInst>(Inst);
3851 const Function *Callee = CI->getCalledFunction();
3852
3853 // The called function could have undefined behavior or side-effects, even
3854 // if marked readnone nounwind.
3855 return Callee && Callee->isSpeculatable();
3856 }
3857 case Instruction::VAArg:
3858 case Instruction::Alloca:
3859 case Instruction::Invoke:
3860 case Instruction::PHI:
3861 case Instruction::Store:
3862 case Instruction::Ret:
3863 case Instruction::Br:
3864 case Instruction::IndirectBr:
3865 case Instruction::Switch:
3866 case Instruction::Unreachable:
3867 case Instruction::Fence:
3868 case Instruction::AtomicRMW:
3869 case Instruction::AtomicCmpXchg:
3870 case Instruction::LandingPad:
3871 case Instruction::Resume:
3872 case Instruction::CatchSwitch:
3873 case Instruction::CatchPad:
3874 case Instruction::CatchRet:
3875 case Instruction::CleanupPad:
3876 case Instruction::CleanupRet:
3877 return false; // Misc instructions which have effects
3878 }
3879}
3880
3881bool llvm::mayBeMemoryDependent(const Instruction &I) {
3882 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3883}
3884
3885OverflowResult llvm::computeOverflowForUnsignedMul(
3886 const Value *LHS, const Value *RHS, const DataLayout &DL,
3887 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3888 bool UseInstrInfo) {
3889 // Multiplying n * m significant bits yields a result of n + m significant
3890 // bits. If the total number of significant bits does not exceed the
3891 // result bit width (minus 1), there is no overflow.
3892 // This means if we have enough leading zero bits in the operands
3893 // we can guarantee that the result does not overflow.
3894 // Ref: "Hacker's Delight" by Henry Warren
3895 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3896 KnownBits LHSKnown(BitWidth);
3897 KnownBits RHSKnown(BitWidth);
3898 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3899 UseInstrInfo);
3900 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT, nullptr,
3901 UseInstrInfo);
3902 // Note that underestimating the number of zero bits gives a more
3903 // conservative answer.
3904 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3905 RHSKnown.countMinLeadingZeros();
3906 // First handle the easy case: if we have enough zero bits there's
3907 // definitely no overflow.
3908 if (ZeroBits >= BitWidth)
3909 return OverflowResult::NeverOverflows;
3910
3911 // Get the largest possible values for each operand.
3912 APInt LHSMax = ~LHSKnown.Zero;
3913 APInt RHSMax = ~RHSKnown.Zero;
3914
3915 // We know the multiply operation doesn't overflow if the maximum values for
3916 // each operand will not overflow after we multiply them together.
3917 bool MaxOverflow;
3918 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
3919 if (!MaxOverflow)
3920 return OverflowResult::NeverOverflows;
3921
3922 // We know it always overflows if multiplying the smallest possible values for
3923 // the operands also results in overflow.
3924 bool MinOverflow;
3925 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
3926 if (MinOverflow)
3927 return OverflowResult::AlwaysOverflows;
3928
3929 return OverflowResult::MayOverflow;
3930}
3931
3932OverflowResult
3933llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
3934 const DataLayout &DL, AssumptionCache *AC,
3935 const Instruction *CxtI,
3936 const DominatorTree *DT, bool UseInstrInfo) {
3937 // Multiplying n * m significant bits yields a result of n + m significant
3938 // bits. If the total number of significant bits does not exceed the
3939 // result bit width (minus 1), there is no overflow.
3940 // This means if we have enough leading sign bits in the operands
3941 // we can guarantee that the result does not overflow.
3942 // Ref: "Hacker's Delight" by Henry Warren
3943 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3944
3945 // Note that underestimating the number of sign bits gives a more
3946 // conservative answer.
3947 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
3948 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
3949
3950 // First handle the easy case: if we have enough sign bits there's
3951 // definitely no overflow.
3952 if (SignBits > BitWidth + 1)
3953 return OverflowResult::NeverOverflows;
3954
3955 // There are two ambiguous cases where there can be no overflow:
3956 // SignBits == BitWidth + 1 and
3957 // SignBits == BitWidth
3958 // The second case is difficult to check, therefore we only handle the
3959 // first case.
3960 if (SignBits == BitWidth + 1) {
3961 // It overflows only when both arguments are negative and the true
3962 // product is exactly the minimum negative number.
3963 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
3964 // For simplicity we just check if at least one side is not negative.
3965 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3966 nullptr, UseInstrInfo);
3967 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
3968 nullptr, UseInstrInfo);
3969 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
3970 return OverflowResult::NeverOverflows;
3971 }
3972 return OverflowResult::MayOverflow;
3973}
3974
3975OverflowResult llvm::computeOverflowForUnsignedAdd(
3976 const Value *LHS, const Value *RHS, const DataLayout &DL,
3977 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3978 bool UseInstrInfo) {
3979 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3980 nullptr, UseInstrInfo);
3981 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3982 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
3983 nullptr, UseInstrInfo);
3984
3985 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
3986 // The sign bit is set in both cases: this MUST overflow.
3987 // Create a simple add instruction, and insert it into the struct.
3988 return OverflowResult::AlwaysOverflows;
3989 }
3990
3991 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
3992 // The sign bit is clear in both cases: this CANNOT overflow.
3993 // Create a simple add instruction, and insert it into the struct.
3994 return OverflowResult::NeverOverflows;
3995 }
3996 }
3997
3998 return OverflowResult::MayOverflow;
3999}
4000
4001/// Return true if we can prove that adding the two values of the
4002/// knownbits will not overflow.
4003/// Otherwise return false.
4004static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
4005 const KnownBits &RHSKnown) {
4006 // Addition of two 2's complement numbers having opposite signs will never
4007 // overflow.
4008 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
4009 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
4010 return true;
4011
4012 // If either of the values is known to be non-negative, adding them can only
4013 // overflow if the second is also non-negative, so we can assume that.
4014 // Two non-negative numbers will only overflow if there is a carry to the
4015 // sign bit, so we can check if even when the values are as big as possible
4016 // there is no overflow to the sign bit.
4017 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
4018 APInt MaxLHS = ~LHSKnown.Zero;
4019 MaxLHS.clearSignBit();
4020 APInt MaxRHS = ~RHSKnown.Zero;
4021 MaxRHS.clearSignBit();
4022 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
4023 return Result.isSignBitClear();
4024 }
4025
4026 // If either of the values is known to be negative, adding them can only
4027 // overflow if the second is also negative, so we can assume that.
4028 // Two negative number will only overflow if there is no carry to the sign
4029 // bit, so we can check if even when the values are as small as possible
4030 // there is overflow to the sign bit.
4031 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
4032 APInt MinLHS = LHSKnown.One;
4033 MinLHS.clearSignBit();
4034 APInt MinRHS = RHSKnown.One;
4035 MinRHS.clearSignBit();
4036 APInt Result = std::move(MinLHS) + std::move(MinRHS);
4037 return Result.isSignBitSet();
4038 }
4039
4040 // If we reached here it means that we know nothing about the sign bits.
4041 // In this case we can't know if there will be an overflow, since by
4042 // changing the sign bits any two values can be made to overflow.
4043 return false;
4044}
4045
4046static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4047 const Value *RHS,
4048 const AddOperator *Add,
4049 const DataLayout &DL,
4050 AssumptionCache *AC,
4051 const Instruction *CxtI,
4052 const DominatorTree *DT) {
4053 if (Add && Add->hasNoSignedWrap()) {
4054 return OverflowResult::NeverOverflows;
4055 }
4056
4057 // If LHS and RHS each have at least two sign bits, the addition will look
4058 // like
4059 //
4060 // XX..... +
4061 // YY.....
4062 //
4063 // If the carry into the most significant position is 0, X and Y can't both
4064 // be 1 and therefore the carry out of the addition is also 0.
4065 //
4066 // If the carry into the most significant position is 1, X and Y can't both
4067 // be 0 and therefore the carry out of the addition is also 1.
4068 //
4069 // Since the carry into the most significant position is always equal to
4070 // the carry out of the addition, there is no signed overflow.
4071 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4072 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4073 return OverflowResult::NeverOverflows;
4074
4075 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
4076 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
4077
4078 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
4079 return OverflowResult::NeverOverflows;
4080
4081 // The remaining code needs Add to be available. Early returns if not so.
4082 if (!Add)
4083 return OverflowResult::MayOverflow;
4084
4085 // If the sign of Add is the same as at least one of the operands, this add
4086 // CANNOT overflow. This is particularly useful when the sum is
4087 // @llvm.assume'ed non-negative rather than proved so from analyzing its
4088 // operands.
4089 bool LHSOrRHSKnownNonNegative =
4090 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
4091 bool LHSOrRHSKnownNegative =
4092 (LHSKnown.isNegative() || RHSKnown.isNegative());
4093 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4094 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
4095 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4096 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
4097 return OverflowResult::NeverOverflows;
4098 }
4099 }
4100
4101 return OverflowResult::MayOverflow;
4102}
4103
4104OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4105 const Value *RHS,
4106 const DataLayout &DL,
4107 AssumptionCache *AC,
4108 const Instruction *CxtI,
4109 const DominatorTree *DT) {
4110 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
4111 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
4112 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
4113 if (LHSKnown.isNegative() && RHSKnown.isNonNegative())
4114 return OverflowResult::NeverOverflows;
4115
4116 return OverflowResult::MayOverflow;
4117}
4118
4119OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4120 const Value *RHS,
4121 const DataLayout &DL,
4122 AssumptionCache *AC,
4123 const Instruction *CxtI,
4124 const DominatorTree *DT) {
4125 // If LHS and RHS each have at least two sign bits, the subtraction
4126 // cannot overflow.
4127 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4128 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4129 return OverflowResult::NeverOverflows;
4130
4131 KnownBits LHSKnown = computeKnownBits(LHS, DL, 0, AC, CxtI, DT);
4132
4133 KnownBits RHSKnown = computeKnownBits(RHS, DL, 0, AC, CxtI, DT);
4134
4135 // Subtraction of two 2's complement numbers having identical signs will
4136 // never overflow.
4137 if ((LHSKnown.isNegative() && RHSKnown.isNegative()) ||
4138 (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()))
4139 return OverflowResult::NeverOverflows;
4140
4141 // TODO: implement logic similar to checkRippleForAdd
4142 return OverflowResult::MayOverflow;
4143}
4144
4145bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
4146 const DominatorTree &DT) {
4147#ifndef NDEBUG
4148 auto IID = II->getIntrinsicID();
4149 assert((IID == Intrinsic::sadd_with_overflow ||(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4150 IID == Intrinsic::uadd_with_overflow ||(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4151 IID == Intrinsic::ssub_with_overflow ||(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4152 IID == Intrinsic::usub_with_overflow ||(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4153 IID == Intrinsic::smul_with_overflow ||(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4154 IID == Intrinsic::umul_with_overflow) &&(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
4155 "Not an overflow intrinsic!")(((IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::
uadd_with_overflow || IID == Intrinsic::ssub_with_overflow ||
IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow
|| IID == Intrinsic::umul_with_overflow) && "Not an overflow intrinsic!"
) ? static_cast<void> (0) : __assert_fail ("(IID == Intrinsic::sadd_with_overflow || IID == Intrinsic::uadd_with_overflow || IID == Intrinsic::ssub_with_overflow || IID == Intrinsic::usub_with_overflow || IID == Intrinsic::smul_with_overflow || IID == Intrinsic::umul_with_overflow) && \"Not an overflow intrinsic!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4155, __PRETTY_FUNCTION__))
;
4156#endif
4157
4158 SmallVector<const BranchInst *, 2> GuardingBranches;
4159 SmallVector<const ExtractValueInst *, 2> Results;
4160
4161 for (const User *U : II->users()) {
4162 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4163 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type")((EVI->getNumIndices() == 1 && "Obvious from CI's type"
) ? static_cast<void> (0) : __assert_fail ("EVI->getNumIndices() == 1 && \"Obvious from CI's type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4163, __PRETTY_FUNCTION__))
;
4164
4165 if (EVI->getIndices()[0] == 0)
4166 Results.push_back(EVI);
4167 else {
4168 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type")((EVI->getIndices()[0] == 1 && "Obvious from CI's type"
) ? static_cast<void> (0) : __assert_fail ("EVI->getIndices()[0] == 1 && \"Obvious from CI's type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4168, __PRETTY_FUNCTION__))
;
4169
4170 for (const auto *U : EVI->users())
4171 if (const auto *B = dyn_cast<BranchInst>(U)) {
4172 assert(B->isConditional() && "How else is it using an i1?")((B->isConditional() && "How else is it using an i1?"
) ? static_cast<void> (0) : __assert_fail ("B->isConditional() && \"How else is it using an i1?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4172, __PRETTY_FUNCTION__))
;
4173 GuardingBranches.push_back(B);
4174 }
4175 }
4176 } else {
4177 // We are using the aggregate directly in a way we don't want to analyze
4178 // here (storing it to a global, say).
4179 return false;
4180 }
4181 }
4182
4183 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
4184 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4185 if (!NoWrapEdge.isSingleEdge())
4186 return false;
4187
4188 // Check if all users of the add are provably no-wrap.
4189 for (const auto *Result : Results) {
4190 // If the extractvalue itself is not executed on overflow, the we don't
4191 // need to check each use separately, since domination is transitive.
4192 if (DT.dominates(NoWrapEdge, Result->getParent()))
4193 continue;
4194
4195 for (auto &RU : Result->uses())
4196 if (!DT.dominates(NoWrapEdge, RU))
4197 return false;
4198 }
4199
4200 return true;
4201 };
4202
4203 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
4204}
4205
4206
4207OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
4208 const DataLayout &DL,
4209 AssumptionCache *AC,
4210 const Instruction *CxtI,
4211 const DominatorTree *DT) {
4212 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
4213 Add, DL, AC, CxtI, DT);
4214}
4215
4216OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4217 const Value *RHS,
4218 const DataLayout &DL,
4219 AssumptionCache *AC,
4220 const Instruction *CxtI,
4221 const DominatorTree *DT) {
4222 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
4223}
4224
4225bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
4226 // A memory operation returns normally if it isn't volatile. A volatile
4227 // operation is allowed to trap.
4228 //
4229 // An atomic operation isn't guaranteed to return in a reasonable amount of
4230 // time because it's possible for another thread to interfere with it for an
4231 // arbitrary length of time, but programs aren't allowed to rely on that.
4232 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4233 return !LI->isVolatile();
4234 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4235 return !SI->isVolatile();
4236 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4237 return !CXI->isVolatile();
4238 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4239 return !RMWI->isVolatile();
4240 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4241 return !MII->isVolatile();
4242
4243 // If there is no successor, then execution can't transfer to it.
4244 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4245 return !CRI->unwindsToCaller();
4246 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4247 return !CatchSwitch->unwindsToCaller();
4248 if (isa<ResumeInst>(I))
4249 return false;
4250 if (isa<ReturnInst>(I))
4251 return false;
4252 if (isa<UnreachableInst>(I))
4253 return false;
4254
4255 // Calls can throw, or contain an infinite loop, or kill the process.
4256 if (auto CS = ImmutableCallSite(I)) {
4257 // Call sites that throw have implicit non-local control flow.
4258 if (!CS.doesNotThrow())
4259 return false;
4260
4261 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4262 // etc. and thus not return. However, LLVM already assumes that
4263 //
4264 // - Thread exiting actions are modeled as writes to memory invisible to
4265 // the program.
4266 //
4267 // - Loops that don't have side effects (side effects are volatile/atomic
4268 // stores and IO) always terminate (see http://llvm.org/PR965).
4269 // Furthermore IO itself is also modeled as writes to memory invisible to
4270 // the program.
4271 //
4272 // We rely on those assumptions here, and use the memory effects of the call
4273 // target as a proxy for checking that it always returns.
4274
4275 // FIXME: This isn't aggressive enough; a call which only writes to a global
4276 // is guaranteed to return.
4277 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
4278 match(I, m_Intrinsic<Intrinsic::assume>()) ||
4279 match(I, m_Intrinsic<Intrinsic::sideeffect>());
4280 }
4281
4282 // Other instructions return normally.
4283 return true;
4284}
4285
4286bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
4287 // TODO: This is slightly consdervative for invoke instruction since exiting
4288 // via an exception *is* normal control for them.
4289 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4290 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4291 return false;
4292 return true;
4293}
4294
4295bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4296 const Loop *L) {
4297 // The loop header is guaranteed to be executed for every iteration.
4298 //
4299 // FIXME: Relax this constraint to cover all basic blocks that are
4300 // guaranteed to be executed at every iteration.
4301 if (I->getParent() != L->getHeader()) return false;
4302
4303 for (const Instruction &LI : *L->getHeader()) {
4304 if (&LI == I) return true;
4305 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4306 }
4307 llvm_unreachable("Instruction not contained in its own parent basic block.")::llvm::llvm_unreachable_internal("Instruction not contained in its own parent basic block."
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4307)
;
4308}
4309
4310bool llvm::propagatesFullPoison(const Instruction *I) {
4311 switch (I->getOpcode()) {
4312 case Instruction::Add:
4313 case Instruction::Sub:
4314 case Instruction::Xor:
4315 case Instruction::Trunc:
4316 case Instruction::BitCast:
4317 case Instruction::AddrSpaceCast:
4318 case Instruction::Mul:
4319 case Instruction::Shl:
4320 case Instruction::GetElementPtr:
4321 // These operations all propagate poison unconditionally. Note that poison
4322 // is not any particular value, so xor or subtraction of poison with
4323 // itself still yields poison, not zero.
4324 return true;
4325
4326 case Instruction::AShr:
4327 case Instruction::SExt:
4328 // For these operations, one bit of the input is replicated across
4329 // multiple output bits. A replicated poison bit is still poison.
4330 return true;
4331
4332 case Instruction::ICmp:
4333 // Comparing poison with any value yields poison. This is why, for
4334 // instance, x s< (x +nsw 1) can be folded to true.
4335 return true;
4336
4337 default:
4338 return false;
4339 }
4340}
4341
4342const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4343 switch (I->getOpcode()) {
4344 case Instruction::Store:
4345 return cast<StoreInst>(I)->getPointerOperand();
4346
4347 case Instruction::Load:
4348 return cast<LoadInst>(I)->getPointerOperand();
4349
4350 case Instruction::AtomicCmpXchg:
4351 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4352
4353 case Instruction::AtomicRMW:
4354 return cast<AtomicRMWInst>(I)->getPointerOperand();
4355
4356 case Instruction::UDiv:
4357 case Instruction::SDiv:
4358 case Instruction::URem:
4359 case Instruction::SRem:
4360 return I->getOperand(1);
4361
4362 default:
4363 return nullptr;
4364 }
4365}
4366
4367bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
4368 // We currently only look for uses of poison values within the same basic
4369 // block, as that makes it easier to guarantee that the uses will be
4370 // executed given that PoisonI is executed.
4371 //
4372 // FIXME: Expand this to consider uses beyond the same basic block. To do
4373 // this, look out for the distinction between post-dominance and strong
4374 // post-dominance.
4375 const BasicBlock *BB = PoisonI->getParent();
4376
4377 // Set of instructions that we have proved will yield poison if PoisonI
4378 // does.
4379 SmallSet<const Value *, 16> YieldsPoison;
4380 SmallSet<const BasicBlock *, 4> Visited;
4381 YieldsPoison.insert(PoisonI);
4382 Visited.insert(PoisonI->getParent());
4383
4384 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
4385
4386 unsigned Iter = 0;
4387 while (Iter++ < MaxDepth) {
4388 for (auto &I : make_range(Begin, End)) {
4389 if (&I != PoisonI) {
4390 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4391 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4392 return true;
4393 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4394 return false;
4395 }
4396
4397 // Mark poison that propagates from I through uses of I.
4398 if (YieldsPoison.count(&I)) {
4399 for (const User *User : I.users()) {
4400 const Instruction *UserI = cast<Instruction>(User);
4401 if (propagatesFullPoison(UserI))
4402 YieldsPoison.insert(User);
4403 }
4404 }
4405 }
4406
4407 if (auto *NextBB = BB->getSingleSuccessor()) {
4408 if (Visited.insert(NextBB).second) {
4409 BB = NextBB;
4410 Begin = BB->getFirstNonPHI()->getIterator();
4411 End = BB->end();
4412 continue;
4413 }
4414 }
4415
4416 break;
4417 }
4418 return false;
4419}
4420
4421static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
4422 if (FMF.noNaNs())
4423 return true;
4424
4425 if (auto *C = dyn_cast<ConstantFP>(V))
4426 return !C->isNaN();
4427
4428 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4429 if (!C->getElementType()->isFloatingPointTy())
4430 return false;
4431 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4432 if (C->getElementAsAPFloat(I).isNaN())
4433 return false;
4434 }
4435 return true;
4436 }
4437
4438 return false;
4439}
4440
4441static bool isKnownNonZero(const Value *V) {
4442 if (auto *C = dyn_cast<ConstantFP>(V))
4443 return !C->isZero();
4444
4445 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4446 if (!C->getElementType()->isFloatingPointTy())
4447 return false;
4448 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4449 if (C->getElementAsAPFloat(I).isZero())
4450 return false;
4451 }
4452 return true;
4453 }
4454
4455 return false;
4456}
4457
4458/// Match clamp pattern for float types without care about NaNs or signed zeros.
4459/// Given non-min/max outer cmp/select from the clamp pattern this
4460/// function recognizes if it can be substitued by a "canonical" min/max
4461/// pattern.
4462static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4463 Value *CmpLHS, Value *CmpRHS,
4464 Value *TrueVal, Value *FalseVal,
4465 Value *&LHS, Value *&RHS) {
4466 // Try to match
4467 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4468 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4469 // and return description of the outer Max/Min.
4470
4471 // First, check if select has inverse order:
4472 if (CmpRHS == FalseVal) {
1
Assuming 'CmpRHS' is not equal to 'FalseVal'
2
Taking false branch
4473 std::swap(TrueVal, FalseVal);
4474 Pred = CmpInst::getInversePredicate(Pred);
4475 }
4476
4477 // Assume success now. If there's no match, callers should not use these anyway.
4478 LHS = TrueVal;
4479 RHS = FalseVal;
4480
4481 const APFloat *FC1;
4482 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
3
Assuming 'CmpRHS' is equal to 'TrueVal'
4
Taking false branch
4483 return {SPF_UNKNOWN, SPNB_NA, false};
4484
4485 const APFloat *FC2;
4486 switch (Pred) {
5
Control jumps to 'case FCMP_UGE:' at line 4500
4487 case CmpInst::FCMP_OLT:
4488 case CmpInst::FCMP_OLE:
4489 case CmpInst::FCMP_ULT:
4490 case CmpInst::FCMP_ULE:
4491 if (match(FalseVal,
4492 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4493 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4494 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4495 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4496 break;
4497 case CmpInst::FCMP_OGT:
4498 case CmpInst::FCMP_OGE:
4499 case CmpInst::FCMP_UGT:
4500 case CmpInst::FCMP_UGE:
4501 if (match(FalseVal,
6
Calling 'match<llvm::Value, llvm::PatternMatch::match_combine_or<llvm::PatternMatch::MaxMin_match<llvm::FCmpInst, llvm::PatternMatch::specificval_ty, llvm::PatternMatch::apfloat_match, llvm::PatternMatch::ofmax_pred_ty, false>, llvm::PatternMatch::MaxMin_match<llvm::FCmpInst, llvm::PatternMatch::specificval_ty, llvm::PatternMatch::apfloat_match, llvm::PatternMatch::ufmax_pred_ty, false> >>'
4502 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4503 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4504 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4505 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4506 break;
4507 default:
4508 break;
4509 }
4510
4511 return {SPF_UNKNOWN, SPNB_NA, false};
4512}
4513
4514/// Recognize variations of:
4515/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4516static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4517 Value *CmpLHS, Value *CmpRHS,
4518 Value *TrueVal, Value *FalseVal) {
4519 // Swap the select operands and predicate to match the patterns below.
4520 if (CmpRHS != TrueVal) {
4521 Pred = ICmpInst::getSwappedPredicate(Pred);
4522 std::swap(TrueVal, FalseVal);
4523 }
4524 const APInt *C1;
4525 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4526 const APInt *C2;
4527 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4528 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4529 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
4530 return {SPF_SMAX, SPNB_NA, false};
4531
4532 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4533 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4534 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
4535 return {SPF_SMIN, SPNB_NA, false};
4536
4537 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4538 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4539 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
4540 return {SPF_UMAX, SPNB_NA, false};
4541
4542 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4543 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4544 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
4545 return {SPF_UMIN, SPNB_NA, false};
4546 }
4547 return {SPF_UNKNOWN, SPNB_NA, false};
4548}
4549
4550/// Recognize variations of:
4551/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4552static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4553 Value *CmpLHS, Value *CmpRHS,
4554 Value *TVal, Value *FVal,
4555 unsigned Depth) {
4556 // TODO: Allow FP min/max with nnan/nsz.
4557 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison")((CmpInst::isIntPredicate(Pred) && "Expected integer comparison"
) ? static_cast<void> (0) : __assert_fail ("CmpInst::isIntPredicate(Pred) && \"Expected integer comparison\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4557, __PRETTY_FUNCTION__))
;
4558
4559 Value *A, *B;
4560 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
4561 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4562 return {SPF_UNKNOWN, SPNB_NA, false};
4563
4564 Value *C, *D;
4565 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
4566 if (L.Flavor != R.Flavor)
4567 return {SPF_UNKNOWN, SPNB_NA, false};
4568
4569 // We have something like: x Pred y ? min(a, b) : min(c, d).
4570 // Try to match the compare to the min/max operations of the select operands.
4571 // First, make sure we have the right compare predicate.
4572 switch (L.Flavor) {
4573 case SPF_SMIN:
4574 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4575 Pred = ICmpInst::getSwappedPredicate(Pred);
4576 std::swap(CmpLHS, CmpRHS);
4577 }
4578 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4579 break;
4580 return {SPF_UNKNOWN, SPNB_NA, false};
4581 case SPF_SMAX:
4582 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4583 Pred = ICmpInst::getSwappedPredicate(Pred);
4584 std::swap(CmpLHS, CmpRHS);
4585 }
4586 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4587 break;
4588 return {SPF_UNKNOWN, SPNB_NA, false};
4589 case SPF_UMIN:
4590 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4591 Pred = ICmpInst::getSwappedPredicate(Pred);
4592 std::swap(CmpLHS, CmpRHS);
4593 }
4594 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4595 break;
4596 return {SPF_UNKNOWN, SPNB_NA, false};
4597 case SPF_UMAX:
4598 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4599 Pred = ICmpInst::getSwappedPredicate(Pred);
4600 std::swap(CmpLHS, CmpRHS);
4601 }
4602 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4603 break;
4604 return {SPF_UNKNOWN, SPNB_NA, false};
4605 default:
4606 return {SPF_UNKNOWN, SPNB_NA, false};
4607 }
4608
4609 // If there is a common operand in the already matched min/max and the other
4610 // min/max operands match the compare operands (either directly or inverted),
4611 // then this is min/max of the same flavor.
4612
4613 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4614 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4615 if (D == B) {
4616 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4617 match(A, m_Not(m_Specific(CmpRHS)))))
4618 return {L.Flavor, SPNB_NA, false};
4619 }
4620 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4621 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4622 if (C == B) {
4623 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4624 match(A, m_Not(m_Specific(CmpRHS)))))
4625 return {L.Flavor, SPNB_NA, false};
4626 }
4627 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4628 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4629 if (D == A) {
4630 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4631 match(B, m_Not(m_Specific(CmpRHS)))))
4632 return {L.Flavor, SPNB_NA, false};
4633 }
4634 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4635 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4636 if (C == A) {
4637 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4638 match(B, m_Not(m_Specific(CmpRHS)))))
4639 return {L.Flavor, SPNB_NA, false};
4640 }
4641
4642 return {SPF_UNKNOWN, SPNB_NA, false};
4643}
4644
4645/// Match non-obvious integer minimum and maximum sequences.
4646static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4647 Value *CmpLHS, Value *CmpRHS,
4648 Value *TrueVal, Value *FalseVal,
4649 Value *&LHS, Value *&RHS,
4650 unsigned Depth) {
4651 // Assume success. If there's no match, callers should not use these anyway.
4652 LHS = TrueVal;
4653 RHS = FalseVal;
4654
4655 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4656 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4657 return SPR;
4658
4659 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
4660 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4661 return SPR;
4662
4663 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
4664 return {SPF_UNKNOWN, SPNB_NA, false};
4665
4666 // Z = X -nsw Y
4667 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4668 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4669 if (match(TrueVal, m_Zero()) &&
4670 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4671 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4672
4673 // Z = X -nsw Y
4674 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4675 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4676 if (match(FalseVal, m_Zero()) &&
4677 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4678 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4679
4680 const APInt *C1;
4681 if (!match(CmpRHS, m_APInt(C1)))
4682 return {SPF_UNKNOWN, SPNB_NA, false};
4683
4684 // An unsigned min/max can be written with a signed compare.
4685 const APInt *C2;
4686 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4687 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4688 // Is the sign bit set?
4689 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4690 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
4691 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4692 C2->isMaxSignedValue())
4693 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4694
4695 // Is the sign bit clear?
4696 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4697 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4698 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4699 C2->isMinSignedValue())
4700 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4701 }
4702
4703 // Look through 'not' ops to find disguised signed min/max.
4704 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4705 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4706 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
4707 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
4708 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4709
4710 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4711 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4712 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
4713 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
4714 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4715
4716 return {SPF_UNKNOWN, SPNB_NA, false};
4717}
4718
4719bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
4720 assert(X && Y && "Invalid operand")((X && Y && "Invalid operand") ? static_cast<
void> (0) : __assert_fail ("X && Y && \"Invalid operand\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 4720, __PRETTY_FUNCTION__))
;
4721
4722 // X = sub (0, Y) || X = sub nsw (0, Y)
4723 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4724 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
4725 return true;
4726
4727 // Y = sub (0, X) || Y = sub nsw (0, X)
4728 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4729 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
4730 return true;
4731
4732 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
4733 Value *A, *B;
4734 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4735 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4736 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4737 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
4738}
4739
4740static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4741 FastMathFlags FMF,
4742 Value *CmpLHS, Value *CmpRHS,
4743 Value *TrueVal, Value *FalseVal,
4744 Value *&LHS, Value *&RHS,
4745 unsigned Depth) {
4746 LHS = CmpLHS;
4747 RHS = CmpRHS;
4748
4749 // Signed zero may return inconsistent results between implementations.
4750 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4751 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4752 // Therefore, we behave conservatively and only proceed if at least one of the
4753 // operands is known to not be zero or if we don't care about signed zero.
4754 switch (Pred) {
4755 default: break;
4756 // FIXME: Include OGT/OLT/UGT/ULT.
4757 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4758 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4759 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4760 !isKnownNonZero(CmpRHS))
4761 return {SPF_UNKNOWN, SPNB_NA, false};
4762 }
4763
4764 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4765 bool Ordered = false;
4766
4767 // When given one NaN and one non-NaN input:
4768 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4769 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4770 // ordered comparison fails), which could be NaN or non-NaN.
4771 // so here we discover exactly what NaN behavior is required/accepted.
4772 if (CmpInst::isFPPredicate(Pred)) {
4773 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4774 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4775
4776 if (LHSSafe && RHSSafe) {
4777 // Both operands are known non-NaN.
4778 NaNBehavior = SPNB_RETURNS_ANY;
4779 } else if (CmpInst::isOrdered(Pred)) {
4780 // An ordered comparison will return false when given a NaN, so it
4781 // returns the RHS.
4782 Ordered = true;
4783 if (LHSSafe)
4784 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
4785 NaNBehavior = SPNB_RETURNS_NAN;
4786 else if (RHSSafe)
4787 NaNBehavior = SPNB_RETURNS_OTHER;
4788 else
4789 // Completely unsafe.
4790 return {SPF_UNKNOWN, SPNB_NA, false};
4791 } else {
4792 Ordered = false;
4793 // An unordered comparison will return true when given a NaN, so it
4794 // returns the LHS.
4795 if (LHSSafe)
4796 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
4797 NaNBehavior = SPNB_RETURNS_OTHER;
4798 else if (RHSSafe)
4799 NaNBehavior = SPNB_RETURNS_NAN;
4800 else
4801 // Completely unsafe.
4802 return {SPF_UNKNOWN, SPNB_NA, false};
4803 }
4804 }
4805
4806 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
4807 std::swap(CmpLHS, CmpRHS);
4808 Pred = CmpInst::getSwappedPredicate(Pred);
4809 if (NaNBehavior == SPNB_RETURNS_NAN)
4810 NaNBehavior = SPNB_RETURNS_OTHER;
4811 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4812 NaNBehavior = SPNB_RETURNS_NAN;
4813 Ordered = !Ordered;
4814 }
4815
4816 // ([if]cmp X, Y) ? X : Y
4817 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
4818 switch (Pred) {
4819 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
4820 case ICmpInst::ICMP_UGT:
4821 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
4822 case ICmpInst::ICMP_SGT:
4823 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
4824 case ICmpInst::ICMP_ULT:
4825 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
4826 case ICmpInst::ICMP_SLT:
4827 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4828 case FCmpInst::FCMP_UGT:
4829 case FCmpInst::FCMP_UGE:
4830 case FCmpInst::FCMP_OGT:
4831 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4832 case FCmpInst::FCMP_ULT:
4833 case FCmpInst::FCMP_ULE:
4834 case FCmpInst::FCMP_OLT:
4835 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
4836 }
4837 }
4838
4839 if (isKnownNegation(TrueVal, FalseVal)) {
4840 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4841 // match against either LHS or sext(LHS).
4842 auto MaybeSExtCmpLHS =
4843 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4844 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4845 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4846 if (match(TrueVal, MaybeSExtCmpLHS)) {
4847 // Set the return values. If the compare uses the negated value (-X >s 0),
4848 // swap the return values because the negated value is always 'RHS'.
4849 LHS = TrueVal;
4850 RHS = FalseVal;
4851 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4852 std::swap(LHS, RHS);
4853
4854 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4855 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4856 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4857 return {SPF_ABS, SPNB_NA, false};
4858
4859 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4860 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4861 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4862 return {SPF_NABS, SPNB_NA, false};
4863 }
4864 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4865 // Set the return values. If the compare uses the negated value (-X >s 0),
4866 // swap the return values because the negated value is always 'RHS'.
4867 LHS = FalseVal;
4868 RHS = TrueVal;
4869 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4870 std::swap(LHS, RHS);
4871
4872 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4873 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4874 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4875 return {SPF_NABS, SPNB_NA, false};
4876
4877 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4878 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4879 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4880 return {SPF_ABS, SPNB_NA, false};
4881 }
4882 }
4883
4884 if (CmpInst::isIntPredicate(Pred))
4885 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
4886
4887 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4888 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4889 // semantics than minNum. Be conservative in such case.
4890 if (NaNBehavior != SPNB_RETURNS_ANY ||
4891 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4892 !isKnownNonZero(CmpRHS)))
4893 return {SPF_UNKNOWN, SPNB_NA, false};
4894
4895 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4896}
4897
4898/// Helps to match a select pattern in case of a type mismatch.
4899///
4900/// The function processes the case when type of true and false values of a
4901/// select instruction differs from type of the cmp instruction operands because
4902/// of a cast instruction. The function checks if it is legal to move the cast
4903/// operation after "select". If yes, it returns the new second value of
4904/// "select" (with the assumption that cast is moved):
4905/// 1. As operand of cast instruction when both values of "select" are same cast
4906/// instructions.
4907/// 2. As restored constant (by applying reverse cast operation) when the first
4908/// value of the "select" is a cast operation and the second value is a
4909/// constant.
4910/// NOTE: We return only the new second value because the first value could be
4911/// accessed as operand of cast instruction.
4912static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4913 Instruction::CastOps *CastOp) {
4914 auto *Cast1 = dyn_cast<CastInst>(V1);
4915 if (!Cast1)
4916 return nullptr;
4917
4918 *CastOp = Cast1->getOpcode();
4919 Type *SrcTy = Cast1->getSrcTy();
4920 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4921 // If V1 and V2 are both the same cast from the same type, look through V1.
4922 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4923 return Cast2->getOperand(0);
4924 return nullptr;
4925 }
4926
4927 auto *C = dyn_cast<Constant>(V2);
4928 if (!C)
4929 return nullptr;
4930
4931 Constant *CastedTo = nullptr;
4932 switch (*CastOp) {
4933 case Instruction::ZExt:
4934 if (CmpI->isUnsigned())
4935 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4936 break;
4937 case Instruction::SExt:
4938 if (CmpI->isSigned())
4939 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4940 break;
4941 case Instruction::Trunc:
4942 Constant *CmpConst;
4943 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4944 CmpConst->getType() == SrcTy) {
4945 // Here we have the following case:
4946 //
4947 // %cond = cmp iN %x, CmpConst
4948 // %tr = trunc iN %x to iK
4949 // %narrowsel = select i1 %cond, iK %t, iK C
4950 //
4951 // We can always move trunc after select operation:
4952 //
4953 // %cond = cmp iN %x, CmpConst
4954 // %widesel = select i1 %cond, iN %x, iN CmpConst
4955 // %tr = trunc iN %widesel to iK
4956 //
4957 // Note that C could be extended in any way because we don't care about
4958 // upper bits after truncation. It can't be abs pattern, because it would
4959 // look like:
4960 //
4961 // select i1 %cond, x, -x.
4962 //
4963 // So only min/max pattern could be matched. Such match requires widened C
4964 // == CmpConst. That is why set widened C = CmpConst, condition trunc
4965 // CmpConst == C is checked below.
4966 CastedTo = CmpConst;
4967 } else {
4968 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4969 }
4970 break;
4971 case Instruction::FPTrunc:
4972 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4973 break;
4974 case Instruction::FPExt:
4975 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4976 break;
4977 case Instruction::FPToUI:
4978 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4979 break;
4980 case Instruction::FPToSI:
4981 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4982 break;
4983 case Instruction::UIToFP:
4984 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4985 break;
4986 case Instruction::SIToFP:
4987 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4988 break;
4989 default:
4990 break;
4991 }
4992
4993 if (!CastedTo)
4994 return nullptr;
4995
4996 // Make sure the cast doesn't lose any information.
4997 Constant *CastedBack =
4998 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
4999 if (CastedBack != C)
5000 return nullptr;
5001
5002 return CastedTo;
5003}
5004
5005SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
5006 Instruction::CastOps *CastOp,
5007 unsigned Depth) {
5008 if (Depth >= MaxDepth)
5009 return {SPF_UNKNOWN, SPNB_NA, false};
5010
5011 SelectInst *SI = dyn_cast<SelectInst>(V);
5012 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
5013
5014 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5015 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
5016
5017 CmpInst::Predicate Pred = CmpI->getPredicate();
5018 Value *CmpLHS = CmpI->getOperand(0);
5019 Value *CmpRHS = CmpI->getOperand(1);
5020 Value *TrueVal = SI->getTrueValue();
5021 Value *FalseVal = SI->getFalseValue();
5022 FastMathFlags FMF;
5023 if (isa<FPMathOperator>(CmpI))
5024 FMF = CmpI->getFastMathFlags();
5025
5026 // Bail out early.
5027 if (CmpI->isEquality())
5028 return {SPF_UNKNOWN, SPNB_NA, false};
5029
5030 // Deal with type mismatches.
5031 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
5032 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5033 // If this is a potential fmin/fmax with a cast to integer, then ignore
5034 // -0.0 because there is no corresponding integer value.
5035 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5036 FMF.setNoSignedZeros();
5037 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
5038 cast<CastInst>(TrueVal)->getOperand(0), C,
5039 LHS, RHS, Depth);
5040 }
5041 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5042 // If this is a potential fmin/fmax with a cast to integer, then ignore
5043 // -0.0 because there is no corresponding integer value.
5044 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5045 FMF.setNoSignedZeros();
5046 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
5047 C, cast<CastInst>(FalseVal)->getOperand(0),
5048 LHS, RHS, Depth);
5049 }
5050 }
5051 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
5052 LHS, RHS, Depth);
5053}
5054
5055CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5056 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5057 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5058 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5059 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5060 if (SPF == SPF_FMINNUM)
5061 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5062 if (SPF == SPF_FMAXNUM)
5063 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5064 llvm_unreachable("unhandled!")::llvm::llvm_unreachable_internal("unhandled!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5064)
;
5065}
5066
5067SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5068 if (SPF == SPF_SMIN) return SPF_SMAX;
5069 if (SPF == SPF_UMIN) return SPF_UMAX;
5070 if (SPF == SPF_SMAX) return SPF_SMIN;
5071 if (SPF == SPF_UMAX) return SPF_UMIN;
5072 llvm_unreachable("unhandled!")::llvm::llvm_unreachable_internal("unhandled!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5072)
;
5073}
5074
5075CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5076 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5077}
5078
5079/// Return true if "icmp Pred LHS RHS" is always true.
5080static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5081 const Value *RHS, const DataLayout &DL,
5082 unsigned Depth) {
5083 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!")((!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!"
) ? static_cast<void> (0) : __assert_fail ("!LHS->getType()->isVectorTy() && \"TODO: extend to handle vectors!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5083, __PRETTY_FUNCTION__))
;
5084 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5085 return true;
5086
5087 switch (Pred) {
5088 default:
5089 return false;
5090
5091 case CmpInst::ICMP_SLE: {
5092 const APInt *C;
5093
5094 // LHS s<= LHS +_{nsw} C if C >= 0
5095 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
5096 return !C->isNegative();
5097 return false;
5098 }
5099
5100 case CmpInst::ICMP_ULE: {
5101 const APInt *C;
5102
5103 // LHS u<= LHS +_{nuw} C for any C
5104 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
5105 return true;
5106
5107 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
5108 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5109 const Value *&X,
5110 const APInt *&CA, const APInt *&CB) {
5111 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5112 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5113 return true;
5114
5115 // If X & C == 0 then (X | C) == X +_{nuw} C
5116 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5117 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
5118 KnownBits Known(CA->getBitWidth());
5119 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5120 /*CxtI*/ nullptr, /*DT*/ nullptr);
5121 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
5122 return true;
5123 }
5124
5125 return false;
5126 };
5127
5128 const Value *X;
5129 const APInt *CLHS, *CRHS;
5130 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5131 return CLHS->ule(*CRHS);
5132
5133 return false;
5134 }
5135 }
5136}
5137
5138/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
5139/// ALHS ARHS" is true. Otherwise, return None.
5140static Optional<bool>
5141isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
5142 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5143 const DataLayout &DL, unsigned Depth) {
5144 switch (Pred) {
5145 default:
5146 return None;
5147
5148 case CmpInst::ICMP_SLT:
5149 case CmpInst::ICMP_SLE:
5150 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5151 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
5152 return true;
5153 return None;
5154
5155 case CmpInst::ICMP_ULT:
5156 case CmpInst::ICMP_ULE:
5157 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5158 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
5159 return true;
5160 return None;
5161 }
5162}
5163
5164/// Return true if the operands of the two compares match. IsSwappedOps is true
5165/// when the operands match, but are swapped.
5166static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5167 const Value *BLHS, const Value *BRHS,
5168 bool &IsSwappedOps) {
5169
5170 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5171 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5172 return IsMatchingOps || IsSwappedOps;
5173}
5174
5175/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
5176/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
5177/// BRHS" is false. Otherwise, return None if we can't infer anything.
5178static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
5179 const Value *ALHS,
5180 const Value *ARHS,
5181 CmpInst::Predicate BPred,
5182 const Value *BLHS,
5183 const Value *BRHS,
5184 bool IsSwappedOps) {
5185 // Canonicalize the operands so they're matching.
5186 if (IsSwappedOps) {
5187 std::swap(BLHS, BRHS);
5188 BPred = ICmpInst::getSwappedPredicate(BPred);
5189 }
5190 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
5191 return true;
5192 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
5193 return false;
5194
5195 return None;
5196}
5197
5198/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
5199/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
5200/// C2" is false. Otherwise, return None if we can't infer anything.
5201static Optional<bool>
5202isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
5203 const ConstantInt *C1,
5204 CmpInst::Predicate BPred,
5205 const Value *BLHS, const ConstantInt *C2) {
5206 assert(ALHS == BLHS && "LHS operands must match.")((ALHS == BLHS && "LHS operands must match.") ? static_cast
<void> (0) : __assert_fail ("ALHS == BLHS && \"LHS operands must match.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5206, __PRETTY_FUNCTION__))
;
5207 ConstantRange DomCR =
5208 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5209 ConstantRange CR =
5210 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5211 ConstantRange Intersection = DomCR.intersectWith(CR);
5212 ConstantRange Difference = DomCR.difference(CR);
5213 if (Intersection.isEmptySet())
5214 return false;
5215 if (Difference.isEmptySet())
5216 return true;
5217 return None;
5218}
5219
5220/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5221/// false. Otherwise, return None if we can't infer anything.
5222static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5223 const ICmpInst *RHS,
5224 const DataLayout &DL, bool LHSIsTrue,
5225 unsigned Depth) {
5226 Value *ALHS = LHS->getOperand(0);
5227 Value *ARHS = LHS->getOperand(1);
5228 // The rest of the logic assumes the LHS condition is true. If that's not the
5229 // case, invert the predicate to make it so.
5230 ICmpInst::Predicate APred =
5231 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
5232
5233 Value *BLHS = RHS->getOperand(0);
5234 Value *BRHS = RHS->getOperand(1);
5235 ICmpInst::Predicate BPred = RHS->getPredicate();
5236
5237 // Can we infer anything when the two compares have matching operands?
5238 bool IsSwappedOps;
5239 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
5240 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
5241 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
5242 return Implication;
5243 // No amount of additional analysis will infer the second condition, so
5244 // early exit.
5245 return None;
5246 }
5247
5248 // Can we infer anything when the LHS operands match and the RHS operands are
5249 // constants (not necessarily matching)?
5250 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5251 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
5252 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
5253 cast<ConstantInt>(BRHS)))
5254 return Implication;
5255 // No amount of additional analysis will infer the second condition, so
5256 // early exit.
5257 return None;
5258 }
5259
5260 if (APred == BPred)
5261 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
5262 return None;
5263}
5264
5265/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5266/// false. Otherwise, return None if we can't infer anything. We expect the
5267/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5268static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5269 const ICmpInst *RHS,
5270 const DataLayout &DL, bool LHSIsTrue,
5271 unsigned Depth) {
5272 // The LHS must be an 'or' or an 'and' instruction.
5273 assert((LHS->getOpcode() == Instruction::And ||(((LHS->getOpcode() == Instruction::And || LHS->getOpcode
() == Instruction::Or) && "Expected LHS to be 'and' or 'or'."
) ? static_cast<void> (0) : __assert_fail ("(LHS->getOpcode() == Instruction::And || LHS->getOpcode() == Instruction::Or) && \"Expected LHS to be 'and' or 'or'.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5275, __PRETTY_FUNCTION__))
5274 LHS->getOpcode() == Instruction::Or) &&(((LHS->getOpcode() == Instruction::And || LHS->getOpcode
() == Instruction::Or) && "Expected LHS to be 'and' or 'or'."
) ? static_cast<void> (0) : __assert_fail ("(LHS->getOpcode() == Instruction::And || LHS->getOpcode() == Instruction::Or) && \"Expected LHS to be 'and' or 'or'.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5275, __PRETTY_FUNCTION__))
5275 "Expected LHS to be 'and' or 'or'.")(((LHS->getOpcode() == Instruction::And || LHS->getOpcode
() == Instruction::Or) && "Expected LHS to be 'and' or 'or'."
) ? static_cast<void> (0) : __assert_fail ("(LHS->getOpcode() == Instruction::And || LHS->getOpcode() == Instruction::Or) && \"Expected LHS to be 'and' or 'or'.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5275, __PRETTY_FUNCTION__))
;
5276
5277 assert(Depth <= MaxDepth && "Hit recursion limit")((Depth <= MaxDepth && "Hit recursion limit") ? static_cast
<void> (0) : __assert_fail ("Depth <= MaxDepth && \"Hit recursion limit\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5277, __PRETTY_FUNCTION__))
;
5278
5279 // If the result of an 'or' is false, then we know both legs of the 'or' are
5280 // false. Similarly, if the result of an 'and' is true, then we know both
5281 // legs of the 'and' are true.
5282 Value *ALHS, *ARHS;
5283 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5284 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
5285 // FIXME: Make this non-recursion.
5286 if (Optional<bool> Implication =
5287 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
5288 return Implication;
5289 if (Optional<bool> Implication =
5290 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
5291 return Implication;
5292 return None;
5293 }
5294 return None;
5295}
5296
5297Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
5298 const DataLayout &DL, bool LHSIsTrue,
5299 unsigned Depth) {
5300 // Bail out when we hit the limit.
5301 if (Depth == MaxDepth)
5302 return None;
5303
5304 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5305 // example.
5306 if (LHS->getType() != RHS->getType())
5307 return None;
5308
5309 Type *OpTy = LHS->getType();
5310 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!")((OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!"
) ? static_cast<void> (0) : __assert_fail ("OpTy->isIntOrIntVectorTy(1) && \"Expected integer type only!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5310, __PRETTY_FUNCTION__))
;
5311
5312 // LHS ==> RHS by definition
5313 if (LHS == RHS)
5314 return LHSIsTrue;
5315
5316 // FIXME: Extending the code below to handle vectors.
5317 if (OpTy->isVectorTy())
5318 return None;
5319
5320 assert(OpTy->isIntegerTy(1) && "implied by above")((OpTy->isIntegerTy(1) && "implied by above") ? static_cast
<void> (0) : __assert_fail ("OpTy->isIntegerTy(1) && \"implied by above\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ValueTracking.cpp"
, 5320, __PRETTY_FUNCTION__))
;
5321
5322 // Both LHS and RHS are icmps.
5323 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5324 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5325 if (LHSCmp && RHSCmp)
5326 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
5327
5328 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5329 // an icmp. FIXME: Add support for and/or on the RHS.
5330 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5331 if (LHSBO && RHSCmp) {
5332 if ((LHSBO->getOpcode() == Instruction::And ||
5333 LHSBO->getOpcode() == Instruction::Or))
5334 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
5335 }
5336 return None;
5337}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/PatternMatch.h

1//===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides a simple and efficient mechanism for performing general
11// tree-based pattern matches on the LLVM IR. The power of these routines is
12// that it allows you to write concise patterns that are expressive and easy to
13// understand. The other major advantage of this is that it allows you to
14// trivially capture/bind elements in the pattern to variables. For example,
15// you can do something like this:
16//
17// Value *Exp = ...
18// Value *X, *Y; ConstantInt *C1, *C2; // (X & C1) | (Y & C2)
19// if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
20// m_And(m_Value(Y), m_ConstantInt(C2))))) {
21// ... Pattern is matched and variables are bound ...
22// }
23//
24// This is primarily useful to things like the instruction combiner, but can
25// also be useful for static analysis tools or code generators.
26//
27//===----------------------------------------------------------------------===//
28
29#ifndef LLVM_IR_PATTERNMATCH_H
30#define LLVM_IR_PATTERNMATCH_H
31
32#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/Operator.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
44#include <cstdint>
45
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);
7
Calling 'match_combine_or::match'
51}
52
53template <typename SubPattern_t> struct OneUse_match {
54 SubPattern_t SubPattern;
55
56 OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
57
58 template <typename OpTy> bool match(OpTy *V) {
59 return V->hasOneUse() && SubPattern.match(V);
60 }
61};
62
63template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
64 return SubPattern;
65}
66
67template <typename Class> struct class_match {
68 template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
69};
70
71/// Match an arbitrary value and ignore it.
72inline class_match<Value> m_Value() { return class_match<Value>(); }
73
74/// Match an arbitrary binary operation and ignore it.
75inline class_match<BinaryOperator> m_BinOp() {
76 return class_match<BinaryOperator>();
77}
78
79/// Matches any compare instruction and ignore it.
80inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
81
82/// Match an arbitrary ConstantInt and ignore it.
83inline class_match<ConstantInt> m_ConstantInt() {
84 return class_match<ConstantInt>();
85}
86
87/// Match an arbitrary undef constant.
88inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
89
90/// Match an arbitrary Constant and ignore it.
91inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
92
93/// Matching combinators
94template <typename LTy, typename RTy> struct match_combine_or {
95 LTy L;
96 RTy R;
97
98 match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
99
100 template <typename ITy> bool match(ITy *V) {
101 if (L.match(V))
8
Calling 'MaxMin_match::match'
102 return true;
103 if (R.match(V))
104 return true;
105 return false;
106 }
107};
108
109template <typename LTy, typename RTy> struct match_combine_and {
110 LTy L;
111 RTy R;
112
113 match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
114
115 template <typename ITy> bool match(ITy *V) {
116 if (L.match(V))
117 if (R.match(V))
118 return true;
119 return false;
120 }
121};
122
123/// Combine two pattern matchers matching L || R
124template <typename LTy, typename RTy>
125inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
126 return match_combine_or<LTy, RTy>(L, R);
127}
128
129/// Combine two pattern matchers matching L && R
130template <typename LTy, typename RTy>
131inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
132 return match_combine_and<LTy, RTy>(L, R);
133}
134
135struct apint_match {
136 const APInt *&Res;
137
138 apint_match(const APInt *&R) : Res(R) {}
139
140 template <typename ITy> bool match(ITy *V) {
141 if (auto *CI = dyn_cast<ConstantInt>(V)) {
142 Res = &CI->getValue();
143 return true;
144 }
145 if (V->getType()->isVectorTy())
146 if (const auto *C = dyn_cast<Constant>(V))
147 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
148 Res = &CI->getValue();
149 return true;
150 }
151 return false;
152 }
153};
154// Either constexpr if or renaming ConstantFP::getValueAPF to
155// ConstantFP::getValue is needed to do it via single template
156// function for both apint/apfloat.
157struct apfloat_match {
158 const APFloat *&Res;
159 apfloat_match(const APFloat *&R) : Res(R) {}
160 template <typename ITy> bool match(ITy *V) {
161 if (auto *CI = dyn_cast<ConstantFP>(V)) {
30
Taking false branch
162 Res = &CI->getValueAPF();
163 return true;
164 }
165 if (V->getType()->isVectorTy())
31
Called C++ object pointer is null
166 if (const auto *C = dyn_cast<Constant>(V))
167 if (auto *CI = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) {
168 Res = &CI->getValueAPF();
169 return true;
170 }
171 return false;
172 }
173};
174
175/// Match a ConstantInt or splatted ConstantVector, binding the
176/// specified pointer to the contained APInt.
177inline apint_match m_APInt(const APInt *&Res) { return Res; }
178
179/// Match a ConstantFP or splatted ConstantVector, binding the
180/// specified pointer to the contained APFloat.
181inline apfloat_match m_APFloat(const APFloat *&Res) { return Res; }
182
183template <int64_t Val> struct constantint_match {
184 template <typename ITy> bool match(ITy *V) {
185 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
186 const APInt &CIV = CI->getValue();
187 if (Val >= 0)
188 return CIV == static_cast<uint64_t>(Val);
189 // If Val is negative, and CI is shorter than it, truncate to the right
190 // number of bits. If it is larger, then we have to sign extend. Just
191 // compare their negated values.
192 return -CIV == -Val;
193 }
194 return false;
195 }
196};
197
198/// Match a ConstantInt with a specific value.
199template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
200 return constantint_match<Val>();
201}
202
203/// This helper class is used to match scalar and vector integer constants that
204/// satisfy a specified predicate.
205/// For vector constants, undefined elements are ignored.
206template <typename Predicate> struct cst_pred_ty : public Predicate {
207 template <typename ITy> bool match(ITy *V) {
208 if (const auto *CI = dyn_cast<ConstantInt>(V))
209 return this->isValue(CI->getValue());
210 if (V->getType()->isVectorTy()) {
211 if (const auto *C = dyn_cast<Constant>(V)) {
212 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
213 return this->isValue(CI->getValue());
214
215 // Non-splat vector constant: check each element for a match.
216 unsigned NumElts = V->getType()->getVectorNumElements();
217 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-8~svn345461/include/llvm/IR/PatternMatch.h"
, 217, __PRETTY_FUNCTION__))
;
218 for (unsigned i = 0; i != NumElts; ++i) {
219 Constant *Elt = C->getAggregateElement(i);
220 if (!Elt)
221 return false;
222 if (isa<UndefValue>(Elt))
223 continue;
224 auto *CI = dyn_cast<ConstantInt>(Elt);
225 if (!CI || !this->isValue(CI->getValue()))
226 return false;
227 }
228 return true;
229 }
230 }
231 return false;
232 }
233};
234
235/// This helper class is used to match scalar and vector constants that
236/// satisfy a specified predicate, and bind them to an APInt.
237template <typename Predicate> struct api_pred_ty : public Predicate {
238 const APInt *&Res;
239
240 api_pred_ty(const APInt *&R) : Res(R) {}
241
242 template <typename ITy> bool match(ITy *V) {
243 if (const auto *CI = dyn_cast<ConstantInt>(V))
244 if (this->isValue(CI->getValue())) {
245 Res = &CI->getValue();
246 return true;
247 }
248 if (V->getType()->isVectorTy())
249 if (const auto *C = dyn_cast<Constant>(V))
250 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
251 if (this->isValue(CI->getValue())) {
252 Res = &CI->getValue();
253 return true;
254 }
255
256 return false;
257 }
258};
259
260/// This helper class is used to match scalar and vector floating-point
261/// constants that satisfy a specified predicate.
262/// For vector constants, undefined elements are ignored.
263template <typename Predicate> struct cstfp_pred_ty : public Predicate {
264 template <typename ITy> bool match(ITy *V) {
265 if (const auto *CF = dyn_cast<ConstantFP>(V))
266 return this->isValue(CF->getValueAPF());
267 if (V->getType()->isVectorTy()) {
268 if (const auto *C = dyn_cast<Constant>(V)) {
269 if (const auto *CF = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
270 return this->isValue(CF->getValueAPF());
271
272 // Non-splat vector constant: check each element for a match.
273 unsigned NumElts = V->getType()->getVectorNumElements();
274 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-8~svn345461/include/llvm/IR/PatternMatch.h"
, 274, __PRETTY_FUNCTION__))
;
275 for (unsigned i = 0; i != NumElts; ++i) {
276 Constant *Elt = C->getAggregateElement(i);
277 if (!Elt)
278 return false;
279 if (isa<UndefValue>(Elt))
280 continue;
281 auto *CF = dyn_cast<ConstantFP>(Elt);
282 if (!CF || !this->isValue(CF->getValueAPF()))
283 return false;
284 }
285 return true;
286 }
287 }
288 return false;
289 }
290};
291
292///////////////////////////////////////////////////////////////////////////////
293//
294// Encapsulate constant value queries for use in templated predicate matchers.
295// This allows checking if constants match using compound predicates and works
296// with vector constants, possibly with relaxed constraints. For example, ignore
297// undef values.
298//
299///////////////////////////////////////////////////////////////////////////////
300
301struct is_all_ones {
302 bool isValue(const APInt &C) { return C.isAllOnesValue(); }
303};
304/// Match an integer or vector with all bits set.
305/// For vectors, this includes constants with undefined elements.
306inline cst_pred_ty<is_all_ones> m_AllOnes() {
307 return cst_pred_ty<is_all_ones>();
308}
309
310struct is_maxsignedvalue {
311 bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
312};
313/// Match an integer or vector with values having all bits except for the high
314/// bit set (0x7f...).
315/// For vectors, this includes constants with undefined elements.
316inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
317 return cst_pred_ty<is_maxsignedvalue>();
318}
319inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
320 return V;
321}
322
323struct is_negative {
324 bool isValue(const APInt &C) { return C.isNegative(); }
325};
326/// Match an integer or vector of negative values.
327/// For vectors, this includes constants with undefined elements.
328inline cst_pred_ty<is_negative> m_Negative() {
329 return cst_pred_ty<is_negative>();
330}
331inline api_pred_ty<is_negative> m_Negative(const APInt *&V) {
332 return V;
333}
334
335struct is_nonnegative {
336 bool isValue(const APInt &C) { return C.isNonNegative(); }
337};
338/// Match an integer or vector of nonnegative values.
339/// For vectors, this includes constants with undefined elements.
340inline cst_pred_ty<is_nonnegative> m_NonNegative() {
341 return cst_pred_ty<is_nonnegative>();
342}
343inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) {
344 return V;
345}
346
347struct is_one {
348 bool isValue(const APInt &C) { return C.isOneValue(); }
349};
350/// Match an integer 1 or a vector with all elements equal to 1.
351/// For vectors, this includes constants with undefined elements.
352inline cst_pred_ty<is_one> m_One() {
353 return cst_pred_ty<is_one>();
354}
355
356struct is_zero_int {
357 bool isValue(const APInt &C) { return C.isNullValue(); }
358};
359/// Match an integer 0 or a vector with all elements equal to 0.
360/// For vectors, this includes constants with undefined elements.
361inline cst_pred_ty<is_zero_int> m_ZeroInt() {
362 return cst_pred_ty<is_zero_int>();
363}
364
365struct is_zero {
366 template <typename ITy> bool match(ITy *V) {
367 auto *C = dyn_cast<Constant>(V);
368 return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
369 }
370};
371/// Match any null constant or a vector with all elements equal to 0.
372/// For vectors, this includes constants with undefined elements.
373inline is_zero m_Zero() {
374 return is_zero();
375}
376
377struct is_power2 {
378 bool isValue(const APInt &C) { return C.isPowerOf2(); }
379};
380/// Match an integer or vector power-of-2.
381/// For vectors, this includes constants with undefined elements.
382inline cst_pred_ty<is_power2> m_Power2() {
383 return cst_pred_ty<is_power2>();
384}
385inline api_pred_ty<is_power2> m_Power2(const APInt *&V) {
386 return V;
387}
388
389struct is_power2_or_zero {
390 bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
391};
392/// Match an integer or vector of 0 or power-of-2 values.
393/// For vectors, this includes constants with undefined elements.
394inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
395 return cst_pred_ty<is_power2_or_zero>();
396}
397inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
398 return V;
399}
400
401struct is_sign_mask {
402 bool isValue(const APInt &C) { return C.isSignMask(); }
403};
404/// Match an integer or vector with only the sign bit(s) set.
405/// For vectors, this includes constants with undefined elements.
406inline cst_pred_ty<is_sign_mask> m_SignMask() {
407 return cst_pred_ty<is_sign_mask>();
408}
409
410struct is_lowbit_mask {
411 bool isValue(const APInt &C) { return C.isMask(); }
412};
413/// Match an integer or vector with only the low bit(s) set.
414/// For vectors, this includes constants with undefined elements.
415inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
416 return cst_pred_ty<is_lowbit_mask>();
417}
418
419struct is_nan {
420 bool isValue(const APFloat &C) { return C.isNaN(); }
421};
422/// Match an arbitrary NaN constant. This includes quiet and signalling nans.
423/// For vectors, this includes constants with undefined elements.
424inline cstfp_pred_ty<is_nan> m_NaN() {
425 return cstfp_pred_ty<is_nan>();
426}
427
428struct is_any_zero_fp {
429 bool isValue(const APFloat &C) { return C.isZero(); }
430};
431/// Match a floating-point negative zero or positive zero.
432/// For vectors, this includes constants with undefined elements.
433inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
434 return cstfp_pred_ty<is_any_zero_fp>();
435}
436
437struct is_pos_zero_fp {
438 bool isValue(const APFloat &C) { return C.isPosZero(); }
439};
440/// Match a floating-point positive zero.
441/// For vectors, this includes constants with undefined elements.
442inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
443 return cstfp_pred_ty<is_pos_zero_fp>();
444}
445
446struct is_neg_zero_fp {
447 bool isValue(const APFloat &C) { return C.isNegZero(); }
448};
449/// Match a floating-point negative zero.
450/// For vectors, this includes constants with undefined elements.
451inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
452 return cstfp_pred_ty<is_neg_zero_fp>();
453}
454
455///////////////////////////////////////////////////////////////////////////////
456
457template <typename Class> struct bind_ty {
458 Class *&VR;
459
460 bind_ty(Class *&V) : VR(V) {}
461
462 template <typename ITy> bool match(ITy *V) {
463 if (auto *CV = dyn_cast<Class>(V)) {
464 VR = CV;
465 return true;
466 }
467 return false;
468 }
469};
470
471/// Match a value, capturing it if we match.
472inline bind_ty<Value> m_Value(Value *&V) { return V; }
473inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
474
475/// Match an instruction, capturing it if we match.
476inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
477/// Match a binary operator, capturing it if we match.
478inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
479
480/// Match a ConstantInt, capturing the value if we match.
481inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
482
483/// Match a Constant, capturing the value if we match.
484inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
485
486/// Match a ConstantFP, capturing the value if we match.
487inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
488
489/// Match a specified Value*.
490struct specificval_ty {
491 const Value *Val;
492
493 specificval_ty(const Value *V) : Val(V) {}
494
495 template <typename ITy> bool match(ITy *V) { return V == Val; }
496};
497
498/// Match if we have a specific specified value.
499inline specificval_ty m_Specific(const Value *V) { return V; }
500
501/// Stores a reference to the Value *, not the Value * itself,
502/// thus can be used in commutative matchers.
503template <typename Class> struct deferredval_ty {
504 Class *const &Val;
505
506 deferredval_ty(Class *const &V) : Val(V) {}
507
508 template <typename ITy> bool match(ITy *const V) { return V == Val; }
509};
510
511/// A commutative-friendly version of m_Specific().