Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ValueTracking.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn350071/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -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 -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/lib/Analysis/ValueTracking.cpp -faddrsig

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

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

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

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