blob: a6211ece22e93f543e32b197e97adb3a94c8f66b [file] [log] [blame]
Chris Lattner965c7692008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
James Molloy493e57d2015-10-26 14:10:46 +000016#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000019#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000020#include "llvm/Analysis/MemoryBuiltins.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000021#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000022#include "llvm/Analysis/LoopInfo.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000024#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/GlobalAlias.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Philip Reames5461d452015-04-23 17:36:48 +000037#include "llvm/IR/Statepoint.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000038#include "llvm/Support/Debug.h"
Chris Lattner965c7692008-06-02 01:18:21 +000039#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000040#include <algorithm>
41#include <array>
Chris Lattner64496902008-06-04 04:46:14 +000042#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000043using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000044using namespace llvm::PatternMatch;
45
46const unsigned MaxDepth = 6;
47
Philip Reames1c292272015-03-10 22:43:20 +000048/// Enable an experimental feature to leverage information about dominating
49/// conditions to compute known bits. The individual options below control how
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000050/// hard we search. The defaults are chosen to be fairly aggressive. If you
Philip Reames1c292272015-03-10 22:43:20 +000051/// run into compile time problems when testing, scale them back and report
52/// your findings.
53static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
54 cl::Hidden, cl::init(false));
55
56// This is expensive, so we only do it for the top level query value.
57// (TODO: evaluate cost vs profit, consider higher thresholds)
58static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
59 cl::Hidden, cl::init(1));
60
61/// How many dominating blocks should be scanned looking for dominating
62/// conditions?
63static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
64 cl::Hidden,
Igor Laevskycea9ede2015-09-29 14:57:52 +000065 cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000066
67// Controls the number of uses of the value searched for possible
68// dominating comparisons.
69static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000070 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000071
72// If true, don't consider only compares whose only use is a branch.
73static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
74 cl::Hidden, cl::init(false));
75
Sanjay Patelaee84212014-11-04 16:27:42 +000076/// Returns the bitwidth of the given scalar or pointer type (if unknown returns
77/// 0). For vector types, returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000078static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000079 if (unsigned BitWidth = Ty->getScalarSizeInBits())
80 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000081
Mehdi Aminia28d91d2015-03-10 02:37:25 +000082 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000083}
Chris Lattner965c7692008-06-02 01:18:21 +000084
Benjamin Kramercfd8d902014-09-12 08:56:53 +000085namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000086// Simplifying using an assume can only be done in a particular control-flow
87// context (the context instruction provides that context). If an assume and
88// the context instruction are not in the same block then the DT helps in
89// figuring out if we can use it.
90struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +000091 const DataLayout &DL;
Chandler Carruth66b31302015-01-04 12:03:27 +000092 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000093 const Instruction *CxtI;
94 const DominatorTree *DT;
95
Matthias Braun37e5d792016-01-28 06:29:33 +000096 /// Set of assumptions that should be excluded from further queries.
97 /// This is because of the potential for mutual recursion to cause
98 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
99 /// classic case of this is assume(x = y), which will attempt to determine
100 /// bits in x from bits in y, which will attempt to determine bits in y from
101 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
102 /// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
103 /// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so
104 /// on.
105 std::array<const Value*, MaxDepth> Excluded;
106 unsigned NumExcluded;
107
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000108 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
109 const DominatorTree *DT)
Matthias Braun37e5d792016-01-28 06:29:33 +0000110 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), NumExcluded(0) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000111
112 Query(const Query &Q, const Value *NewExcl)
Matthias Braun37e5d792016-01-28 06:29:33 +0000113 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), NumExcluded(Q.NumExcluded) {
114 Excluded = Q.Excluded;
115 Excluded[NumExcluded++] = NewExcl;
116 assert(NumExcluded <= Excluded.size());
117 }
118
119 bool isExcluded(const Value *Value) const {
120 if (NumExcluded == 0)
121 return false;
122 auto End = Excluded.begin() + NumExcluded;
123 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000124 }
125};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000126} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000127
Sanjay Patel547e9752014-11-04 16:09:50 +0000128// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000129// the preferred context instruction (if any).
130static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
131 // If we've been provided with a context instruction, then use that (provided
132 // it has been inserted).
133 if (CxtI && CxtI->getParent())
134 return CxtI;
135
136 // If the value is really an already-inserted instruction, then use that.
137 CxtI = dyn_cast<Instruction>(V);
138 if (CxtI && CxtI->getParent())
139 return CxtI;
140
141 return nullptr;
142}
143
144static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000145 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000146
147void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000148 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000149 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000150 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000151 ::computeKnownBits(V, KnownZero, KnownOne, Depth,
152 Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000153}
154
Jingyue Wuca321902015-05-14 23:53:19 +0000155bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
156 AssumptionCache *AC, const Instruction *CxtI,
157 const DominatorTree *DT) {
158 assert(LHS->getType() == RHS->getType() &&
159 "LHS and RHS should have the same type");
160 assert(LHS->getType()->isIntOrIntVectorTy() &&
161 "LHS and RHS should be integers");
162 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
163 APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
164 APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
165 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
166 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
167 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
168}
169
Hal Finkel60db0582014-09-07 18:57:58 +0000170static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000171 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000172
173void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000174 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000175 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000176 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000177 ::ComputeSignBit(V, KnownZero, KnownOne, Depth,
178 Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000179}
180
181static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000182 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000183
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000184bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
Chandler Carruth66b31302015-01-04 12:03:27 +0000185 unsigned Depth, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000186 const Instruction *CxtI,
187 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000188 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000189 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000190}
191
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000192static bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000193
194bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
195 AssumptionCache *AC, const Instruction *CxtI,
196 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000197 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000198}
199
Jingyue Wu10fcea52015-08-20 18:27:04 +0000200bool llvm::isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth,
201 AssumptionCache *AC, const Instruction *CxtI,
202 const DominatorTree *DT) {
203 bool NonNegative, Negative;
204 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
205 return NonNegative;
206}
207
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000208static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000209
210bool llvm::isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
211 AssumptionCache *AC, const Instruction *CxtI,
212 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000213 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
214 safeCxtI(V1, safeCxtI(V2, CxtI)),
215 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000216}
217
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000218static bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
219 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220
221bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
222 unsigned Depth, AssumptionCache *AC,
223 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000224 return ::MaskedValueIsZero(V, Mask, Depth,
225 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000226}
227
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000228static unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229
230unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
231 unsigned Depth, AssumptionCache *AC,
232 const Instruction *CxtI,
233 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000234 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000235}
236
Jay Foada0653a32014-05-14 21:14:37 +0000237static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
238 APInt &KnownZero, APInt &KnownOne,
239 APInt &KnownZero2, APInt &KnownOne2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000240 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000241 if (!Add) {
242 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
243 // We know that the top bits of C-X are clear if X contains less bits
244 // than C (i.e. no wrap-around can happen). For example, 20-X is
245 // positive if we can prove that X is >= 0 and < 16.
246 if (!CLHS->getValue().isNegative()) {
247 unsigned BitWidth = KnownZero.getBitWidth();
248 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
249 // NLZ can't be BitWidth with no sign bit
250 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000251 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000252
253 // If all of the MaskV bits are known to be zero, then we know the
254 // output top bits are zero, because we now know that the output is
255 // from [0-C].
256 if ((KnownZero2 & MaskV) == MaskV) {
257 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
258 // Top bits known zero.
259 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
260 }
261 }
262 }
263 }
264
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000265 unsigned BitWidth = KnownZero.getBitWidth();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000266
David Majnemer97ddca32014-08-22 00:40:43 +0000267 // If an initial sequence of bits in the result is not needed, the
268 // corresponding bits in the operands are not needed.
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000269 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000270 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, Depth + 1, Q);
271 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000272
David Majnemer97ddca32014-08-22 00:40:43 +0000273 // Carry in a 1 for a subtract, rather than a 0.
274 APInt CarryIn(BitWidth, 0);
275 if (!Add) {
276 // Sum = LHS + ~RHS + 1
277 std::swap(KnownZero2, KnownOne2);
278 CarryIn.setBit(0);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000279 }
280
David Majnemer97ddca32014-08-22 00:40:43 +0000281 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
282 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
283
284 // Compute known bits of the carry.
285 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
286 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
287
288 // Compute set of known bits (where all three relevant bits are known).
289 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
290 APInt RHSKnown = KnownZero2 | KnownOne2;
291 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
292 APInt Known = LHSKnown & RHSKnown & CarryKnown;
293
294 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
295 "known bits of sum differ");
296
297 // Compute known bits of the result.
298 KnownZero = ~PossibleSumOne & Known;
299 KnownOne = PossibleSumOne & Known;
300
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000301 // Are we still trying to solve for the sign bit?
David Majnemer97ddca32014-08-22 00:40:43 +0000302 if (!Known.isNegative()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000303 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000304 // Adding two non-negative numbers, or subtracting a negative number from
305 // a non-negative one, can't wrap into negative.
306 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
307 KnownZero |= APInt::getSignBit(BitWidth);
308 // Adding two negative numbers, or subtracting a non-negative number from
309 // a negative one, can't wrap into non-negative.
310 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
311 KnownOne |= APInt::getSignBit(BitWidth);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000312 }
313 }
314}
315
Jay Foada0653a32014-05-14 21:14:37 +0000316static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
317 APInt &KnownZero, APInt &KnownOne,
318 APInt &KnownZero2, APInt &KnownOne2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000319 unsigned Depth, const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000320 unsigned BitWidth = KnownZero.getBitWidth();
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000321 computeKnownBits(Op1, KnownZero, KnownOne, Depth + 1, Q);
322 computeKnownBits(Op0, KnownZero2, KnownOne2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000323
324 bool isKnownNegative = false;
325 bool isKnownNonNegative = false;
326 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000327 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000328 if (Op0 == Op1) {
329 // The product of a number with itself is non-negative.
330 isKnownNonNegative = true;
331 } else {
332 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
333 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
334 bool isKnownNegativeOp1 = KnownOne.isNegative();
335 bool isKnownNegativeOp0 = KnownOne2.isNegative();
336 // The product of two numbers with the same sign is non-negative.
337 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
338 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
339 // The product of a negative number and a non-negative number is either
340 // negative or zero.
341 if (!isKnownNonNegative)
342 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000343 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000344 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000345 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000346 }
347 }
348
349 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000350 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000351 // More trickiness is possible, but this is sufficient for the
352 // interesting case of alignment computation.
353 KnownOne.clearAllBits();
354 unsigned TrailZ = KnownZero.countTrailingOnes() +
355 KnownZero2.countTrailingOnes();
356 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
357 KnownZero2.countLeadingOnes(),
358 BitWidth) - BitWidth;
359
360 TrailZ = std::min(TrailZ, BitWidth);
361 LeadZ = std::min(LeadZ, BitWidth);
362 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
363 APInt::getHighBitsSet(BitWidth, LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000364
365 // Only make use of no-wrap flags if we failed to compute the sign bit
366 // directly. This matters if the multiplication always overflows, in
367 // which case we prefer to follow the result of the direct computation,
368 // though as the program is invoking undefined behaviour we can choose
369 // whatever we like here.
370 if (isKnownNonNegative && !KnownOne.isNegative())
371 KnownZero.setBit(BitWidth - 1);
372 else if (isKnownNegative && !KnownZero.isNegative())
373 KnownOne.setBit(BitWidth - 1);
374}
375
Jingyue Wu37fcb592014-06-19 16:50:16 +0000376void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000377 APInt &KnownZero,
378 APInt &KnownOne) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000379 unsigned BitWidth = KnownZero.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000380 unsigned NumRanges = Ranges.getNumOperands() / 2;
381 assert(NumRanges >= 1);
382
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000383 KnownZero.setAllBits();
384 KnownOne.setAllBits();
385
Rafael Espindola53190532012-03-30 15:52:11 +0000386 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000387 ConstantInt *Lower =
388 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
389 ConstantInt *Upper =
390 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000391 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000392
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000393 // The first CommonPrefixBits of all values in Range are equal.
394 unsigned CommonPrefixBits =
395 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
396
397 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
398 KnownOne &= Range.getUnsignedMax() & Mask;
399 KnownZero &= ~Range.getUnsignedMax() & Mask;
400 }
Rafael Espindola53190532012-03-30 15:52:11 +0000401}
Jay Foad5a29c362014-05-15 12:12:55 +0000402
Hal Finkel60db0582014-09-07 18:57:58 +0000403static bool isEphemeralValueOf(Instruction *I, const Value *E) {
404 SmallVector<const Value *, 16> WorkSet(1, I);
405 SmallPtrSet<const Value *, 32> Visited;
406 SmallPtrSet<const Value *, 16> EphValues;
407
Hal Finkelf2199b22015-10-23 20:37:08 +0000408 // The instruction defining an assumption's condition itself is always
409 // considered ephemeral to that assumption (even if it has other
410 // non-ephemeral users). See r246696's test case for an example.
411 if (std::find(I->op_begin(), I->op_end(), E) != I->op_end())
412 return true;
413
Hal Finkel60db0582014-09-07 18:57:58 +0000414 while (!WorkSet.empty()) {
415 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000416 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000417 continue;
418
419 // If all uses of this value are ephemeral, then so is this value.
Benjamin Kramer56115612015-10-24 19:30:37 +0000420 if (std::all_of(V->user_begin(), V->user_end(),
421 [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000422 if (V == E)
423 return true;
424
425 EphValues.insert(V);
426 if (const User *U = dyn_cast<User>(V))
427 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
428 J != JE; ++J) {
429 if (isSafeToSpeculativelyExecute(*J))
430 WorkSet.push_back(*J);
431 }
432 }
433 }
434
435 return false;
436}
437
438// Is this an intrinsic that cannot be speculated but also cannot trap?
439static bool isAssumeLikeIntrinsic(const Instruction *I) {
440 if (const CallInst *CI = dyn_cast<CallInst>(I))
441 if (Function *F = CI->getCalledFunction())
442 switch (F->getIntrinsicID()) {
443 default: break;
444 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
445 case Intrinsic::assume:
446 case Intrinsic::dbg_declare:
447 case Intrinsic::dbg_value:
448 case Intrinsic::invariant_start:
449 case Intrinsic::invariant_end:
450 case Intrinsic::lifetime_start:
451 case Intrinsic::lifetime_end:
452 case Intrinsic::objectsize:
453 case Intrinsic::ptr_annotation:
454 case Intrinsic::var_annotation:
455 return true;
456 }
457
458 return false;
459}
460
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000461static bool isValidAssumeForContext(Value *V, const Instruction *CxtI,
462 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000463 Instruction *Inv = cast<Instruction>(V);
464
465 // There are two restrictions on the use of an assume:
466 // 1. The assume must dominate the context (or the control flow must
467 // reach the assume whenever it reaches the context).
468 // 2. The context must not be in the assume's set of ephemeral values
469 // (otherwise we will use the assume to prove that the condition
470 // feeding the assume is trivially true, thus causing the removal of
471 // the assume).
472
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000473 if (DT) {
474 if (DT->dominates(Inv, CxtI)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000475 return true;
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000476 } else if (Inv->getParent() == CxtI->getParent()) {
Hal Finkel60db0582014-09-07 18:57:58 +0000477 // The context comes first, but they're both in the same block. Make sure
478 // there is nothing in between that might interrupt the control flow.
479 for (BasicBlock::const_iterator I =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000480 std::next(BasicBlock::const_iterator(CxtI)),
Hal Finkel60db0582014-09-07 18:57:58 +0000481 IE(Inv); I != IE; ++I)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000482 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
Hal Finkel60db0582014-09-07 18:57:58 +0000483 return false;
484
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000485 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000486 }
487
488 return false;
489 }
490
491 // When we don't have a DT, we do a limited search...
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000492 if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
Hal Finkel60db0582014-09-07 18:57:58 +0000493 return true;
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000494 } else if (Inv->getParent() == CxtI->getParent()) {
Hal Finkel60db0582014-09-07 18:57:58 +0000495 // Search forward from the assume until we reach the context (or the end
496 // of the block); the common case is that the assume will come first.
497 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
498 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000499 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000500 return true;
501
502 // The context must come first...
503 for (BasicBlock::const_iterator I =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000504 std::next(BasicBlock::const_iterator(CxtI)),
Hal Finkel60db0582014-09-07 18:57:58 +0000505 IE(Inv); I != IE; ++I)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000506 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
Hal Finkel60db0582014-09-07 18:57:58 +0000507 return false;
508
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000509 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000510 }
511
512 return false;
513}
514
515bool llvm::isValidAssumeForContext(const Instruction *I,
516 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000517 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000518 return ::isValidAssumeForContext(const_cast<Instruction *>(I), CxtI, DT);
Hal Finkel60db0582014-09-07 18:57:58 +0000519}
520
521template<typename LHS, typename RHS>
522inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
523 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
524m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
525 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
526}
527
528template<typename LHS, typename RHS>
529inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
530 BinaryOp_match<RHS, LHS, Instruction::And>>
531m_c_And(const LHS &L, const RHS &R) {
532 return m_CombineOr(m_And(L, R), m_And(R, L));
533}
534
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000535template<typename LHS, typename RHS>
536inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
537 BinaryOp_match<RHS, LHS, Instruction::Or>>
538m_c_Or(const LHS &L, const RHS &R) {
539 return m_CombineOr(m_Or(L, R), m_Or(R, L));
540}
541
542template<typename LHS, typename RHS>
543inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
544 BinaryOp_match<RHS, LHS, Instruction::Xor>>
545m_c_Xor(const LHS &L, const RHS &R) {
546 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
547}
548
Philip Reames1c292272015-03-10 22:43:20 +0000549/// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
550/// true (at the context instruction.) This is mostly a utility function for
551/// the prototype dominating conditions reasoning below.
552static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
553 APInt &KnownZero,
554 APInt &KnownOne,
Philip Reames1c292272015-03-10 22:43:20 +0000555 unsigned Depth, const Query &Q) {
556 Value *LHS = Cmp->getOperand(0);
557 Value *RHS = Cmp->getOperand(1);
558 // TODO: We could potentially be more aggressive here. This would be worth
559 // evaluating. If we can, explore commoning this code with the assume
560 // handling logic.
561 if (LHS != V && RHS != V)
562 return;
563
564 const unsigned BitWidth = KnownZero.getBitWidth();
565
566 switch (Cmp->getPredicate()) {
567 default:
568 // We know nothing from this condition
569 break;
570 // TODO: implement unsigned bound from below (known one bits)
571 // TODO: common condition check implementations with assumes
572 // TODO: implement other patterns from assume (e.g. V & B == A)
573 case ICmpInst::ICMP_SGT:
574 if (LHS == V) {
575 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000576 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
Philip Reames1c292272015-03-10 22:43:20 +0000577 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
578 // We know that the sign bit is zero.
579 KnownZero |= APInt::getSignBit(BitWidth);
580 }
581 }
582 break;
583 case ICmpInst::ICMP_EQ:
Jingyue Wu12b0c282015-06-15 05:46:29 +0000584 {
585 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
586 if (LHS == V)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000587 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +0000588 else if (RHS == V)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000589 computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +0000590 else
591 llvm_unreachable("missing use?");
592 KnownZero |= KnownZeroTemp;
593 KnownOne |= KnownOneTemp;
594 }
Philip Reames1c292272015-03-10 22:43:20 +0000595 break;
596 case ICmpInst::ICMP_ULE:
597 if (LHS == V) {
598 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000599 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
Philip Reames1c292272015-03-10 22:43:20 +0000600 // The known zero bits carry over
601 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
602 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
603 }
604 break;
605 case ICmpInst::ICMP_ULT:
606 if (LHS == V) {
607 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000608 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
Philip Reames1c292272015-03-10 22:43:20 +0000609 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
610 // power of 2, then one more).
611 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000612 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp)))
Philip Reames1c292272015-03-10 22:43:20 +0000613 SignBits++;
614 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
615 }
616 break;
617 };
618}
619
620/// Compute known bits in 'V' from conditions which are known to be true along
621/// all paths leading to the context instruction. In particular, look for
622/// cases where one branch of an interesting condition dominates the context
623/// instruction. This does not do general dataflow.
624/// NOTE: This code is EXPERIMENTAL and currently off by default.
625static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
626 APInt &KnownOne,
Philip Reames1c292272015-03-10 22:43:20 +0000627 unsigned Depth,
628 const Query &Q) {
629 // Need both the dominator tree and the query location to do anything useful
630 if (!Q.DT || !Q.CxtI)
631 return;
632 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
Philip Reames963febd2015-09-21 22:04:10 +0000633 // The context instruction might be in a statically unreachable block. If
634 // so, asking dominator queries may yield suprising results. (e.g. the block
635 // may not have a dom tree node)
636 if (!Q.DT->isReachableFromEntry(Cxt->getParent()))
637 return;
Philip Reames1c292272015-03-10 22:43:20 +0000638
639 // Avoid useless work
640 if (auto VI = dyn_cast<Instruction>(V))
641 if (VI->getParent() == Cxt->getParent())
642 return;
643
644 // Note: We currently implement two options. It's not clear which of these
645 // will survive long term, we need data for that.
646 // Option 1 - Try walking the dominator tree looking for conditions which
647 // might apply. This works well for local conditions (loop guards, etc..),
648 // but not as well for things far from the context instruction (presuming a
649 // low max blocks explored). If we can set an high enough limit, this would
650 // be all we need.
651 // Option 2 - We restrict out search to those conditions which are uses of
652 // the value we're interested in. This is independent of dom structure,
653 // but is slightly less powerful without looking through lots of use chains.
654 // It does handle conditions far from the context instruction (e.g. early
655 // function exits on entry) really well though.
656
657 // Option 1 - Search the dom tree
658 unsigned NumBlocksExplored = 0;
659 BasicBlock *Current = Cxt->getParent();
660 while (true) {
661 // Stop searching if we've gone too far up the chain
662 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
663 break;
664 NumBlocksExplored++;
665
666 if (!Q.DT->getNode(Current)->getIDom())
667 break;
668 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
669 if (!Current)
670 // found function entry
671 break;
672
673 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
674 if (!BI || BI->isUnconditional())
675 continue;
676 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
677 if (!Cmp)
678 continue;
679
680 // We're looking for conditions that are guaranteed to hold at the context
681 // instruction. Finding a condition where one path dominates the context
682 // isn't enough because both the true and false cases could merge before
683 // the context instruction we're actually interested in. Instead, we need
Philip Reames963febd2015-09-21 22:04:10 +0000684 // to ensure that the taken *edge* dominates the context instruction. We
685 // know that the edge must be reachable since we started from a reachable
686 // block.
Philip Reames1c292272015-03-10 22:43:20 +0000687 BasicBlock *BB0 = BI->getSuccessor(0);
688 BasicBlockEdge Edge(BI->getParent(), BB0);
689 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
690 continue;
691
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000692 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
Philip Reames1c292272015-03-10 22:43:20 +0000693 }
694
695 // Option 2 - Search the other uses of V
696 unsigned NumUsesExplored = 0;
697 for (auto U : V->users()) {
698 // Avoid massive lists
699 if (NumUsesExplored >= DomConditionsMaxUses)
700 break;
701 NumUsesExplored++;
702 // Consider only compare instructions uniquely controlling a branch
703 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
704 if (!Cmp)
705 continue;
706
707 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
708 continue;
709
710 for (auto *CmpU : Cmp->users()) {
711 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
712 if (!BI || BI->isUnconditional())
713 continue;
714 // We're looking for conditions that are guaranteed to hold at the
715 // context instruction. Finding a condition where one path dominates
716 // the context isn't enough because both the true and false cases could
717 // merge before the context instruction we're actually interested in.
718 // Instead, we need to ensure that the taken *edge* dominates the context
719 // instruction.
720 BasicBlock *BB0 = BI->getSuccessor(0);
721 BasicBlockEdge Edge(BI->getParent(), BB0);
722 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
723 continue;
724
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000725 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
Philip Reames1c292272015-03-10 22:43:20 +0000726 }
727 }
728}
729
Hal Finkel60db0582014-09-07 18:57:58 +0000730static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000731 APInt &KnownOne, unsigned Depth,
732 const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000733 // Use of assumptions is context-sensitive. If we don't have a context, we
734 // cannot use them!
Chandler Carruth66b31302015-01-04 12:03:27 +0000735 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000736 return;
737
738 unsigned BitWidth = KnownZero.getBitWidth();
739
Chandler Carruth66b31302015-01-04 12:03:27 +0000740 for (auto &AssumeVH : Q.AC->assumptions()) {
741 if (!AssumeVH)
742 continue;
743 CallInst *I = cast<CallInst>(AssumeVH);
Chandler Carruth75c11b82015-01-04 23:13:57 +0000744 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
Chandler Carruth66b31302015-01-04 12:03:27 +0000745 "Got assumption for the wrong function!");
Matthias Braun37e5d792016-01-28 06:29:33 +0000746 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000747 continue;
748
Philip Reames00d3b272014-11-24 23:44:28 +0000749 // Warning: This loop can end up being somewhat performance sensetive.
750 // We're running this loop for once for each value queried resulting in a
751 // runtime of ~O(#assumes * #values).
752
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000753 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
Philip Reames00d3b272014-11-24 23:44:28 +0000754 "must be an assume intrinsic");
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000755
Philip Reames00d3b272014-11-24 23:44:28 +0000756 Value *Arg = I->getArgOperand(0);
757
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000758 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000759 assert(BitWidth == 1 && "assume operand is not i1?");
760 KnownZero.clearAllBits();
761 KnownOne.setAllBits();
762 return;
763 }
764
David Majnemer9b609752014-12-12 23:59:29 +0000765 // The remaining tests are all recursive, so bail out if we hit the limit.
766 if (Depth == MaxDepth)
767 continue;
768
Hal Finkel60db0582014-09-07 18:57:58 +0000769 Value *A, *B;
770 auto m_V = m_CombineOr(m_Specific(V),
771 m_CombineOr(m_PtrToInt(m_Specific(V)),
772 m_BitCast(m_Specific(V))));
773
774 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000775 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000776 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000777 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000778 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000779 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000780 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000781 KnownZero |= RHSKnownZero;
782 KnownOne |= RHSKnownOne;
783 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000784 } else if (match(Arg,
785 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000786 Pred == ICmpInst::ICMP_EQ &&
787 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000788 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000789 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000790 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000791 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000792
793 // For those bits in the mask that are known to be one, we can propagate
794 // known bits from the RHS to V.
795 KnownZero |= RHSKnownZero & MaskKnownOne;
796 KnownOne |= RHSKnownOne & MaskKnownOne;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000797 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000798 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
799 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000800 Pred == ICmpInst::ICMP_EQ &&
801 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000802 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000803 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000804 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000805 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000806
807 // For those bits in the mask that are known to be one, we can propagate
808 // inverted known bits from the RHS to V.
809 KnownZero |= RHSKnownOne & MaskKnownOne;
810 KnownOne |= RHSKnownZero & MaskKnownOne;
811 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000812 } else if (match(Arg,
813 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000814 Pred == ICmpInst::ICMP_EQ &&
815 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000816 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000817 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000818 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000819 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000820
821 // For those bits in B that are known to be zero, we can propagate known
822 // bits from the RHS to V.
823 KnownZero |= RHSKnownZero & BKnownZero;
824 KnownOne |= RHSKnownOne & BKnownZero;
825 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000826 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
827 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000828 Pred == ICmpInst::ICMP_EQ &&
829 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000830 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000831 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000832 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000833 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000834
835 // For those bits in B that are known to be zero, we can propagate
836 // inverted known bits from the RHS to V.
837 KnownZero |= RHSKnownOne & BKnownZero;
838 KnownOne |= RHSKnownZero & BKnownZero;
839 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000840 } else if (match(Arg,
841 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000842 Pred == ICmpInst::ICMP_EQ &&
843 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000844 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000845 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000846 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000847 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000848
849 // For those bits in B that are known to be zero, we can propagate known
850 // bits from the RHS to V. For those bits in B that are known to be one,
851 // we can propagate inverted known bits from the RHS to V.
852 KnownZero |= RHSKnownZero & BKnownZero;
853 KnownOne |= RHSKnownOne & BKnownZero;
854 KnownZero |= RHSKnownOne & BKnownOne;
855 KnownOne |= RHSKnownZero & BKnownOne;
856 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000857 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
858 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000859 Pred == ICmpInst::ICMP_EQ &&
860 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000861 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000862 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000863 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000864 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000865
866 // For those bits in B that are known to be zero, we can propagate
867 // inverted known bits from the RHS to V. For those bits in B that are
868 // known to be one, we can propagate known bits from the RHS to V.
869 KnownZero |= RHSKnownOne & BKnownZero;
870 KnownOne |= RHSKnownZero & BKnownZero;
871 KnownZero |= RHSKnownZero & BKnownOne;
872 KnownOne |= RHSKnownOne & BKnownOne;
873 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000874 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
875 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000876 Pred == ICmpInst::ICMP_EQ &&
877 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000878 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000879 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000880 // For those bits in RHS that are known, we can propagate them to known
881 // bits in V shifted to the right by C.
882 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
883 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
884 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000885 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
886 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000887 Pred == ICmpInst::ICMP_EQ &&
888 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000889 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000890 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000891 // For those bits in RHS that are known, we can propagate them inverted
892 // to known bits in V shifted to the right by C.
893 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
894 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
895 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000896 } else if (match(Arg,
897 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000898 m_AShr(m_V, m_ConstantInt(C))),
899 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000900 Pred == ICmpInst::ICMP_EQ &&
901 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000902 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000903 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000904 // For those bits in RHS that are known, we can propagate them to known
905 // bits in V shifted to the right by C.
906 KnownZero |= RHSKnownZero << C->getZExtValue();
907 KnownOne |= RHSKnownOne << C->getZExtValue();
908 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000909 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000910 m_LShr(m_V, m_ConstantInt(C)),
911 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000912 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000913 Pred == ICmpInst::ICMP_EQ &&
914 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000915 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000916 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000917 // For those bits in RHS that are known, we can propagate them inverted
918 // to known bits in V shifted to the right by C.
919 KnownZero |= RHSKnownOne << C->getZExtValue();
920 KnownOne |= RHSKnownZero << C->getZExtValue();
921 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000922 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000923 Pred == ICmpInst::ICMP_SGE &&
924 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000925 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000926 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000927
928 if (RHSKnownZero.isNegative()) {
929 // We know that the sign bit is zero.
930 KnownZero |= APInt::getSignBit(BitWidth);
931 }
932 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000933 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000934 Pred == ICmpInst::ICMP_SGT &&
935 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000936 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000937 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000938
939 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
940 // We know that the sign bit is zero.
941 KnownZero |= APInt::getSignBit(BitWidth);
942 }
943 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000944 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000945 Pred == ICmpInst::ICMP_SLE &&
946 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000947 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000948 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000949
950 if (RHSKnownOne.isNegative()) {
951 // We know that the sign bit is one.
952 KnownOne |= APInt::getSignBit(BitWidth);
953 }
954 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000955 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000956 Pred == ICmpInst::ICMP_SLT &&
957 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000958 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000959 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000960
961 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
962 // We know that the sign bit is one.
963 KnownOne |= APInt::getSignBit(BitWidth);
964 }
965 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000966 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000967 Pred == ICmpInst::ICMP_ULE &&
968 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000969 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000970 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000971
972 // Whatever high bits in c are zero are known to be zero.
973 KnownZero |=
974 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
975 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000976 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000977 Pred == ICmpInst::ICMP_ULT &&
978 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000979 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000980 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000981
982 // Whatever high bits in c are zero are known to be zero (if c is a power
983 // of 2, then one more).
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000984 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000985 KnownZero |=
986 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
987 else
988 KnownZero |=
989 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000990 }
991 }
992}
993
Hal Finkelf2199b22015-10-23 20:37:08 +0000994// Compute known bits from a shift operator, including those with a
995// non-constant shift amount. KnownZero and KnownOne are the outputs of this
996// function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the
997// same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific
998// functors that, given the known-zero or known-one bits respectively, and a
999// shift amount, compute the implied known-zero or known-one bits of the shift
1000// operator's result respectively for that shift amount. The results from calling
1001// KZF and KOF are conservatively combined for all permitted shift amounts.
1002template <typename KZFunctor, typename KOFunctor>
1003static void computeKnownBitsFromShiftOperator(Operator *I,
1004 APInt &KnownZero, APInt &KnownOne,
1005 APInt &KnownZero2, APInt &KnownOne2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001006 unsigned Depth, const Query &Q, KZFunctor KZF, KOFunctor KOF) {
Hal Finkelf2199b22015-10-23 20:37:08 +00001007 unsigned BitWidth = KnownZero.getBitWidth();
1008
1009 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1010 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
1011
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001012 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +00001013 KnownZero = KZF(KnownZero, ShiftAmt);
1014 KnownOne = KOF(KnownOne, ShiftAmt);
1015 return;
1016 }
1017
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001018 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +00001019
1020 // Note: We cannot use KnownZero.getLimitedValue() here, because if
1021 // BitWidth > 64 and any upper bits are known, we'll end up returning the
1022 // limit value (which implies all bits are known).
1023 uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue();
1024 uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue();
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.
Richard Trieu7a083812016-02-18 22:09:30 +00001028 KnownZero.clearAllBits();
1029 KnownOne.clearAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +00001030
James Molloy493e57d2015-10-26 14:10:46 +00001031 // If we know the shifter operand is nonzero, we can sometimes infer more
1032 // known bits. However this is expensive to compute, so be lazy about it and
1033 // only compute it when absolutely necessary.
1034 Optional<bool> ShifterOperandIsNonZero;
1035
Hal Finkelf2199b22015-10-23 20:37:08 +00001036 // Early exit if we can't constrain any well-defined shift amount.
James Molloy493e57d2015-10-26 14:10:46 +00001037 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
1038 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001039 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +00001040 if (!*ShifterOperandIsNonZero)
1041 return;
1042 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001043
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001044 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +00001045
1046 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
1047 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
1048 // Combine the shifted known input bits only for those shift amounts
1049 // compatible with its known constraints.
1050 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
1051 continue;
1052 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
1053 continue;
James Molloy493e57d2015-10-26 14:10:46 +00001054 // If we know the shifter is nonzero, we may be able to infer more known
1055 // bits. This check is sunk down as far as possible to avoid the expensive
1056 // call to isKnownNonZero if the cheaper checks above fail.
1057 if (ShiftAmt == 0) {
1058 if (!ShifterOperandIsNonZero.hasValue())
1059 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001060 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +00001061 if (*ShifterOperandIsNonZero)
1062 continue;
1063 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001064
1065 KnownZero &= KZF(KnownZero2, ShiftAmt);
1066 KnownOne &= KOF(KnownOne2, ShiftAmt);
1067 }
1068
1069 // If there are no compatible shift amounts, then we've proven that the shift
1070 // amount must be >= the BitWidth, and the result is undefined. We could
1071 // return anything we'd like, but we need to make sure the sets of known bits
1072 // stay disjoint (it should be better for some other code to actually
1073 // propagate the undef than to pick a value here using known bits).
Richard Trieu7a083812016-02-18 22:09:30 +00001074 if ((KnownZero & KnownOne) != 0) {
1075 KnownZero.clearAllBits();
1076 KnownOne.clearAllBits();
1077 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001078}
1079
Jingyue Wu12b0c282015-06-15 05:46:29 +00001080static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001081 APInt &KnownOne, unsigned Depth,
1082 const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001083 unsigned BitWidth = KnownZero.getBitWidth();
1084
Chris Lattner965c7692008-06-02 01:18:21 +00001085 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001086 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001087 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +00001088 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001089 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Sanjoy Das1d1929a2015-10-28 03:20:15 +00001090 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
Jay Foad5a29c362014-05-15 12:12:55 +00001091 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001092 case Instruction::And: {
1093 // If either the LHS or the RHS are Zero, the result is zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001094 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1095 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001096
Chris Lattner965c7692008-06-02 01:18:21 +00001097 // Output known-1 bits are only known if set in both the LHS & RHS.
1098 KnownOne &= KnownOne2;
1099 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1100 KnownZero |= KnownZero2;
Philip Reames2d858742015-11-10 18:46:14 +00001101
1102 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1103 // here we handle the more general case of adding any odd number by
1104 // matching the form add(x, add(x, y)) where y is odd.
1105 // TODO: This could be generalized to clearing any bit set in y where the
1106 // following bit is known to be unset in y.
1107 Value *Y = nullptr;
1108 if (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
1109 m_Value(Y))) ||
1110 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
1111 m_Value(Y)))) {
1112 APInt KnownZero3(BitWidth, 0), KnownOne3(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001113 computeKnownBits(Y, KnownZero3, KnownOne3, Depth + 1, Q);
Philip Reames2d858742015-11-10 18:46:14 +00001114 if (KnownOne3.countTrailingOnes() > 0)
1115 KnownZero |= APInt::getLowBitsSet(BitWidth, 1);
1116 }
Jay Foad5a29c362014-05-15 12:12:55 +00001117 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001118 }
1119 case Instruction::Or: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001120 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1121 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001122
Chris Lattner965c7692008-06-02 01:18:21 +00001123 // Output known-0 bits are only known if clear in both the LHS & RHS.
1124 KnownZero &= KnownZero2;
1125 // Output known-1 are known to be set if set in either the LHS | RHS.
1126 KnownOne |= KnownOne2;
Jay Foad5a29c362014-05-15 12:12:55 +00001127 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001128 }
1129 case Instruction::Xor: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001130 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1131 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001132
Chris Lattner965c7692008-06-02 01:18:21 +00001133 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1134 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1135 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1136 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1137 KnownZero = KnownZeroOut;
Jay Foad5a29c362014-05-15 12:12:55 +00001138 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001139 }
1140 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001141 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001143 KnownOne, KnownZero2, KnownOne2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001144 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001145 }
1146 case Instruction::UDiv: {
1147 // For the purposes of computing leading zeros we can conservatively
1148 // treat a udiv as a logical right shift by the power of 2 known to
1149 // be less than the denominator.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001150 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001151 unsigned LeadZ = KnownZero2.countLeadingOnes();
1152
Jay Foad25a5e4c2010-12-01 08:53:58 +00001153 KnownOne2.clearAllBits();
1154 KnownZero2.clearAllBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001155 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001156 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1157 if (RHSUnknownLeadingOnes != BitWidth)
1158 LeadZ = std::min(BitWidth,
1159 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1160
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001161 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001162 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001163 }
James Molloyc5eded52016-01-14 15:49:32 +00001164 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001165 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q);
1166 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001167
1168 // Only known if known in both the LHS and RHS.
1169 KnownOne &= KnownOne2;
1170 KnownZero &= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +00001171 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001172 case Instruction::FPTrunc:
1173 case Instruction::FPExt:
1174 case Instruction::FPToUI:
1175 case Instruction::FPToSI:
1176 case Instruction::SIToFP:
1177 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001178 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001179 case Instruction::PtrToInt:
1180 case Instruction::IntToPtr:
Matt Arsenaultf1a7e622014-07-15 01:55:03 +00001181 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
Chris Lattner965c7692008-06-02 01:18:21 +00001182 // FALL THROUGH and handle them the same as zext/trunc.
1183 case Instruction::ZExt:
1184 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001185 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001186
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001187 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001188 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1189 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001190 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001191
1192 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Jay Foad583abbc2010-12-07 08:25:19 +00001193 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1194 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001195 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001196 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1197 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001198 // Any top bits are known to be zero.
1199 if (BitWidth > SrcBitWidth)
1200 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001201 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001202 }
1203 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001204 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Patel9115cf82015-10-08 16:56:55 +00001205 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy() ||
1206 SrcTy->isFloatingPointTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001207 // TODO: For now, not handling conversions like:
1208 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001209 !I->getType()->isVectorTy()) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001210 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001211 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001212 }
1213 break;
1214 }
1215 case Instruction::SExt: {
1216 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001217 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001218
Jay Foad583abbc2010-12-07 08:25:19 +00001219 KnownZero = KnownZero.trunc(SrcBitWidth);
1220 KnownOne = KnownOne.trunc(SrcBitWidth);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001221 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001222 KnownZero = KnownZero.zext(BitWidth);
1223 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001224
1225 // If the sign bit of the input is known set or clear, then we know the
1226 // top bits of the result.
1227 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1228 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1229 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1230 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001231 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001232 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001233 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001234 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Hal Finkelf2199b22015-10-23 20:37:08 +00001235 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1236 return (KnownZero << ShiftAmt) |
1237 APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0.
1238 };
1239
1240 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1241 return KnownOne << ShiftAmt;
1242 };
1243
1244 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001245 KnownZero2, KnownOne2, Depth, Q, KZF,
1246 KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001247 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001248 }
1249 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001250 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Hal Finkelf2199b22015-10-23 20:37:08 +00001251 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1252 return APIntOps::lshr(KnownZero, ShiftAmt) |
1253 // High bits known zero.
1254 APInt::getHighBitsSet(BitWidth, ShiftAmt);
1255 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001256
Hal Finkelf2199b22015-10-23 20:37:08 +00001257 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1258 return APIntOps::lshr(KnownOne, ShiftAmt);
1259 };
1260
1261 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001262 KnownZero2, KnownOne2, Depth, Q, KZF,
1263 KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001264 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001265 }
1266 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001267 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Hal Finkelf2199b22015-10-23 20:37:08 +00001268 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1269 return APIntOps::ashr(KnownZero, ShiftAmt);
1270 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001271
Hal Finkelf2199b22015-10-23 20:37:08 +00001272 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1273 return APIntOps::ashr(KnownOne, ShiftAmt);
1274 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001275
Hal Finkelf2199b22015-10-23 20:37:08 +00001276 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001277 KnownZero2, KnownOne2, Depth, Q, KZF,
1278 KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001279 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001280 }
Chris Lattner965c7692008-06-02 01:18:21 +00001281 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001282 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001283 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001284 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1285 Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001286 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001287 }
Chris Lattner965c7692008-06-02 01:18:21 +00001288 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001289 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001290 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001291 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1292 Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001293 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001294 }
1295 case Instruction::SRem:
1296 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001297 APInt RA = Rem->getValue().abs();
1298 if (RA.isPowerOf2()) {
1299 APInt LowBits = RA - 1;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001300 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001301 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001302
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001303 // The low bits of the first operand are unchanged by the srem.
1304 KnownZero = KnownZero2 & LowBits;
1305 KnownOne = KnownOne2 & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001306
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001307 // If the first operand is non-negative or has all low bits zero, then
1308 // the upper bits are all zero.
1309 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1310 KnownZero |= ~LowBits;
1311
1312 // If the first operand is negative and not all low bits are zero, then
1313 // the upper bits are all one.
1314 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1315 KnownOne |= ~LowBits;
1316
Craig Topper1bef2c82012-12-22 19:15:35 +00001317 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001318 }
1319 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001320
1321 // The sign bit is the LHS's sign bit, except when the result of the
1322 // remainder is zero.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001323 if (KnownZero.isNonNegative()) {
Nick Lewyckye4679792011-03-07 01:50:10 +00001324 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001325 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
1326 Q);
Nick Lewyckye4679792011-03-07 01:50:10 +00001327 // If it's known zero, our sign bit is also zero.
1328 if (LHSKnownZero.isNegative())
Duncan Sands34c48692012-04-30 11:56:58 +00001329 KnownZero.setBit(BitWidth - 1);
Nick Lewyckye4679792011-03-07 01:50:10 +00001330 }
1331
Chris Lattner965c7692008-06-02 01:18:21 +00001332 break;
1333 case Instruction::URem: {
1334 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1335 APInt RA = Rem->getValue();
1336 if (RA.isPowerOf2()) {
1337 APInt LowBits = (RA - 1);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001338 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001339 KnownZero |= ~LowBits;
1340 KnownOne &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001341 break;
1342 }
1343 }
1344
1345 // Since the result is less than or equal to either operand, any leading
1346 // zero bits in either operand must also exist in the result.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001347 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1348 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001349
Chris Lattner4612ae12009-01-20 18:22:57 +00001350 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner965c7692008-06-02 01:18:21 +00001351 KnownZero2.countLeadingOnes());
Jay Foad25a5e4c2010-12-01 08:53:58 +00001352 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001353 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001354 break;
1355 }
1356
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001357 case Instruction::Alloca: {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001358 AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001359 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001360 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001361 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001362
Chris Lattner965c7692008-06-02 01:18:21 +00001363 if (Align > 0)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001364 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001365 break;
1366 }
1367 case Instruction::GetElementPtr: {
1368 // Analyze all of the subscripts of this getelementptr instruction
1369 // to determine if we can prove known low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001370 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001371 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, Depth + 1,
1372 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001373 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1374
1375 gep_type_iterator GTI = gep_type_begin(I);
1376 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1377 Value *Index = I->getOperand(i);
Chris Lattner229907c2011-07-18 04:54:35 +00001378 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001379 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001380
1381 // Handle case when index is vector zeroinitializer
1382 Constant *CIndex = cast<Constant>(Index);
1383 if (CIndex->isZeroValue())
1384 continue;
1385
1386 if (CIndex->getType()->isVectorTy())
1387 Index = CIndex->getSplatValue();
1388
Chris Lattner965c7692008-06-02 01:18:21 +00001389 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001390 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001391 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001392 TrailZ = std::min<unsigned>(TrailZ,
1393 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001394 } else {
1395 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001396 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001397 if (!IndexedTy->isSized()) {
1398 TrailZ = 0;
1399 break;
1400 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001401 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001402 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Chris Lattner965c7692008-06-02 01:18:21 +00001403 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001404 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001405 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001406 unsigned(countTrailingZeros(TypeSize) +
Chris Lattner4612ae12009-01-20 18:22:57 +00001407 LocalKnownZero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001408 }
1409 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001410
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001411 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001412 break;
1413 }
1414 case Instruction::PHI: {
1415 PHINode *P = cast<PHINode>(I);
1416 // Handle the case of a simple two-predecessor recurrence PHI.
1417 // There's a lot more that could theoretically be done here, but
1418 // this is sufficient to catch some interesting cases.
1419 if (P->getNumIncomingValues() == 2) {
1420 for (unsigned i = 0; i != 2; ++i) {
1421 Value *L = P->getIncomingValue(i);
1422 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001423 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001424 if (!LU)
1425 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001426 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001427 // Check for operations that have the property that if
1428 // both their operands have low zero bits, the result
1429 // will have low zero bits.
1430 if (Opcode == Instruction::Add ||
1431 Opcode == Instruction::Sub ||
1432 Opcode == Instruction::And ||
1433 Opcode == Instruction::Or ||
1434 Opcode == Instruction::Mul) {
1435 Value *LL = LU->getOperand(0);
1436 Value *LR = LU->getOperand(1);
1437 // Find a recurrence.
1438 if (LL == I)
1439 L = LR;
1440 else if (LR == I)
1441 L = LL;
1442 else
1443 break;
1444 // Ok, we have a PHI of the form L op= R. Check for low
1445 // zero bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001446 computeKnownBits(R, KnownZero2, KnownOne2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001447
1448 // We need to take the minimum number of known bits
1449 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001450 computeKnownBits(L, KnownZero3, KnownOne3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001451
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001452 KnownZero = APInt::getLowBitsSet(BitWidth,
David Greeneaebd9e02008-10-27 23:24:03 +00001453 std::min(KnownZero2.countTrailingOnes(),
1454 KnownZero3.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001455 break;
1456 }
1457 }
1458 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001459
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001460 // Unreachable blocks may have zero-operand PHI nodes.
1461 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001462 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001463
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001464 // Otherwise take the unions of the known bit sets of the operands,
1465 // taking conservative care to avoid excessive recursion.
1466 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001467 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001468 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001469 break;
1470
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001471 KnownZero = APInt::getAllOnesValue(BitWidth);
1472 KnownOne = APInt::getAllOnesValue(BitWidth);
Pete Cooper833f34d2015-05-12 20:05:31 +00001473 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001474 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001475 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001476
1477 KnownZero2 = APInt(BitWidth, 0);
1478 KnownOne2 = APInt(BitWidth, 0);
1479 // Recurse, but cap the recursion to one level, because we don't
1480 // want to waste time spinning around in loops.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001481 computeKnownBits(IncValue, KnownZero2, KnownOne2, MaxDepth - 1, Q);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001482 KnownZero &= KnownZero2;
1483 KnownOne &= KnownOne2;
1484 // If all bits have been ruled out, there's no need to check
1485 // more operands.
1486 if (!KnownZero && !KnownOne)
1487 break;
1488 }
1489 }
Chris Lattner965c7692008-06-02 01:18:21 +00001490 break;
1491 }
1492 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001493 case Instruction::Invoke:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001494 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Sanjoy Das1d1929a2015-10-28 03:20:15 +00001495 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
Jingyue Wu37fcb592014-06-19 16:50:16 +00001496 // If a range metadata is attached to this IntrinsicInst, intersect the
1497 // explicit range specified by the metadata and the implicit range of
1498 // the intrinsic.
Chris Lattner965c7692008-06-02 01:18:21 +00001499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1500 switch (II->getIntrinsicID()) {
1501 default: break;
Philip Reames675418e2015-10-06 20:20:45 +00001502 case Intrinsic::bswap:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001503 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Philip Reames675418e2015-10-06 20:20:45 +00001504 KnownZero |= KnownZero2.byteSwap();
1505 KnownOne |= KnownOne2.byteSwap();
1506 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001507 case Intrinsic::ctlz:
1508 case Intrinsic::cttz: {
1509 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001510 // If this call is undefined for 0, the result will be less than 2^n.
1511 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1512 LowBits -= 1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001513 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001514 break;
1515 }
1516 case Intrinsic::ctpop: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001517 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001518 // We can bound the space the count needs. Also, bits known to be zero
1519 // can't contribute to the population.
1520 unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation();
1521 unsigned LeadingZeros =
1522 APInt(BitWidth, BitsPossiblySet).countLeadingZeros();
Aaron Ballman58f413c2015-10-15 13:55:43 +00001523 assert(LeadingZeros <= BitWidth);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001524 KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros);
1525 KnownOne &= ~KnownZero;
1526 // TODO: we could bound KnownOne using the lower bound on the number
1527 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001528 break;
1529 }
Sanjay Patel9115cf82015-10-08 16:56:55 +00001530 case Intrinsic::fabs: {
1531 Type *Ty = II->getType();
1532 APInt SignBit = APInt::getSignBit(Ty->getScalarSizeInBits());
1533 KnownZero |= APInt::getSplat(Ty->getPrimitiveSizeInBits(), SignBit);
1534 break;
1535 }
Chad Rosierb3628842011-05-26 23:13:19 +00001536 case Intrinsic::x86_sse42_crc32_64_64:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001537 KnownZero |= APInt::getHighBitsSet(64, 32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001538 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001539 }
1540 }
1541 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001542 case Instruction::ExtractValue:
1543 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1544 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1545 if (EVI->getNumIndices() != 1) break;
1546 if (EVI->getIndices()[0] == 0) {
1547 switch (II->getIntrinsicID()) {
1548 default: break;
1549 case Intrinsic::uadd_with_overflow:
1550 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001551 computeKnownBitsAddSub(true, II->getArgOperand(0),
1552 II->getArgOperand(1), false, KnownZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001553 KnownOne, KnownZero2, KnownOne2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001554 break;
1555 case Intrinsic::usub_with_overflow:
1556 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001557 computeKnownBitsAddSub(false, II->getArgOperand(0),
1558 II->getArgOperand(1), false, KnownZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001559 KnownOne, KnownZero2, KnownOne2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001560 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001561 case Intrinsic::umul_with_overflow:
1562 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001563 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001564 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1565 Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001566 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001567 }
1568 }
1569 }
Chris Lattner965c7692008-06-02 01:18:21 +00001570 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001571}
1572
1573/// Determine which bits of V are known to be either zero or one and return
1574/// them in the KnownZero/KnownOne bit sets.
1575///
1576/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1577/// we cannot optimize based on the assumption that it is zero without changing
1578/// it to be an explicit zero. If we don't change it to zero, other code could
1579/// optimized based on the contradictory assumption that it is non-zero.
1580/// Because instcombine aggressively folds operations with undef args anyway,
1581/// this won't lose us code quality.
1582///
1583/// This function is defined on values with integer type, values with pointer
1584/// type, and vectors of integers. In the case
1585/// where V is a vector, known zero, and known one values are the
1586/// same width as the vector element, and the bit is set only if it is true
1587/// for all of the elements in the vector.
1588void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001589 unsigned Depth, const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001590 assert(V && "No Value?");
1591 assert(Depth <= MaxDepth && "Limit Search Depth");
1592 unsigned BitWidth = KnownZero.getBitWidth();
1593
1594 assert((V->getType()->isIntOrIntVectorTy() ||
Sanjay Patel9115cf82015-10-08 16:56:55 +00001595 V->getType()->isFPOrFPVectorTy() ||
Jingyue Wu12b0c282015-06-15 05:46:29 +00001596 V->getType()->getScalarType()->isPointerTy()) &&
Sanjay Patel9115cf82015-10-08 16:56:55 +00001597 "Not integer, floating point, or pointer type!");
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001598 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Jingyue Wu12b0c282015-06-15 05:46:29 +00001599 (!V->getType()->isIntOrIntVectorTy() ||
1600 V->getType()->getScalarSizeInBits() == BitWidth) &&
1601 KnownZero.getBitWidth() == BitWidth &&
1602 KnownOne.getBitWidth() == BitWidth &&
1603 "V, KnownOne and KnownZero should have same BitWidth");
1604
1605 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1606 // We know all of the bits for a constant!
1607 KnownOne = CI->getValue();
1608 KnownZero = ~KnownOne;
1609 return;
1610 }
1611 // Null and aggregate-zero are all-zeros.
1612 if (isa<ConstantPointerNull>(V) ||
1613 isa<ConstantAggregateZero>(V)) {
1614 KnownOne.clearAllBits();
1615 KnownZero = APInt::getAllOnesValue(BitWidth);
1616 return;
1617 }
1618 // Handle a constant vector by taking the intersection of the known bits of
1619 // each element. There is no real need to handle ConstantVector here, because
1620 // we don't handle undef in any particularly useful way.
1621 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1622 // We know that CDS must be a vector of integers. Take the intersection of
1623 // each element.
1624 KnownZero.setAllBits(); KnownOne.setAllBits();
1625 APInt Elt(KnownZero.getBitWidth(), 0);
1626 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1627 Elt = CDS->getElementAsInteger(i);
1628 KnownZero &= ~Elt;
1629 KnownOne &= Elt;
1630 }
1631 return;
1632 }
1633
Jingyue Wu12b0c282015-06-15 05:46:29 +00001634 // Start out not knowing anything.
1635 KnownZero.clearAllBits(); KnownOne.clearAllBits();
1636
1637 // Limit search depth.
1638 // All recursive calls that increase depth must come after this.
1639 if (Depth == MaxDepth)
1640 return;
1641
1642 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1643 // the bits of its aliasee.
1644 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1645 if (!GA->mayBeOverridden())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001646 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001647 return;
1648 }
1649
1650 if (Operator *I = dyn_cast<Operator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001651 computeKnownBitsFromOperator(I, KnownZero, KnownOne, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001652
Artur Pilipenko029d8532015-09-30 11:55:45 +00001653 // Aligned pointers have trailing zeros - refine KnownZero set
1654 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001655 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001656 if (Align)
1657 KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1658 }
1659
Jingyue Wu12b0c282015-06-15 05:46:29 +00001660 // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
1661 // strictly refines KnownZero and KnownOne. Therefore, we run them after
1662 // computeKnownBitsFromOperator.
1663
1664 // Check whether a nearby assume intrinsic can determine some known bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001665 computeKnownBitsFromAssume(V, KnownZero, KnownOne, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001666
1667 // Check whether there's a dominating condition which implies something about
1668 // this value at the given context.
1669 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001670 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, Depth, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001671
1672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001673}
1674
Sanjay Patelaee84212014-11-04 16:27:42 +00001675/// Determine whether the sign bit is known to be zero or one.
1676/// Convenience wrapper around computeKnownBits.
Hal Finkel60db0582014-09-07 18:57:58 +00001677void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001678 unsigned Depth, const Query &Q) {
1679 unsigned BitWidth = getBitWidth(V->getType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001680 if (!BitWidth) {
1681 KnownZero = false;
1682 KnownOne = false;
1683 return;
1684 }
1685 APInt ZeroBits(BitWidth, 0);
1686 APInt OneBits(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001687 computeKnownBits(V, ZeroBits, OneBits, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001688 KnownOne = OneBits[BitWidth - 1];
1689 KnownZero = ZeroBits[BitWidth - 1];
1690}
1691
Sanjay Patelaee84212014-11-04 16:27:42 +00001692/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001693/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001694/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001695/// types and vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001696bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001697 const Query &Q) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001698 if (Constant *C = dyn_cast<Constant>(V)) {
1699 if (C->isNullValue())
1700 return OrZero;
1701 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1702 return CI->getValue().isPowerOf2();
1703 // TODO: Handle vector constants.
1704 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001705
1706 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1707 // it is shifted off the end then the result is undefined.
1708 if (match(V, m_Shl(m_One(), m_Value())))
1709 return true;
1710
1711 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1712 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands4b397fc2011-02-01 08:50:33 +00001713 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001714 return true;
1715
1716 // The remaining tests are all recursive, so bail out if we hit the limit.
1717 if (Depth++ == MaxDepth)
1718 return false;
1719
Craig Topper9f008862014-04-15 04:59:12 +00001720 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001721 // A shift left or a logical shift right of a power of two is a power of two
1722 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001723 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001724 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001725 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001726
Duncan Sandsd3951082011-01-25 09:38:29 +00001727 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001728 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001729
1730 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001731 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1732 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001733
Duncan Sandsba286d72011-10-26 20:55:21 +00001734 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1735 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001736 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1737 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001738 return true;
1739 // X & (-X) is always a power of two or zero.
1740 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1741 return true;
1742 return false;
1743 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001744
David Majnemerb7d54092013-07-30 21:01:36 +00001745 // Adding a power-of-two or zero to the same power-of-two or zero yields
1746 // either the original power-of-two, a larger power-of-two or zero.
1747 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1748 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1749 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1750 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1751 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001752 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001753 return true;
1754 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1755 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001756 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001757 return true;
1758
1759 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1760 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001761 computeKnownBits(X, LHSZeroBits, LHSOneBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001762
1763 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001764 computeKnownBits(Y, RHSZeroBits, RHSOneBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001765 // If i8 V is a power of two or zero:
1766 // ZeroBits: 1 1 1 0 1 1 1 1
1767 // ~ZeroBits: 0 0 0 1 0 0 0 0
1768 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1769 // If OrZero isn't set, we cannot give back a zero result.
1770 // Make sure either the LHS or RHS has a bit set.
1771 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1772 return true;
1773 }
1774 }
David Majnemerbeab5672013-05-18 19:30:37 +00001775
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001776 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001777 // is a power of two only if the first operand is a power of two and not
1778 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001779 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1780 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001781 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001782 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001783 }
1784
Duncan Sandsd3951082011-01-25 09:38:29 +00001785 return false;
1786}
1787
Chandler Carruth80d3e562012-12-07 02:08:58 +00001788/// \brief Test whether a GEP's result is known to be non-null.
1789///
1790/// Uses properties inherent in a GEP to try to determine whether it is known
1791/// to be non-null.
1792///
1793/// Currently this routine does not support vector GEPs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001794static bool isGEPKnownNonNull(GEPOperator *GEP, unsigned Depth,
1795 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001796 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1797 return false;
1798
1799 // FIXME: Support vector-GEPs.
1800 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1801
1802 // If the base pointer is non-null, we cannot walk to a null address with an
1803 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001804 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001805 return true;
1806
Chandler Carruth80d3e562012-12-07 02:08:58 +00001807 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1808 // If so, then the GEP cannot produce a null pointer, as doing so would
1809 // inherently violate the inbounds contract within address space zero.
1810 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1811 GTI != GTE; ++GTI) {
1812 // Struct types are easy -- they must always be indexed by a constant.
1813 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1814 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1815 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001816 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001817 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1818 if (ElementOffset > 0)
1819 return true;
1820 continue;
1821 }
1822
1823 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001824 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001825 continue;
1826
1827 // Fast path the constant operand case both for efficiency and so we don't
1828 // increment Depth when just zipping down an all-constant GEP.
1829 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1830 if (!OpC->isZero())
1831 return true;
1832 continue;
1833 }
1834
1835 // We post-increment Depth here because while isKnownNonZero increments it
1836 // as well, when we pop back up that increment won't persist. We don't want
1837 // to recurse 10k times just because we have 10k GEP operands. We don't
1838 // bail completely out because we want to handle constant GEPs regardless
1839 // of depth.
1840 if (Depth++ >= MaxDepth)
1841 continue;
1842
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001843 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001844 return true;
1845 }
1846
1847 return false;
1848}
1849
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001850/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1851/// ensure that the value it's attached to is never Value? 'RangeType' is
1852/// is the type of the value described by the range.
1853static bool rangeMetadataExcludesValue(MDNode* Ranges,
1854 const APInt& Value) {
1855 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1856 assert(NumRanges >= 1);
1857 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001858 ConstantInt *Lower =
1859 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1860 ConstantInt *Upper =
1861 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001862 ConstantRange Range(Lower->getValue(), Upper->getValue());
1863 if (Range.contains(Value))
1864 return false;
1865 }
1866 return true;
1867}
1868
Sanjay Patelaee84212014-11-04 16:27:42 +00001869/// Return true if the given value is known to be non-zero when defined.
1870/// For vectors return true if every element is known to be non-zero when
1871/// defined. Supports values with integer or pointer type and vectors of
1872/// integers.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001873bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001874 if (Constant *C = dyn_cast<Constant>(V)) {
1875 if (C->isNullValue())
1876 return false;
1877 if (isa<ConstantInt>(C))
1878 // Must be non-zero due to null test above.
1879 return true;
1880 // TODO: Handle vectors
1881 return false;
1882 }
1883
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001884 if (Instruction* I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001885 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001886 // If the possible ranges don't contain zero, then the value is
1887 // definitely non-zero.
1888 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1889 const APInt ZeroValue(Ty->getBitWidth(), 0);
1890 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1891 return true;
1892 }
1893 }
1894 }
1895
Duncan Sandsd3951082011-01-25 09:38:29 +00001896 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001897 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001898 return false;
1899
Chandler Carruth80d3e562012-12-07 02:08:58 +00001900 // Check for pointer simplifications.
1901 if (V->getType()->isPointerTy()) {
Manman Ren12171122013-03-18 21:23:25 +00001902 if (isKnownNonNull(V))
1903 return true;
Chandler Carruth80d3e562012-12-07 02:08:58 +00001904 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001905 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001906 return true;
1907 }
1908
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001909 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001910
1911 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001912 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001913 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001914 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001915
1916 // ext X != 0 if X != 0.
1917 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001918 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001919
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001920 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001921 // if the lowest bit is shifted off the end.
1922 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001923 // shl nuw can't remove any non-zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001924 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001925 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001926 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001927
Duncan Sandsd3951082011-01-25 09:38:29 +00001928 APInt KnownZero(BitWidth, 0);
1929 APInt KnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001930 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001931 if (KnownOne[0])
1932 return true;
1933 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001934 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001935 // defined if the sign bit is shifted off the end.
1936 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001937 // shr exact can only shift out zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001938 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001939 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001940 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001941
Duncan Sandsd3951082011-01-25 09:38:29 +00001942 bool XKnownNonNegative, XKnownNegative;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001943 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001944 if (XKnownNegative)
1945 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001946
1947 // If the shifter operand is a constant, and all of the bits shifted
1948 // out are known to be zero, and X is known non-zero then at least one
1949 // non-zero bit must remain.
1950 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
1951 APInt KnownZero(BitWidth, 0);
1952 APInt KnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001953 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001954
1955 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1956 // Is there a known one in the portion not shifted out?
1957 if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal)
1958 return true;
1959 // Are all the bits to be shifted out known zero?
1960 if (KnownZero.countTrailingOnes() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001961 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001962 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001963 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001964 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001965 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001966 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001967 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001968 // X + Y.
1969 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1970 bool XKnownNonNegative, XKnownNegative;
1971 bool YKnownNonNegative, YKnownNegative;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001972 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1973 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001974
1975 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001976 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001977 if (XKnownNonNegative && YKnownNonNegative)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001978 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001979 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001980
1981 // If X and Y are both negative (as signed values) then their sum is not
1982 // zero unless both X and Y equal INT_MIN.
1983 if (BitWidth && XKnownNegative && YKnownNegative) {
1984 APInt KnownZero(BitWidth, 0);
1985 APInt KnownOne(BitWidth, 0);
1986 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1987 // The sign bit of X is set. If some other bit is set then X is not equal
1988 // to INT_MIN.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001989 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001990 if ((KnownOne & Mask) != 0)
1991 return true;
1992 // The sign bit of Y is set. If some other bit is set then Y is not equal
1993 // to INT_MIN.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001994 computeKnownBits(Y, KnownZero, KnownOne, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001995 if ((KnownOne & Mask) != 0)
1996 return true;
1997 }
1998
1999 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00002000 if (XKnownNonNegative &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002001 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002002 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00002003 if (YKnownNonNegative &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002004 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002005 return true;
2006 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002007 // X * Y.
2008 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2009 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2010 // If X and Y are non-zero then so is X * Y as long as the multiplication
2011 // does not overflow.
2012 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002013 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002014 return true;
2015 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002016 // (C ? X : Y) != 0 if X != 0 and Y != 0.
2017 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002018 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2019 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002020 return true;
2021 }
James Molloy897048b2015-09-29 14:08:45 +00002022 // PHI
2023 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2024 // Try and detect a recurrence that monotonically increases from a
2025 // starting value, as these are common as induction variables.
2026 if (PN->getNumIncomingValues() == 2) {
2027 Value *Start = PN->getIncomingValue(0);
2028 Value *Induction = PN->getIncomingValue(1);
2029 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2030 std::swap(Start, Induction);
2031 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2032 if (!C->isZero() && !C->isNegative()) {
2033 ConstantInt *X;
2034 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2035 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2036 !X->isNegative())
2037 return true;
2038 }
2039 }
2040 }
Jun Bum Limca832662016-02-01 17:03:07 +00002041 // Check if all incoming values are non-zero constant.
2042 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
2043 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
2044 });
2045 if (AllNonZeroConstants)
2046 return true;
James Molloy897048b2015-09-29 14:08:45 +00002047 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002048
2049 if (!BitWidth) return false;
2050 APInt KnownZero(BitWidth, 0);
2051 APInt KnownOne(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002052 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002053 return KnownOne != 0;
2054}
2055
James Molloy1d88d6f2015-10-22 13:18:42 +00002056/// Return true if V2 == V1 + X, where X is known non-zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002057static bool isAddOfNonZero(Value *V1, Value *V2, const Query &Q) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002058 BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2059 if (!BO || BO->getOpcode() != Instruction::Add)
2060 return false;
2061 Value *Op = nullptr;
2062 if (V2 == BO->getOperand(0))
2063 Op = BO->getOperand(1);
2064 else if (V2 == BO->getOperand(1))
2065 Op = BO->getOperand(0);
2066 else
2067 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002068 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002069}
2070
2071/// Return true if it is known that V1 != V2.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002072static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002073 if (V1->getType()->isVectorTy() || V1 == V2)
2074 return false;
2075 if (V1->getType() != V2->getType())
2076 // We can't look through casts yet.
2077 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002078 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002079 return true;
2080
2081 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
2082 // Are any known bits in V1 contradictory to known bits in V2? If V1
2083 // has a known zero where V2 has a known one, they must not be equal.
2084 auto BitWidth = Ty->getBitWidth();
2085 APInt KnownZero1(BitWidth, 0);
2086 APInt KnownOne1(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002087 computeKnownBits(V1, KnownZero1, KnownOne1, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002088 APInt KnownZero2(BitWidth, 0);
2089 APInt KnownOne2(BitWidth, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002090 computeKnownBits(V2, KnownZero2, KnownOne2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002091
2092 auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1);
2093 if (OppositeBits.getBoolValue())
2094 return true;
2095 }
2096 return false;
2097}
2098
Sanjay Patelaee84212014-11-04 16:27:42 +00002099/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2100/// simplify operations downstream. Mask is known to be zero for bits that V
2101/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002102///
2103/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002104/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002105/// where V is a vector, the mask, known zero, and known one values are the
2106/// same width as the vector element, and the bit is set only if it is true
2107/// for all of the elements in the vector.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002108bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
2109 const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +00002110 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002111 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002112 return (KnownZero & Mask) == Mask;
2113}
2114
2115
2116
Sanjay Patelaee84212014-11-04 16:27:42 +00002117/// Return the number of times the sign bit of the register is replicated into
2118/// the other bits. We know that at least 1 bit is always equal to the sign bit
2119/// (itself), but other cases can give us information. For example, immediately
2120/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2121/// other, so we return 3.
Chris Lattner965c7692008-06-02 01:18:21 +00002122///
2123/// 'Op' must have a scalar integer type.
2124///
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002125unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q) {
2126 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002127 unsigned Tmp, Tmp2;
2128 unsigned FirstAnswer = 1;
2129
Jay Foada0653a32014-05-14 21:14:37 +00002130 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002131 // below.
2132
Chris Lattner965c7692008-06-02 01:18:21 +00002133 if (Depth == 6)
2134 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002135
Dan Gohman80ca01c2009-07-17 20:47:02 +00002136 Operator *U = dyn_cast<Operator>(V);
2137 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002138 default: break;
2139 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002140 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002141 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002142
Nadav Rotemc99a3872015-03-06 00:23:58 +00002143 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002144 const APInt *Denominator;
2145 // sdiv X, C -> adds log(C) sign bits.
2146 if (match(U->getOperand(1), m_APInt(Denominator))) {
2147
2148 // Ignore non-positive denominator.
2149 if (!Denominator->isStrictlyPositive())
2150 break;
2151
2152 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002153 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002154
2155 // Add floor(log(C)) bits to the numerator bits.
2156 return std::min(TyBits, NumBits + Denominator->logBase2());
2157 }
2158 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002159 }
2160
2161 case Instruction::SRem: {
2162 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002163 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2164 // positive constant. This let us put a lower bound on the number of sign
2165 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002166 if (match(U->getOperand(1), m_APInt(Denominator))) {
2167
2168 // Ignore non-positive denominator.
2169 if (!Denominator->isStrictlyPositive())
2170 break;
2171
2172 // Calculate the incoming numerator bits. SRem by a positive constant
2173 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002174 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002175 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002176
2177 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002178 // denominator. Given that the denominator is positive, there are two
2179 // cases:
2180 //
2181 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2182 // (1 << ceilLogBase2(C)).
2183 //
2184 // 2. the numerator is negative. Then the result range is (-C,0] and
2185 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2186 //
2187 // Thus a lower bound on the number of sign bits is `TyBits -
2188 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002189
Sanjoy Dase561fee2015-03-25 22:33:53 +00002190 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002191 return std::max(NumrBits, ResBits);
2192 }
2193 break;
2194 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002195
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002196 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002197 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002198 // ashr X, C -> adds C sign bits. Vectors too.
2199 const APInt *ShAmt;
2200 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2201 Tmp += ShAmt->getZExtValue();
Chris Lattner965c7692008-06-02 01:18:21 +00002202 if (Tmp > TyBits) Tmp = TyBits;
2203 }
2204 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002205 }
2206 case Instruction::Shl: {
2207 const APInt *ShAmt;
2208 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002209 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002210 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002211 Tmp2 = ShAmt->getZExtValue();
2212 if (Tmp2 >= TyBits || // Bad shift.
2213 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2214 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002215 }
2216 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002217 }
Chris Lattner965c7692008-06-02 01:18:21 +00002218 case Instruction::And:
2219 case Instruction::Or:
2220 case Instruction::Xor: // NOT is handled here.
2221 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002222 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002223 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002224 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002225 FirstAnswer = std::min(Tmp, Tmp2);
2226 // We computed what we know about the sign bits as our first
2227 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002228 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002229 }
2230 break;
2231
2232 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002233 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002234 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002235 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002236 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002237
Chris Lattner965c7692008-06-02 01:18:21 +00002238 case Instruction::Add:
2239 // Add can have at most one carry bit. Thus we know that the output
2240 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002241 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002242 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002243
Chris Lattner965c7692008-06-02 01:18:21 +00002244 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002245 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002246 if (CRHS->isAllOnesValue()) {
2247 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002248 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002249
Chris Lattner965c7692008-06-02 01:18:21 +00002250 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2251 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002252 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002253 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002254
Chris Lattner965c7692008-06-02 01:18:21 +00002255 // If we are subtracting one from a positive number, there is no carry
2256 // out of the result.
2257 if (KnownZero.isNegative())
2258 return Tmp;
2259 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002260
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002261 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002262 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002263 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002264
Chris Lattner965c7692008-06-02 01:18:21 +00002265 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002266 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002267 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002268
Chris Lattner965c7692008-06-02 01:18:21 +00002269 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002270 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002271 if (CLHS->isNullValue()) {
2272 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002273 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002274 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2275 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002276 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002277 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002278
Chris Lattner965c7692008-06-02 01:18:21 +00002279 // If the input is known to be positive (the sign bit is known clear),
2280 // the output of the NEG has the same number of sign bits as the input.
2281 if (KnownZero.isNegative())
2282 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002283
Chris Lattner965c7692008-06-02 01:18:21 +00002284 // Otherwise, we treat this like a SUB.
2285 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002286
Chris Lattner965c7692008-06-02 01:18:21 +00002287 // Sub can have at most one carry bit. Thus we know that the output
2288 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002289 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002290 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002291 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002292
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002293 case Instruction::PHI: {
2294 PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002295 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002296 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002297 if (NumIncomingValues > 4) break;
2298 // Unreachable blocks may have zero-operand PHI nodes.
2299 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002300
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002301 // Take the minimum of all incoming values. This can't infinitely loop
2302 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002303 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002304 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002305 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002306 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002307 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002308 }
2309 return Tmp;
2310 }
2311
Chris Lattner965c7692008-06-02 01:18:21 +00002312 case Instruction::Trunc:
2313 // FIXME: it's tricky to do anything useful for this, but it is an important
2314 // case for targets like X86.
2315 break;
2316 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002317
Chris Lattner965c7692008-06-02 01:18:21 +00002318 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2319 // use this information.
2320 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002321 APInt Mask;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002322 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002323
Chris Lattner965c7692008-06-02 01:18:21 +00002324 if (KnownZero.isNegative()) { // sign bit is 0
2325 Mask = KnownZero;
2326 } else if (KnownOne.isNegative()) { // sign bit is 1;
2327 Mask = KnownOne;
2328 } else {
2329 // Nothing known.
2330 return FirstAnswer;
2331 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002332
Chris Lattner965c7692008-06-02 01:18:21 +00002333 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2334 // the number of identical bits in the top of the input value.
2335 Mask = ~Mask;
2336 Mask <<= Mask.getBitWidth()-TyBits;
2337 // Return # leading zeros. We use 'min' here in case Val was zero before
2338 // shifting. We don't want to return '64' as for an i32 "0".
2339 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2340}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002341
Sanjay Patelaee84212014-11-04 16:27:42 +00002342/// This function computes the integer multiple of Base that equals V.
2343/// If successful, it returns true and returns the multiple in
2344/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002345/// through SExt instructions only if LookThroughSExt is true.
2346bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002347 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002348 const unsigned MaxDepth = 6;
2349
Dan Gohman6a976bb2009-11-18 00:58:27 +00002350 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002351 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002352 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002353
Chris Lattner229907c2011-07-18 04:54:35 +00002354 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002355
Dan Gohman6a976bb2009-11-18 00:58:27 +00002356 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002357
2358 if (Base == 0)
2359 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002360
Victor Hernandez47444882009-11-10 08:28:35 +00002361 if (Base == 1) {
2362 Multiple = V;
2363 return true;
2364 }
2365
2366 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2367 Constant *BaseVal = ConstantInt::get(T, Base);
2368 if (CO && CO == BaseVal) {
2369 // Multiple is 1.
2370 Multiple = ConstantInt::get(T, 1);
2371 return true;
2372 }
2373
2374 if (CI && CI->getZExtValue() % Base == 0) {
2375 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002376 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002377 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002378
Victor Hernandez47444882009-11-10 08:28:35 +00002379 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002380
Victor Hernandez47444882009-11-10 08:28:35 +00002381 Operator *I = dyn_cast<Operator>(V);
2382 if (!I) return false;
2383
2384 switch (I->getOpcode()) {
2385 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002386 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002387 if (!LookThroughSExt) return false;
2388 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002389 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002390 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2391 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002392 case Instruction::Shl:
2393 case Instruction::Mul: {
2394 Value *Op0 = I->getOperand(0);
2395 Value *Op1 = I->getOperand(1);
2396
2397 if (I->getOpcode() == Instruction::Shl) {
2398 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2399 if (!Op1CI) return false;
2400 // Turn Op0 << Op1 into Op0 * 2^Op1
2401 APInt Op1Int = Op1CI->getValue();
2402 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002403 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002404 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002405 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002406 }
2407
Craig Topper9f008862014-04-15 04:59:12 +00002408 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002409 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2410 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2411 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002412 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002413 MulC->getType()->getPrimitiveSizeInBits())
2414 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002415 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002416 MulC->getType()->getPrimitiveSizeInBits())
2417 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002418
Chris Lattner72d283c2010-09-05 17:20:46 +00002419 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2420 Multiple = ConstantExpr::getMul(MulC, Op1C);
2421 return true;
2422 }
Victor Hernandez47444882009-11-10 08:28:35 +00002423
2424 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2425 if (Mul0CI->getValue() == 1) {
2426 // V == Base * Op1, so return Op1
2427 Multiple = Op1;
2428 return true;
2429 }
2430 }
2431
Craig Topper9f008862014-04-15 04:59:12 +00002432 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002433 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2434 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2435 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002436 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002437 MulC->getType()->getPrimitiveSizeInBits())
2438 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002439 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002440 MulC->getType()->getPrimitiveSizeInBits())
2441 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002442
Chris Lattner72d283c2010-09-05 17:20:46 +00002443 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2444 Multiple = ConstantExpr::getMul(MulC, Op0C);
2445 return true;
2446 }
Victor Hernandez47444882009-11-10 08:28:35 +00002447
2448 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2449 if (Mul1CI->getValue() == 1) {
2450 // V == Base * Op0, so return Op0
2451 Multiple = Op0;
2452 return true;
2453 }
2454 }
Victor Hernandez47444882009-11-10 08:28:35 +00002455 }
2456 }
2457
2458 // We could not determine if V is a multiple of Base.
2459 return false;
2460}
2461
Sanjay Patelaee84212014-11-04 16:27:42 +00002462/// Return true if we can prove that the specified FP value is never equal to
2463/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002464///
2465/// NOTE: this function will need to be revisited when we support non-default
2466/// rounding modes!
2467///
2468bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2469 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2470 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002471
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002472 // FIXME: Magic number! At the least, this should be given a name because it's
2473 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2474 // expose it as a parameter, so it can be used for testing / experimenting.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002475 if (Depth == 6)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002476 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002477
Dan Gohman80ca01c2009-07-17 20:47:02 +00002478 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002479 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002480
2481 // Check if the nsz fast-math flag is set
2482 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2483 if (FPO->hasNoSignedZeros())
2484 return true;
2485
Chris Lattnera12a6de2008-06-02 01:29:46 +00002486 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002487 if (I->getOpcode() == Instruction::FAdd)
2488 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2489 if (CFP->isNullValue())
2490 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002491
Chris Lattnera12a6de2008-06-02 01:29:46 +00002492 // sitofp and uitofp turn into +0.0 for zero.
2493 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2494 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002495
Chris Lattnera12a6de2008-06-02 01:29:46 +00002496 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2497 // sqrt(-0.0) = -0.0, no other negative results are possible.
2498 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif1abbde32010-06-23 23:38:07 +00002499 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Craig Topper1bef2c82012-12-22 19:15:35 +00002500
Chris Lattnera12a6de2008-06-02 01:29:46 +00002501 if (const CallInst *CI = dyn_cast<CallInst>(I))
2502 if (const Function *F = CI->getCalledFunction()) {
2503 if (F->isDeclaration()) {
Daniel Dunbarca414c72009-07-26 08:34:35 +00002504 // abs(x) != -0.0
2505 if (F->getName() == "abs") return true;
Dale Johannesenf6a987b2009-09-25 20:54:50 +00002506 // fabs[lf](x) != -0.0
2507 if (F->getName() == "fabs") return true;
2508 if (F->getName() == "fabsf") return true;
2509 if (F->getName() == "fabsl") return true;
2510 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2511 F->getName() == "sqrtl")
Gabor Greif1abbde32010-06-23 23:38:07 +00002512 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattnera12a6de2008-06-02 01:29:46 +00002513 }
2514 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002515
Chris Lattnera12a6de2008-06-02 01:29:46 +00002516 return false;
2517}
2518
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002519bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2520 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2521 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2522
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002523 // FIXME: Magic number! At the least, this should be given a name because it's
2524 // used similarly in CannotBeNegativeZero(). A better fix may be to
2525 // expose it as a parameter, so it can be used for testing / experimenting.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002526 if (Depth == 6)
2527 return false; // Limit search depth.
2528
2529 const Operator *I = dyn_cast<Operator>(V);
2530 if (!I) return false;
2531
2532 switch (I->getOpcode()) {
2533 default: break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002534 // Unsigned integers are always nonnegative.
2535 case Instruction::UIToFP:
2536 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002537 case Instruction::FMul:
2538 // x*x is always non-negative or a NaN.
2539 if (I->getOperand(0) == I->getOperand(1))
2540 return true;
2541 // Fall through
2542 case Instruction::FAdd:
2543 case Instruction::FDiv:
2544 case Instruction::FRem:
2545 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2546 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002547 case Instruction::Select:
2548 return CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1) &&
2549 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002550 case Instruction::FPExt:
2551 case Instruction::FPTrunc:
2552 // Widening/narrowing never change sign.
2553 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2554 case Instruction::Call:
2555 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2556 switch (II->getIntrinsicID()) {
2557 default: break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002558 case Intrinsic::maxnum:
2559 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) ||
2560 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2561 case Intrinsic::minnum:
2562 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2563 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002564 case Intrinsic::exp:
2565 case Intrinsic::exp2:
2566 case Intrinsic::fabs:
2567 case Intrinsic::sqrt:
2568 return true;
2569 case Intrinsic::powi:
2570 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2571 // powi(x,n) is non-negative if n is even.
2572 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2573 return true;
2574 }
2575 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2576 case Intrinsic::fma:
2577 case Intrinsic::fmuladd:
2578 // x*x+y is non-negative if y is non-negative.
2579 return I->getOperand(0) == I->getOperand(1) &&
2580 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2581 }
2582 break;
2583 }
2584 return false;
2585}
2586
Sanjay Patelaee84212014-11-04 16:27:42 +00002587/// If the specified value can be set by repeating the same byte in memory,
2588/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002589/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2590/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2591/// byte store (e.g. i16 0x1234), return null.
2592Value *llvm::isBytewiseValue(Value *V) {
2593 // All byte-wide stores are splatable, even of arbitrary variables.
2594 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002595
2596 // Handle 'null' ConstantArrayZero etc.
2597 if (Constant *C = dyn_cast<Constant>(V))
2598 if (C->isNullValue())
2599 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002600
Chris Lattner9cb10352010-12-26 20:15:01 +00002601 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002602 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002603 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2604 if (CFP->getType()->isFloatTy())
2605 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2606 if (CFP->getType()->isDoubleTy())
2607 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2608 // Don't handle long double formats, which have strange constraints.
2609 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002610
Benjamin Kramer17d90152015-02-07 19:29:02 +00002611 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002612 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002613 if (CI->getBitWidth() % 8 == 0) {
2614 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002615
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002616 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002617 return nullptr;
2618 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002619 }
2620 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002621
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002622 // A ConstantDataArray/Vector is splatable if all its members are equal and
2623 // also splatable.
2624 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2625 Value *Elt = CA->getElementAsConstant(0);
2626 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002627 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002628 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002629
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002630 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2631 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002632 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002633
Chris Lattner9cb10352010-12-26 20:15:01 +00002634 return Val;
2635 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002636
Chris Lattner9cb10352010-12-26 20:15:01 +00002637 // Conceptually, we could handle things like:
2638 // %a = zext i8 %X to i16
2639 // %b = shl i16 %a, 8
2640 // %c = or i16 %a, %b
2641 // but until there is an example that actually needs this, it doesn't seem
2642 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002643 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002644}
2645
2646
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002647// This is the recursive version of BuildSubAggregate. It takes a few different
2648// arguments. Idxs is the index within the nested struct From that we are
2649// looking at now (which is of type IndexedType). IdxSkip is the number of
2650// indices from Idxs that should be left out when inserting into the resulting
2651// struct. To is the result struct built so far, new insertvalue instructions
2652// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002653static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002654 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002655 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002656 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002657 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002658 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002659 // Save the original To argument so we can modify it
2660 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002661 // General case, the type indexed by Idxs is a struct
2662 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2663 // Process each struct element recursively
2664 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002665 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002666 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002667 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002668 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002669 if (!To) {
2670 // Couldn't find any inserted value for this index? Cleanup
2671 while (PrevTo != OrigTo) {
2672 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2673 PrevTo = Del->getAggregateOperand();
2674 Del->eraseFromParent();
2675 }
2676 // Stop processing elements
2677 break;
2678 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002679 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002680 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002681 if (To)
2682 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002683 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002684 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2685 // the struct's elements had a value that was inserted directly. In the latter
2686 // case, perhaps we can't determine each of the subelements individually, but
2687 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002688
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002689 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002690 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002691
2692 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002693 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002694
2695 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002696 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002697 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002698}
2699
2700// This helper takes a nested struct and extracts a part of it (which is again a
2701// struct) into a new value. For example, given the struct:
2702// { a, { b, { c, d }, e } }
2703// and the indices "1, 1" this returns
2704// { c, d }.
2705//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002706// It does this by inserting an insertvalue for each element in the resulting
2707// struct, as opposed to just inserting a single struct. This will only work if
2708// each of the elements of the substruct are known (ie, inserted into From by an
2709// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002710//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002711// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002712static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002713 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002714 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002715 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002716 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002717 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002718 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002719 unsigned IdxSkip = Idxs.size();
2720
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002721 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002722}
2723
Sanjay Patelaee84212014-11-04 16:27:42 +00002724/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002725/// the scalar value indexed is already around as a register, for example if it
2726/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002727///
2728/// If InsertBefore is not null, this function will duplicate (modified)
2729/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002730Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2731 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002732 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002733 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002734 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002735 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002736 // We have indices, so V should have an indexable type.
2737 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2738 "Not looking at a struct or array?");
2739 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2740 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002741
Chris Lattner67058832012-01-25 06:48:06 +00002742 if (Constant *C = dyn_cast<Constant>(V)) {
2743 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002744 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002745 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2746 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002747
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002748 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002749 // Loop the indices for the insertvalue instruction in parallel with the
2750 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002751 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002752 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2753 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002754 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002755 // We can't handle this without inserting insertvalues
2756 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002757 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002758
2759 // The requested index identifies a part of a nested aggregate. Handle
2760 // this specially. For example,
2761 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2762 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2763 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2764 // This can be changed into
2765 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2766 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2767 // which allows the unused 0,0 element from the nested struct to be
2768 // removed.
2769 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2770 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002771 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002772
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002773 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002774 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002775 // looking for, then.
2776 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002777 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002778 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002779 }
2780 // If we end up here, the indices of the insertvalue match with those
2781 // requested (though possibly only partially). Now we recursively look at
2782 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002783 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002784 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002785 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002786 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002787
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002788 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002789 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002790 // something else, we can extract from that something else directly instead.
2791 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002792
2793 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002794 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002795 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002796 SmallVector<unsigned, 5> Idxs;
2797 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002798 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002799 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002800
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002801 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002802 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002803
Craig Topper1bef2c82012-12-22 19:15:35 +00002804 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002805 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002806
Jay Foad57aa6362011-07-13 10:26:04 +00002807 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002808 }
2809 // Otherwise, we don't know (such as, extracting from a function return value
2810 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002811 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002812}
Evan Chengda3db112008-06-30 07:31:25 +00002813
Sanjay Patelaee84212014-11-04 16:27:42 +00002814/// Analyze the specified pointer to see if it can be expressed as a base
2815/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002816Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002817 const DataLayout &DL) {
2818 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002819 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002820
2821 // We walk up the defs but use a visited set to handle unreachable code. In
2822 // that case, we stop after accumulating the cycle once (not that it
2823 // matters).
2824 SmallPtrSet<Value *, 16> Visited;
2825 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002826 if (Ptr->getType()->isVectorTy())
2827 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002828
Nuno Lopes368c4d02012-12-31 20:48:35 +00002829 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002830 APInt GEPOffset(BitWidth, 0);
2831 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2832 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002833
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002834 ByteOffset += GEPOffset;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002835
Nuno Lopes368c4d02012-12-31 20:48:35 +00002836 Ptr = GEP->getPointerOperand();
Matt Arsenaultfd78d0c2014-07-14 22:39:22 +00002837 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2838 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002839 Ptr = cast<Operator>(Ptr)->getOperand(0);
2840 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2841 if (GA->mayBeOverridden())
2842 break;
2843 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002844 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002845 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002846 }
2847 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002848 Offset = ByteOffset.getSExtValue();
2849 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002850}
2851
2852
Sanjay Patelaee84212014-11-04 16:27:42 +00002853/// This function computes the length of a null-terminated C string pointed to
2854/// by V. If successful, it returns true and returns the string in Str.
2855/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002856bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2857 uint64_t Offset, bool TrimAtNul) {
2858 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002859
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002860 // Look through bitcast instructions and geps.
2861 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002862
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002863 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002864 // offset.
2865 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Chengda3db112008-06-30 07:31:25 +00002866 // Make sure the GEP has exactly three arguments.
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002867 if (GEP->getNumOperands() != 3)
2868 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002869
Evan Chengda3db112008-06-30 07:31:25 +00002870 // Make sure the index-ee is a pointer to array of i8.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002871 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Craig Topper9f008862014-04-15 04:59:12 +00002872 if (!AT || !AT->getElementType()->isIntegerTy(8))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002873 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002874
Evan Chengda3db112008-06-30 07:31:25 +00002875 // Check to make sure that the first operand of the GEP is an integer and
2876 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0b4df042010-04-14 22:20:45 +00002877 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Craig Topper9f008862014-04-15 04:59:12 +00002878 if (!FirstIdx || !FirstIdx->isZero())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002879 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002880
Evan Chengda3db112008-06-30 07:31:25 +00002881 // If the second index isn't a ConstantInt, then this is a variable index
2882 // into the array. If this occurs, we can't say anything meaningful about
2883 // the string.
2884 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002885 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002886 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002887 else
2888 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002889 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2890 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00002891 }
Nick Lewycky46209882011-10-20 00:34:35 +00002892
Evan Chengda3db112008-06-30 07:31:25 +00002893 // The GEP instruction, constant or instruction, must reference a global
2894 // variable that is a constant and is initialized. The referenced constant
2895 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002896 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002897 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002898 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002899
Nick Lewycky46209882011-10-20 00:34:35 +00002900 // Handle the all-zeros case
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002901 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00002902 // This is a degenerate case. The initializer is constant zero so the
2903 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002904 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002905 return true;
2906 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002907
Evan Chengda3db112008-06-30 07:31:25 +00002908 // Must be a Constant Array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002909 const ConstantDataArray *Array =
2910 dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00002911 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002912 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002913
Evan Chengda3db112008-06-30 07:31:25 +00002914 // Get the number of elements in the array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002915 uint64_t NumElts = Array->getType()->getArrayNumElements();
2916
2917 // Start out with the entire array in the StringRef.
2918 Str = Array->getAsString();
2919
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002920 if (Offset > NumElts)
2921 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002922
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002923 // Skip over 'offset' bytes.
2924 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00002925
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002926 if (TrimAtNul) {
2927 // Trim off the \0 and anything after it. If the array is not nul
2928 // terminated, we just return the whole end of string. The client may know
2929 // some other way that the string is length-bound.
2930 Str = Str.substr(0, Str.find('\0'));
2931 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002932 return true;
Evan Chengda3db112008-06-30 07:31:25 +00002933}
Eric Christopher4899cbc2010-03-05 06:58:57 +00002934
2935// These next two are very similar to the above, but also look through PHI
2936// nodes.
2937// TODO: See if we can integrate these two together.
2938
Sanjay Patelaee84212014-11-04 16:27:42 +00002939/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002940/// the specified pointer, return 'len+1'. If we can't, return 0.
Craig Topper71b7b682014-08-21 05:55:13 +00002941static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00002942 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002943 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00002944
2945 // If this is a PHI node, there are two cases: either we have already seen it
2946 // or we haven't.
2947 if (PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00002948 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00002949 return ~0ULL; // already in the set.
2950
2951 // If it was new, see if all the input strings are the same length.
2952 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00002953 for (Value *IncValue : PN->incoming_values()) {
2954 uint64_t Len = GetStringLengthH(IncValue, PHIs);
Eric Christopher4899cbc2010-03-05 06:58:57 +00002955 if (Len == 0) return 0; // Unknown length -> unknown.
2956
2957 if (Len == ~0ULL) continue;
2958
2959 if (Len != LenSoFar && LenSoFar != ~0ULL)
2960 return 0; // Disagree -> unknown.
2961 LenSoFar = Len;
2962 }
2963
2964 // Success, all agree.
2965 return LenSoFar;
2966 }
2967
2968 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2969 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2970 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2971 if (Len1 == 0) return 0;
2972 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2973 if (Len2 == 0) return 0;
2974 if (Len1 == ~0ULL) return Len2;
2975 if (Len2 == ~0ULL) return Len1;
2976 if (Len1 != Len2) return 0;
2977 return Len1;
2978 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002979
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002980 // Otherwise, see if we can read the string.
2981 StringRef StrData;
2982 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00002983 return 0;
2984
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002985 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00002986}
2987
Sanjay Patelaee84212014-11-04 16:27:42 +00002988/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002989/// the specified pointer, return 'len+1'. If we can't, return 0.
2990uint64_t llvm::GetStringLength(Value *V) {
2991 if (!V->getType()->isPointerTy()) return 0;
2992
2993 SmallPtrSet<PHINode*, 32> PHIs;
2994 uint64_t Len = GetStringLengthH(V, PHIs);
2995 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2996 // an empty string as a length.
2997 return Len == ~0ULL ? 1 : Len;
2998}
Dan Gohmana4fcd242010-12-15 20:02:24 +00002999
Adam Nemete2b885c2015-04-23 20:09:20 +00003000/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3001/// previous iteration of the loop was referring to the same object as \p PN.
3002static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
3003 // Find the loop-defined value.
3004 Loop *L = LI->getLoopFor(PN->getParent());
3005 if (PN->getNumIncomingValues() != 2)
3006 return true;
3007
3008 // Find the value from previous iteration.
3009 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3010 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3011 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3012 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3013 return true;
3014
3015 // If a new pointer is loaded in the loop, the pointer references a different
3016 // object in every iteration. E.g.:
3017 // for (i)
3018 // int *p = a[i];
3019 // ...
3020 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3021 if (!L->isLoopInvariant(Load->getPointerOperand()))
3022 return false;
3023 return true;
3024}
3025
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003026Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3027 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003028 if (!V->getType()->isPointerTy())
3029 return V;
3030 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3031 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3032 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003033 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3034 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003035 V = cast<Operator>(V)->getOperand(0);
3036 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3037 if (GA->mayBeOverridden())
3038 return V;
3039 V = GA->getAliasee();
3040 } else {
Dan Gohman05b18f12010-12-15 20:49:55 +00003041 // See if InstructionSimplify knows any relevant tricks.
3042 if (Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +00003043 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003044 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003045 V = Simplified;
3046 continue;
3047 }
3048
Dan Gohmana4fcd242010-12-15 20:02:24 +00003049 return V;
3050 }
3051 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3052 }
3053 return V;
3054}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003055
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003056void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003057 const DataLayout &DL, LoopInfo *LI,
3058 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003059 SmallPtrSet<Value *, 4> Visited;
3060 SmallVector<Value *, 4> Worklist;
3061 Worklist.push_back(V);
3062 do {
3063 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003064 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003065
David Blaikie70573dc2014-11-19 07:49:26 +00003066 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003067 continue;
3068
3069 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3070 Worklist.push_back(SI->getTrueValue());
3071 Worklist.push_back(SI->getFalseValue());
3072 continue;
3073 }
3074
3075 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003076 // If this PHI changes the underlying object in every iteration of the
3077 // loop, don't look through it. Consider:
3078 // int **A;
3079 // for (i) {
3080 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3081 // Curr = A[i];
3082 // *Prev, *Curr;
3083 //
3084 // Prev is tracking Curr one iteration behind so they refer to different
3085 // underlying objects.
3086 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3087 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003088 for (Value *IncValue : PN->incoming_values())
3089 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003090 continue;
3091 }
3092
3093 Objects.push_back(P);
3094 } while (!Worklist.empty());
3095}
3096
Sanjay Patelaee84212014-11-04 16:27:42 +00003097/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003098bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003099 for (const User *U : V->users()) {
3100 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003101 if (!II) return false;
3102
3103 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3104 II->getIntrinsicID() != Intrinsic::lifetime_end)
3105 return false;
3106 }
3107 return true;
3108}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003109
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003110bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3111 const Instruction *CtxI,
3112 const DominatorTree *DT,
3113 const TargetLibraryInfo *TLI) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003114 const Operator *Inst = dyn_cast<Operator>(V);
3115 if (!Inst)
3116 return false;
3117
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003118 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3119 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3120 if (C->canTrap())
3121 return false;
3122
3123 switch (Inst->getOpcode()) {
3124 default:
3125 return true;
3126 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003127 case Instruction::URem: {
3128 // x / y is undefined if y == 0.
3129 const APInt *V;
3130 if (match(Inst->getOperand(1), m_APInt(V)))
3131 return *V != 0;
3132 return false;
3133 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003134 case Instruction::SDiv:
3135 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003136 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003137 const APInt *Numerator, *Denominator;
3138 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3139 return false;
3140 // We cannot hoist this division if the denominator is 0.
3141 if (*Denominator == 0)
3142 return false;
3143 // It's safe to hoist if the denominator is not 0 or -1.
3144 if (*Denominator != -1)
3145 return true;
3146 // At this point we know that the denominator is -1. It is safe to hoist as
3147 // long we know that the numerator is not INT_MIN.
3148 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3149 return !Numerator->isMinSignedValue();
3150 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003151 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003152 }
3153 case Instruction::Load: {
3154 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003155 if (!LI->isUnordered() ||
3156 // Speculative load may create a race that did not exist in the source.
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003157 LI->getParent()->getParent()->hasFnAttribute(
3158 Attribute::SanitizeThread) ||
3159 // Speculative load may load data from dirty regions.
3160 LI->getParent()->getParent()->hasFnAttribute(
3161 Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003162 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003163 const DataLayout &DL = LI->getModule()->getDataLayout();
Artur Pilipenko34d8ba82015-08-17 15:54:26 +00003164 return isDereferenceableAndAlignedPointer(
3165 LI->getPointerOperand(), LI->getAlignment(), DL, CtxI, DT, TLI);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003166 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003167 case Instruction::Call: {
David Majnemer0a92f862015-08-28 21:13:39 +00003168 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3169 switch (II->getIntrinsicID()) {
3170 // These synthetic intrinsics have no side-effects and just mark
3171 // information about their operands.
3172 // FIXME: There are other no-op synthetic instructions that potentially
3173 // should be considered at least *safe* to speculate...
3174 case Intrinsic::dbg_declare:
3175 case Intrinsic::dbg_value:
3176 return true;
3177
3178 case Intrinsic::bswap:
3179 case Intrinsic::ctlz:
3180 case Intrinsic::ctpop:
3181 case Intrinsic::cttz:
3182 case Intrinsic::objectsize:
3183 case Intrinsic::sadd_with_overflow:
3184 case Intrinsic::smul_with_overflow:
3185 case Intrinsic::ssub_with_overflow:
3186 case Intrinsic::uadd_with_overflow:
3187 case Intrinsic::umul_with_overflow:
3188 case Intrinsic::usub_with_overflow:
3189 return true;
3190 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3191 // errno like libm sqrt would.
3192 case Intrinsic::sqrt:
3193 case Intrinsic::fma:
3194 case Intrinsic::fmuladd:
3195 case Intrinsic::fabs:
3196 case Intrinsic::minnum:
3197 case Intrinsic::maxnum:
3198 return true;
3199 // TODO: some fp intrinsics are marked as having the same error handling
3200 // as libm. They're safe to speculate when they won't error.
3201 // TODO: are convert_{from,to}_fp16 safe?
3202 // TODO: can we list target-specific intrinsics here?
3203 default: break;
3204 }
3205 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003206 return false; // The called function could have undefined behavior or
David Majnemer0a92f862015-08-28 21:13:39 +00003207 // side-effects, even if marked readnone nounwind.
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003208 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003209 case Instruction::VAArg:
3210 case Instruction::Alloca:
3211 case Instruction::Invoke:
3212 case Instruction::PHI:
3213 case Instruction::Store:
3214 case Instruction::Ret:
3215 case Instruction::Br:
3216 case Instruction::IndirectBr:
3217 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003218 case Instruction::Unreachable:
3219 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003220 case Instruction::AtomicRMW:
3221 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003222 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003223 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003224 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003225 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003226 case Instruction::CatchRet:
3227 case Instruction::CleanupPad:
3228 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003229 return false; // Misc instructions which have effects
3230 }
3231}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003232
Quentin Colombet6443cce2015-08-06 18:44:34 +00003233bool llvm::mayBeMemoryDependent(const Instruction &I) {
3234 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3235}
3236
Sanjay Patelaee84212014-11-04 16:27:42 +00003237/// Return true if we know that the specified value is never null.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003238bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
Chen Li0d043b52015-09-14 18:10:43 +00003239 assert(V->getType()->isPointerTy() && "V must be pointer type");
3240
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003241 // Alloca never returns null, malloc might.
3242 if (isa<AllocaInst>(V)) return true;
3243
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003244 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003245 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003246 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003247
Pete Cooper6b716212015-08-27 03:16:29 +00003248 // A global variable in address space 0 is non null unless extern weak.
3249 // Other address spaces may have null as a valid address for a global,
3250 // so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003251 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Pete Cooper6b716212015-08-27 03:16:29 +00003252 return !GV->hasExternalWeakLinkage() &&
3253 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003254
Philip Reamescdb72f32014-10-20 22:40:55 +00003255 // A Load tagged w/nonnull metadata is never null.
3256 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003257 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003258
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003259 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003260 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003261 return true;
3262
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003263 return false;
3264}
David Majnemer491331a2015-01-02 07:29:43 +00003265
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003266static bool isKnownNonNullFromDominatingCondition(const Value *V,
3267 const Instruction *CtxI,
3268 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003269 assert(V->getType()->isPointerTy() && "V must be pointer type");
3270
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003271 unsigned NumUsesExplored = 0;
3272 for (auto U : V->users()) {
3273 // Avoid massive lists
3274 if (NumUsesExplored >= DomConditionsMaxUses)
3275 break;
3276 NumUsesExplored++;
3277 // Consider only compare instructions uniquely controlling a branch
3278 const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
3279 if (!Cmp)
3280 continue;
3281
3282 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
3283 continue;
3284
3285 for (auto *CmpU : Cmp->users()) {
3286 const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
3287 if (!BI)
3288 continue;
3289
3290 assert(BI->isConditional() && "uses a comparison!");
3291
3292 BasicBlock *NonNullSuccessor = nullptr;
3293 CmpInst::Predicate Pred;
3294
3295 if (match(const_cast<ICmpInst*>(Cmp),
3296 m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
3297 if (Pred == ICmpInst::ICMP_EQ)
3298 NonNullSuccessor = BI->getSuccessor(1);
3299 else if (Pred == ICmpInst::ICMP_NE)
3300 NonNullSuccessor = BI->getSuccessor(0);
3301 }
3302
3303 if (NonNullSuccessor) {
3304 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3305 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3306 return true;
3307 }
3308 }
3309 }
3310
3311 return false;
3312}
3313
3314bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3315 const DominatorTree *DT, const TargetLibraryInfo *TLI) {
3316 if (isKnownNonNull(V, TLI))
3317 return true;
3318
3319 return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
3320}
3321
David Majnemer491331a2015-01-02 07:29:43 +00003322OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003323 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003324 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003325 const Instruction *CxtI,
3326 const DominatorTree *DT) {
3327 // Multiplying n * m significant bits yields a result of n + m significant
3328 // bits. If the total number of significant bits does not exceed the
3329 // result bit width (minus 1), there is no overflow.
3330 // This means if we have enough leading zero bits in the operands
3331 // we can guarantee that the result does not overflow.
3332 // Ref: "Hacker's Delight" by Henry Warren
3333 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3334 APInt LHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00003335 APInt LHSKnownOne(BitWidth, 0);
David Majnemer491331a2015-01-02 07:29:43 +00003336 APInt RHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00003337 APInt RHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003338 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3339 DT);
3340 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3341 DT);
David Majnemer491331a2015-01-02 07:29:43 +00003342 // Note that underestimating the number of zero bits gives a more
3343 // conservative answer.
3344 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3345 RHSKnownZero.countLeadingOnes();
3346 // First handle the easy case: if we have enough zero bits there's
3347 // definitely no overflow.
3348 if (ZeroBits >= BitWidth)
3349 return OverflowResult::NeverOverflows;
3350
3351 // Get the largest possible values for each operand.
3352 APInt LHSMax = ~LHSKnownZero;
3353 APInt RHSMax = ~RHSKnownZero;
3354
3355 // We know the multiply operation doesn't overflow if the maximum values for
3356 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003357 bool MaxOverflow;
3358 LHSMax.umul_ov(RHSMax, MaxOverflow);
3359 if (!MaxOverflow)
3360 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003361
David Majnemerc8a576b2015-01-02 07:29:47 +00003362 // We know it always overflows if multiplying the smallest possible values for
3363 // the operands also results in overflow.
3364 bool MinOverflow;
3365 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3366 if (MinOverflow)
3367 return OverflowResult::AlwaysOverflows;
3368
3369 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003370}
David Majnemer5310c1e2015-01-07 00:39:50 +00003371
3372OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003373 const DataLayout &DL,
David Majnemer5310c1e2015-01-07 00:39:50 +00003374 AssumptionCache *AC,
3375 const Instruction *CxtI,
3376 const DominatorTree *DT) {
3377 bool LHSKnownNonNegative, LHSKnownNegative;
3378 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3379 AC, CxtI, DT);
3380 if (LHSKnownNonNegative || LHSKnownNegative) {
3381 bool RHSKnownNonNegative, RHSKnownNegative;
3382 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3383 AC, CxtI, DT);
3384
3385 if (LHSKnownNegative && RHSKnownNegative) {
3386 // The sign bit is set in both cases: this MUST overflow.
3387 // Create a simple add instruction, and insert it into the struct.
3388 return OverflowResult::AlwaysOverflows;
3389 }
3390
3391 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3392 // The sign bit is clear in both cases: this CANNOT overflow.
3393 // Create a simple add instruction, and insert it into the struct.
3394 return OverflowResult::NeverOverflows;
3395 }
3396 }
3397
3398 return OverflowResult::MayOverflow;
3399}
James Molloy71b91c22015-05-11 14:42:20 +00003400
Jingyue Wu10fcea52015-08-20 18:27:04 +00003401static OverflowResult computeOverflowForSignedAdd(
3402 Value *LHS, Value *RHS, AddOperator *Add, const DataLayout &DL,
3403 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) {
3404 if (Add && Add->hasNoSignedWrap()) {
3405 return OverflowResult::NeverOverflows;
3406 }
3407
3408 bool LHSKnownNonNegative, LHSKnownNegative;
3409 bool RHSKnownNonNegative, RHSKnownNegative;
3410 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3411 AC, CxtI, DT);
3412 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3413 AC, CxtI, DT);
3414
3415 if ((LHSKnownNonNegative && RHSKnownNegative) ||
3416 (LHSKnownNegative && RHSKnownNonNegative)) {
3417 // The sign bits are opposite: this CANNOT overflow.
3418 return OverflowResult::NeverOverflows;
3419 }
3420
3421 // The remaining code needs Add to be available. Early returns if not so.
3422 if (!Add)
3423 return OverflowResult::MayOverflow;
3424
3425 // If the sign of Add is the same as at least one of the operands, this add
3426 // CANNOT overflow. This is particularly useful when the sum is
3427 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3428 // operands.
3429 bool LHSOrRHSKnownNonNegative =
3430 (LHSKnownNonNegative || RHSKnownNonNegative);
3431 bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3432 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3433 bool AddKnownNonNegative, AddKnownNegative;
3434 ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
3435 /*Depth=*/0, AC, CxtI, DT);
3436 if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3437 (AddKnownNegative && LHSOrRHSKnownNegative)) {
3438 return OverflowResult::NeverOverflows;
3439 }
3440 }
3441
3442 return OverflowResult::MayOverflow;
3443}
3444
3445OverflowResult llvm::computeOverflowForSignedAdd(AddOperator *Add,
3446 const DataLayout &DL,
3447 AssumptionCache *AC,
3448 const Instruction *CxtI,
3449 const DominatorTree *DT) {
3450 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3451 Add, DL, AC, CxtI, DT);
3452}
3453
3454OverflowResult llvm::computeOverflowForSignedAdd(Value *LHS, Value *RHS,
3455 const DataLayout &DL,
3456 AssumptionCache *AC,
3457 const Instruction *CxtI,
3458 const DominatorTree *DT) {
3459 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3460}
3461
Jingyue Wu42f1d672015-07-28 18:22:40 +00003462bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3463 // FIXME: This conservative implementation can be relaxed. E.g. most
3464 // atomic operations are guaranteed to terminate on most platforms
3465 // and most functions terminate.
3466
3467 return !I->isAtomic() && // atomics may never succeed on some platforms
3468 !isa<CallInst>(I) && // could throw and might not terminate
3469 !isa<InvokeInst>(I) && // might not terminate and could throw to
3470 // non-successor (see bug 24185 for details).
3471 !isa<ResumeInst>(I) && // has no successors
3472 !isa<ReturnInst>(I); // has no successors
3473}
3474
3475bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3476 const Loop *L) {
3477 // The loop header is guaranteed to be executed for every iteration.
3478 //
3479 // FIXME: Relax this constraint to cover all basic blocks that are
3480 // guaranteed to be executed at every iteration.
3481 if (I->getParent() != L->getHeader()) return false;
3482
3483 for (const Instruction &LI : *L->getHeader()) {
3484 if (&LI == I) return true;
3485 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3486 }
3487 llvm_unreachable("Instruction not contained in its own parent basic block.");
3488}
3489
3490bool llvm::propagatesFullPoison(const Instruction *I) {
3491 switch (I->getOpcode()) {
3492 case Instruction::Add:
3493 case Instruction::Sub:
3494 case Instruction::Xor:
3495 case Instruction::Trunc:
3496 case Instruction::BitCast:
3497 case Instruction::AddrSpaceCast:
3498 // These operations all propagate poison unconditionally. Note that poison
3499 // is not any particular value, so xor or subtraction of poison with
3500 // itself still yields poison, not zero.
3501 return true;
3502
3503 case Instruction::AShr:
3504 case Instruction::SExt:
3505 // For these operations, one bit of the input is replicated across
3506 // multiple output bits. A replicated poison bit is still poison.
3507 return true;
3508
3509 case Instruction::Shl: {
3510 // Left shift *by* a poison value is poison. The number of
3511 // positions to shift is unsigned, so no negative values are
3512 // possible there. Left shift by zero places preserves poison. So
3513 // it only remains to consider left shift of poison by a positive
3514 // number of places.
3515 //
3516 // A left shift by a positive number of places leaves the lowest order bit
3517 // non-poisoned. However, if such a shift has a no-wrap flag, then we can
3518 // make the poison operand violate that flag, yielding a fresh full-poison
3519 // value.
3520 auto *OBO = cast<OverflowingBinaryOperator>(I);
3521 return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
3522 }
3523
3524 case Instruction::Mul: {
3525 // A multiplication by zero yields a non-poison zero result, so we need to
3526 // rule out zero as an operand. Conservatively, multiplication by a
3527 // non-zero constant is not multiplication by zero.
3528 //
3529 // Multiplication by a non-zero constant can leave some bits
3530 // non-poisoned. For example, a multiplication by 2 leaves the lowest
3531 // order bit unpoisoned. So we need to consider that.
3532 //
3533 // Multiplication by 1 preserves poison. If the multiplication has a
3534 // no-wrap flag, then we can make the poison operand violate that flag
3535 // when multiplied by any integer other than 0 and 1.
3536 auto *OBO = cast<OverflowingBinaryOperator>(I);
3537 if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
3538 for (Value *V : OBO->operands()) {
3539 if (auto *CI = dyn_cast<ConstantInt>(V)) {
3540 // A ConstantInt cannot yield poison, so we can assume that it is
3541 // the other operand that is poison.
3542 return !CI->isZero();
3543 }
3544 }
3545 }
3546 return false;
3547 }
3548
3549 case Instruction::GetElementPtr:
3550 // A GEP implicitly represents a sequence of additions, subtractions,
3551 // truncations, sign extensions and multiplications. The multiplications
3552 // are by the non-zero sizes of some set of types, so we do not have to be
3553 // concerned with multiplication by zero. If the GEP is in-bounds, then
3554 // these operations are implicitly no-signed-wrap so poison is propagated
3555 // by the arguments above for Add, Sub, Trunc, SExt and Mul.
3556 return cast<GEPOperator>(I)->isInBounds();
3557
3558 default:
3559 return false;
3560 }
3561}
3562
3563const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3564 switch (I->getOpcode()) {
3565 case Instruction::Store:
3566 return cast<StoreInst>(I)->getPointerOperand();
3567
3568 case Instruction::Load:
3569 return cast<LoadInst>(I)->getPointerOperand();
3570
3571 case Instruction::AtomicCmpXchg:
3572 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3573
3574 case Instruction::AtomicRMW:
3575 return cast<AtomicRMWInst>(I)->getPointerOperand();
3576
3577 case Instruction::UDiv:
3578 case Instruction::SDiv:
3579 case Instruction::URem:
3580 case Instruction::SRem:
3581 return I->getOperand(1);
3582
3583 default:
3584 return nullptr;
3585 }
3586}
3587
3588bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3589 // We currently only look for uses of poison values within the same basic
3590 // block, as that makes it easier to guarantee that the uses will be
3591 // executed given that PoisonI is executed.
3592 //
3593 // FIXME: Expand this to consider uses beyond the same basic block. To do
3594 // this, look out for the distinction between post-dominance and strong
3595 // post-dominance.
3596 const BasicBlock *BB = PoisonI->getParent();
3597
3598 // Set of instructions that we have proved will yield poison if PoisonI
3599 // does.
3600 SmallSet<const Value *, 16> YieldsPoison;
3601 YieldsPoison.insert(PoisonI);
3602
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00003603 for (BasicBlock::const_iterator I = PoisonI->getIterator(), E = BB->end();
3604 I != E; ++I) {
3605 if (&*I != PoisonI) {
3606 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&*I);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003607 if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) return true;
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00003608 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
3609 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003610 }
3611
3612 // Mark poison that propagates from I through uses of I.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00003613 if (YieldsPoison.count(&*I)) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003614 for (const User *User : I->users()) {
3615 const Instruction *UserI = cast<Instruction>(User);
3616 if (UserI->getParent() == BB && propagatesFullPoison(UserI))
3617 YieldsPoison.insert(User);
3618 }
3619 }
3620 }
3621 return false;
3622}
3623
James Molloy134bec22015-08-11 09:12:57 +00003624static bool isKnownNonNaN(Value *V, FastMathFlags FMF) {
3625 if (FMF.noNaNs())
3626 return true;
3627
3628 if (auto *C = dyn_cast<ConstantFP>(V))
3629 return !C->isNaN();
3630 return false;
3631}
3632
3633static bool isKnownNonZero(Value *V) {
3634 if (auto *C = dyn_cast<ConstantFP>(V))
3635 return !C->isZero();
3636 return false;
3637}
3638
3639static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3640 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00003641 Value *CmpLHS, Value *CmpRHS,
3642 Value *TrueVal, Value *FalseVal,
3643 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003644 LHS = CmpLHS;
3645 RHS = CmpRHS;
3646
James Molloy134bec22015-08-11 09:12:57 +00003647 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
3648 // return inconsistent results between implementations.
3649 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3650 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3651 // Therefore we behave conservatively and only proceed if at least one of the
3652 // operands is known to not be zero, or if we don't care about signed zeroes.
3653 switch (Pred) {
3654 default: break;
3655 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3656 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3657 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3658 !isKnownNonZero(CmpRHS))
3659 return {SPF_UNKNOWN, SPNB_NA, false};
3660 }
3661
3662 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3663 bool Ordered = false;
3664
3665 // When given one NaN and one non-NaN input:
3666 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3667 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3668 // ordered comparison fails), which could be NaN or non-NaN.
3669 // so here we discover exactly what NaN behavior is required/accepted.
3670 if (CmpInst::isFPPredicate(Pred)) {
3671 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3672 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3673
3674 if (LHSSafe && RHSSafe) {
3675 // Both operands are known non-NaN.
3676 NaNBehavior = SPNB_RETURNS_ANY;
3677 } else if (CmpInst::isOrdered(Pred)) {
3678 // An ordered comparison will return false when given a NaN, so it
3679 // returns the RHS.
3680 Ordered = true;
3681 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00003682 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00003683 NaNBehavior = SPNB_RETURNS_NAN;
3684 else if (RHSSafe)
3685 NaNBehavior = SPNB_RETURNS_OTHER;
3686 else
3687 // Completely unsafe.
3688 return {SPF_UNKNOWN, SPNB_NA, false};
3689 } else {
3690 Ordered = false;
3691 // An unordered comparison will return true when given a NaN, so it
3692 // returns the LHS.
3693 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00003694 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00003695 NaNBehavior = SPNB_RETURNS_OTHER;
3696 else if (RHSSafe)
3697 NaNBehavior = SPNB_RETURNS_NAN;
3698 else
3699 // Completely unsafe.
3700 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003701 }
3702 }
3703
James Molloy71b91c22015-05-11 14:42:20 +00003704 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00003705 std::swap(CmpLHS, CmpRHS);
3706 Pred = CmpInst::getSwappedPredicate(Pred);
3707 if (NaNBehavior == SPNB_RETURNS_NAN)
3708 NaNBehavior = SPNB_RETURNS_OTHER;
3709 else if (NaNBehavior == SPNB_RETURNS_OTHER)
3710 NaNBehavior = SPNB_RETURNS_NAN;
3711 Ordered = !Ordered;
3712 }
3713
3714 // ([if]cmp X, Y) ? X : Y
3715 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003716 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00003717 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00003718 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00003719 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003720 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00003721 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003722 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00003723 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003724 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00003725 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
3726 case FCmpInst::FCMP_UGT:
3727 case FCmpInst::FCMP_UGE:
3728 case FCmpInst::FCMP_OGT:
3729 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
3730 case FCmpInst::FCMP_ULT:
3731 case FCmpInst::FCMP_ULE:
3732 case FCmpInst::FCMP_OLT:
3733 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00003734 }
3735 }
3736
3737 if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
3738 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
3739 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
3740
3741 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
3742 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
3743 if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
James Molloy134bec22015-08-11 09:12:57 +00003744 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003745 }
3746
3747 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
3748 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
3749 if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
James Molloy134bec22015-08-11 09:12:57 +00003750 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003751 }
3752 }
3753
3754 // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
3755 if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
3756 if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
3757 (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
3758 match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
3759 LHS = TrueVal;
3760 RHS = FalseVal;
James Molloy134bec22015-08-11 09:12:57 +00003761 return {SPF_SMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003762 }
3763 }
3764 }
3765
3766 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
3767
James Molloy134bec22015-08-11 09:12:57 +00003768 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003769}
James Molloy270ef8c2015-05-15 16:04:50 +00003770
James Molloy569cea62015-09-02 17:25:25 +00003771static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
3772 Instruction::CastOps *CastOp) {
James Molloy270ef8c2015-05-15 16:04:50 +00003773 CastInst *CI = dyn_cast<CastInst>(V1);
3774 Constant *C = dyn_cast<Constant>(V2);
James Molloy569cea62015-09-02 17:25:25 +00003775 CastInst *CI2 = dyn_cast<CastInst>(V2);
3776 if (!CI)
James Molloy270ef8c2015-05-15 16:04:50 +00003777 return nullptr;
3778 *CastOp = CI->getOpcode();
3779
James Molloy569cea62015-09-02 17:25:25 +00003780 if (CI2) {
3781 // If V1 and V2 are both the same cast from the same type, we can look
3782 // through V1.
3783 if (CI2->getOpcode() == CI->getOpcode() &&
3784 CI2->getSrcTy() == CI->getSrcTy())
3785 return CI2->getOperand(0);
3786 return nullptr;
3787 } else if (!C) {
3788 return nullptr;
3789 }
3790
James Molloy2b21a7c2015-05-20 18:41:25 +00003791 if (isa<SExtInst>(CI) && CmpI->isSigned()) {
3792 Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
3793 // This is only valid if the truncated value can be sign-extended
3794 // back to the original value.
3795 if (ConstantExpr::getSExt(T, C->getType()) == C)
3796 return T;
3797 return nullptr;
3798 }
3799 if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
James Molloy270ef8c2015-05-15 16:04:50 +00003800 return ConstantExpr::getTrunc(C, CI->getSrcTy());
3801
3802 if (isa<TruncInst>(CI))
3803 return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
3804
James Molloy134bec22015-08-11 09:12:57 +00003805 if (isa<FPToUIInst>(CI))
3806 return ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
3807
3808 if (isa<FPToSIInst>(CI))
3809 return ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
3810
3811 if (isa<UIToFPInst>(CI))
3812 return ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
3813
3814 if (isa<SIToFPInst>(CI))
3815 return ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
3816
3817 if (isa<FPTruncInst>(CI))
3818 return ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
3819
3820 if (isa<FPExtInst>(CI))
3821 return ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
3822
James Molloy270ef8c2015-05-15 16:04:50 +00003823 return nullptr;
3824}
3825
James Molloy134bec22015-08-11 09:12:57 +00003826SelectPatternResult llvm::matchSelectPattern(Value *V,
James Molloy270ef8c2015-05-15 16:04:50 +00003827 Value *&LHS, Value *&RHS,
3828 Instruction::CastOps *CastOp) {
3829 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00003830 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00003831
James Molloy134bec22015-08-11 09:12:57 +00003832 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
3833 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00003834
James Molloy134bec22015-08-11 09:12:57 +00003835 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00003836 Value *CmpLHS = CmpI->getOperand(0);
3837 Value *CmpRHS = CmpI->getOperand(1);
3838 Value *TrueVal = SI->getTrueValue();
3839 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00003840 FastMathFlags FMF;
3841 if (isa<FPMathOperator>(CmpI))
3842 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00003843
3844 // Bail out early.
3845 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00003846 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00003847
3848 // Deal with type mismatches.
3849 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00003850 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00003851 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00003852 cast<CastInst>(TrueVal)->getOperand(0), C,
3853 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00003854 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00003855 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00003856 C, cast<CastInst>(FalseVal)->getOperand(0),
3857 LHS, RHS);
3858 }
James Molloy134bec22015-08-11 09:12:57 +00003859 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00003860 LHS, RHS);
3861}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003862
3863ConstantRange llvm::getConstantRangeFromMetadata(MDNode &Ranges) {
3864 const unsigned NumRanges = Ranges.getNumOperands() / 2;
3865 assert(NumRanges >= 1 && "Must have at least one range!");
3866 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
3867
3868 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
3869 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
3870
3871 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
3872
3873 for (unsigned i = 1; i < NumRanges; ++i) {
3874 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
3875 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
3876
3877 // Note: unionWith will potentially create a range that contains values not
3878 // contained in any of the original N ranges.
3879 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
3880 }
3881
3882 return CR;
3883}
Sanjoy Das3ef1e682015-10-28 03:20:19 +00003884
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003885/// Return true if "icmp Pred LHS RHS" is always true.
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003886static bool isTruePredicate(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
3887 const DataLayout &DL, unsigned Depth,
3888 AssumptionCache *AC, const Instruction *CxtI,
3889 const DominatorTree *DT) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00003890 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003891 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
3892 return true;
3893
3894 switch (Pred) {
3895 default:
3896 return false;
3897
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003898 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00003899 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003900
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003901 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00003902 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00003903 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003904 return false;
3905 }
3906
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003907 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00003908 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003909
Sanjoy Dasdc26df42015-11-11 00:16:41 +00003910 // LHS u<= LHS +_{nuw} C for any C
3911 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00003912 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00003913
3914 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
3915 auto MatchNUWAddsToSameValue = [&](Value *A, Value *B, Value *&X,
3916 const APInt *&CA, const APInt *&CB) {
3917 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
3918 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
3919 return true;
3920
3921 // If X & C == 0 then (X | C) == X +_{nuw} C
3922 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
3923 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
3924 unsigned BitWidth = CA->getBitWidth();
3925 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3926 computeKnownBits(X, KnownZero, KnownOne, DL, Depth + 1, AC, CxtI, DT);
3927
3928 if ((KnownZero & *CA) == *CA && (KnownZero & *CB) == *CB)
3929 return true;
3930 }
3931
3932 return false;
3933 };
3934
3935 Value *X;
3936 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00003937 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
3938 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00003939
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003940 return false;
3941 }
3942 }
3943}
3944
3945/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
3946/// ALHS ARHS" is true.
3947static bool isImpliedCondOperands(CmpInst::Predicate Pred, Value *ALHS,
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003948 Value *ARHS, Value *BLHS, Value *BRHS,
3949 const DataLayout &DL, unsigned Depth,
3950 AssumptionCache *AC, const Instruction *CxtI,
3951 const DominatorTree *DT) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003952 switch (Pred) {
3953 default:
3954 return false;
3955
3956 case CmpInst::ICMP_SLT:
3957 case CmpInst::ICMP_SLE:
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003958 return isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
3959 DT) &&
3960 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI,
3961 DT);
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003962
3963 case CmpInst::ICMP_ULT:
3964 case CmpInst::ICMP_ULE:
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003965 return isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
3966 DT) &&
3967 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI,
3968 DT);
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003969 }
3970}
3971
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003972bool llvm::isImpliedCondition(Value *LHS, Value *RHS, const DataLayout &DL,
3973 unsigned Depth, AssumptionCache *AC,
3974 const Instruction *CxtI,
3975 const DominatorTree *DT) {
Sanjoy Das3ef1e682015-10-28 03:20:19 +00003976 assert(LHS->getType() == RHS->getType() && "mismatched type");
3977 Type *OpTy = LHS->getType();
3978 assert(OpTy->getScalarType()->isIntegerTy(1));
3979
3980 // LHS ==> RHS by definition
3981 if (LHS == RHS) return true;
3982
3983 if (OpTy->isVectorTy())
3984 // TODO: extending the code below to handle vectors
3985 return false;
3986 assert(OpTy->isIntegerTy(1) && "implied by above");
3987
3988 ICmpInst::Predicate APred, BPred;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003989 Value *ALHS, *ARHS;
3990 Value *BLHS, *BRHS;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00003991
Sanjoy Das9349dcc2015-11-06 19:00:57 +00003992 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
3993 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
3994 return false;
3995
3996 if (APred == BPred)
Sanjoy Das55ea67c2015-11-06 19:01:08 +00003997 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
3998 CxtI, DT);
Sanjoy Das3ef1e682015-10-28 03:20:19 +00003999
4000 return false;
4001}