Bug Summary

File:include/llvm/Analysis/ValueTracking.h
Warning:line 626, column 5
Assigned value is garbage or undefined

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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn372306/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~svn372306/lib/Analysis -I /build/llvm-toolchain-snapshot-10~svn372306/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn372306/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn372306/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn372306=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-09-19-172240-30738-1 -x c++ /build/llvm-toolchain-snapshot-10~svn372306/lib/Analysis/ValueTracking.cpp

/build/llvm-toolchain-snapshot-10~svn372306/lib/Analysis/ValueTracking.cpp

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

/build/llvm-toolchain-snapshot-10~svn372306/include/llvm/IR/Operator.h

1//===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines various classes for working with Instructions and
10// ConstantExprs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_OPERATOR_H
15#define LLVM_IR_OPERATOR_H
16
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instruction.h"
21#include "llvm/IR/Type.h"
22#include "llvm/IR/Value.h"
23#include "llvm/Support/Casting.h"
24#include <cstddef>
25
26namespace llvm {
27
28/// This is a utility class that provides an abstraction for the common
29/// functionality between Instructions and ConstantExprs.
30class Operator : public User {
31public:
32 // The Operator class is intended to be used as a utility, and is never itself
33 // instantiated.
34 Operator() = delete;
35 ~Operator() = delete;
36
37 void *operator new(size_t s) = delete;
38
39 /// Return the opcode for this Instruction or ConstantExpr.
40 unsigned getOpcode() const {
41 if (const Instruction *I
2.1
'I' is non-null
2.1
'I' is non-null
2.1
'I' is non-null
= dyn_cast<Instruction>(this))
2
Assuming the object is a 'Instruction'
3
Taking true branch
42 return I->getOpcode();
4
Returning value, which participates in a condition later
43 return cast<ConstantExpr>(this)->getOpcode();
44 }
45
46 /// If V is an Instruction or ConstantExpr, return its opcode.
47 /// Otherwise return UserOp1.
48 static unsigned getOpcode(const Value *V) {
49 if (const Instruction *I = dyn_cast<Instruction>(V))
50 return I->getOpcode();
51 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
52 return CE->getOpcode();
53 return Instruction::UserOp1;
54 }
55
56 static bool classof(const Instruction *) { return true; }
57 static bool classof(const ConstantExpr *) { return true; }
58 static bool classof(const Value *V) {
59 return isa<Instruction>(V) || isa<ConstantExpr>(V);
60 }
61};
62
63/// Utility class for integer operators which may exhibit overflow - Add, Sub,
64/// Mul, and Shl. It does not include SDiv, despite that operator having the
65/// potential for overflow.
66class OverflowingBinaryOperator : public Operator {
67public:
68 enum {
69 NoUnsignedWrap = (1 << 0),
70 NoSignedWrap = (1 << 1)
71 };
72
73private:
74 friend class Instruction;
75 friend class ConstantExpr;
76
77 void setHasNoUnsignedWrap(bool B) {
78 SubclassOptionalData =
79 (SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
80 }
81 void setHasNoSignedWrap(bool B) {
82 SubclassOptionalData =
83 (SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
84 }
85
86public:
87 /// Test whether this operation is known to never
88 /// undergo unsigned overflow, aka the nuw property.
89 bool hasNoUnsignedWrap() const {
90 return SubclassOptionalData & NoUnsignedWrap;
91 }
92
93 /// Test whether this operation is known to never
94 /// undergo signed overflow, aka the nsw property.
95 bool hasNoSignedWrap() const {
96 return (SubclassOptionalData & NoSignedWrap) != 0;
97 }
98
99 static bool classof(const Instruction *I) {
100 return I->getOpcode() == Instruction::Add ||
101 I->getOpcode() == Instruction::Sub ||
102 I->getOpcode() == Instruction::Mul ||
103 I->getOpcode() == Instruction::Shl;
104 }
105 static bool classof(const ConstantExpr *CE) {
106 return CE->getOpcode() == Instruction::Add ||
107 CE->getOpcode() == Instruction::Sub ||
108 CE->getOpcode() == Instruction::Mul ||
109 CE->ge