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