blob: aeb8fcfc2b1a32f3d42ea9135fb68c1e117d8c35 [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +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"
Sanjay Patel54656ca2017-02-06 18:26:06 +000023#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
David Majnemer3ee5f342016-04-13 06:55:52 +000024#include "llvm/Analysis/VectorUtils.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000025#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalAlias.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000038#include "llvm/IR/PatternMatch.h"
Philip Reames5461d452015-04-23 17:36:48 +000039#include "llvm/IR/Statepoint.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000040#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000041#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000042#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000043#include <algorithm>
44#include <array>
Chris Lattner64496902008-06-04 04:46:14 +000045#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000046using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000047using namespace llvm::PatternMatch;
48
49const unsigned MaxDepth = 6;
50
Philip Reames1c292272015-03-10 22:43:20 +000051// Controls the number of uses of the value searched for possible
52// dominating comparisons.
53static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000054 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000055
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +000056// This optimization is known to cause performance regressions is some cases,
57// keep it under a temporary flag for now.
58static cl::opt<bool>
59DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
60 cl::Hidden, cl::init(true));
61
Sanjay Patelaee84212014-11-04 16:27:42 +000062/// Returns the bitwidth of the given scalar or pointer type (if unknown returns
63/// 0). For vector types, returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000064static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000065 if (unsigned BitWidth = Ty->getScalarSizeInBits())
66 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000067
Mehdi Aminia28d91d2015-03-10 02:37:25 +000068 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000069}
Chris Lattner965c7692008-06-02 01:18:21 +000070
Benjamin Kramercfd8d902014-09-12 08:56:53 +000071namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000072// Simplifying using an assume can only be done in a particular control-flow
73// context (the context instruction provides that context). If an assume and
74// the context instruction are not in the same block then the DT helps in
75// figuring out if we can use it.
76struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +000077 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000078 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000079 const Instruction *CxtI;
80 const DominatorTree *DT;
Sanjay Patel54656ca2017-02-06 18:26:06 +000081 // Unlike the other analyses, this may be a nullptr because not all clients
82 // provide it currently.
83 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +000084
Matthias Braun37e5d792016-01-28 06:29:33 +000085 /// Set of assumptions that should be excluded from further queries.
86 /// This is because of the potential for mutual recursion to cause
87 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
88 /// classic case of this is assume(x = y), which will attempt to determine
89 /// bits in x from bits in y, which will attempt to determine bits in y from
90 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
91 /// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
92 /// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so
93 /// on.
Li Huang755f75f2016-10-15 19:00:04 +000094 std::array<const Value *, MaxDepth> Excluded;
Matthias Braun37e5d792016-01-28 06:29:33 +000095 unsigned NumExcluded;
96
Daniel Jasperaec2fa32016-12-19 08:22:17 +000097 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +000098 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
99 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), NumExcluded(0) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000100
101 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000102 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
103 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000104 Excluded = Q.Excluded;
105 Excluded[NumExcluded++] = NewExcl;
106 assert(NumExcluded <= Excluded.size());
107 }
108
109 bool isExcluded(const Value *Value) const {
110 if (NumExcluded == 0)
111 return false;
112 auto End = Excluded.begin() + NumExcluded;
113 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000114 }
115};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000116} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000117
Sanjay Patel547e9752014-11-04 16:09:50 +0000118// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000119// the preferred context instruction (if any).
120static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
121 // If we've been provided with a context instruction, then use that (provided
122 // it has been inserted).
123 if (CxtI && CxtI->getParent())
124 return CxtI;
125
126 // If the value is really an already-inserted instruction, then use that.
127 CxtI = dyn_cast<Instruction>(V);
128 if (CxtI && CxtI->getParent())
129 return CxtI;
130
131 return nullptr;
132}
133
Craig Topperb45eabc2017-04-26 16:39:58 +0000134static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000135 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000136
Craig Topperb45eabc2017-04-26 16:39:58 +0000137void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000138 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000139 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000140 const DominatorTree *DT,
141 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000142 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000143 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000144}
145
Pete Cooper35b00d52016-08-13 01:05:32 +0000146bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
147 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000148 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000149 const DominatorTree *DT) {
150 assert(LHS->getType() == RHS->getType() &&
151 "LHS and RHS should have the same type");
152 assert(LHS->getType()->isIntOrIntVectorTy() &&
153 "LHS and RHS should be integers");
154 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000155 KnownBits LHSKnown(IT->getBitWidth());
156 KnownBits RHSKnown(IT->getBitWidth());
157 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
158 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
159 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000160}
161
Pete Cooper35b00d52016-08-13 01:05:32 +0000162static void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000163 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000164
Pete Cooper35b00d52016-08-13 01:05:32 +0000165void llvm::ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000167 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000168 const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000169 ::ComputeSignBit(V, KnownZero, KnownOne, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000171}
172
Pete Cooper35b00d52016-08-13 01:05:32 +0000173static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000174 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000175
Pete Cooper35b00d52016-08-13 01:05:32 +0000176bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
177 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000178 unsigned Depth, AssumptionCache *AC,
179 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000180 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000181 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000182 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000183}
184
Pete Cooper35b00d52016-08-13 01:05:32 +0000185static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000186
Pete Cooper35b00d52016-08-13 01:05:32 +0000187bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000188 AssumptionCache *AC, const Instruction *CxtI,
189 const DominatorTree *DT) {
190 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000191}
192
Pete Cooper35b00d52016-08-13 01:05:32 +0000193bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000194 unsigned Depth,
195 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000196 const DominatorTree *DT) {
197 bool NonNegative, Negative;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000198 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +0000199 return NonNegative;
200}
201
Pete Cooper35b00d52016-08-13 01:05:32 +0000202bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000203 AssumptionCache *AC, const Instruction *CxtI,
204 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000205 if (auto *CI = dyn_cast<ConstantInt>(V))
206 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000207
Philip Reames8f12eba2016-03-09 21:31:47 +0000208 // TODO: We'd doing two recursive queries here. We should factor this such
209 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000210 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
211 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000212}
213
Pete Cooper35b00d52016-08-13 01:05:32 +0000214bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000215 AssumptionCache *AC, const Instruction *CxtI,
216 const DominatorTree *DT) {
Nick Lewycky762f8a82016-04-21 00:53:14 +0000217 bool NonNegative, Negative;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000218 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
Nick Lewycky762f8a82016-04-21 00:53:14 +0000219 return Negative;
220}
221
Pete Cooper35b00d52016-08-13 01:05:32 +0000222static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000223
Pete Cooper35b00d52016-08-13 01:05:32 +0000224bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000225 const DataLayout &DL,
226 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000227 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000228 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
229 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000230 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000231}
232
Pete Cooper35b00d52016-08-13 01:05:32 +0000233static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000234 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235
Pete Cooper35b00d52016-08-13 01:05:32 +0000236bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
237 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000238 unsigned Depth, AssumptionCache *AC,
239 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000240 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000241 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242}
243
Pete Cooper35b00d52016-08-13 01:05:32 +0000244static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
245 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246
Pete Cooper35b00d52016-08-13 01:05:32 +0000247unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000248 unsigned Depth, AssumptionCache *AC,
249 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000251 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000252}
253
Craig Topper8fbb74b2017-03-24 22:12:10 +0000254static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
255 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000256 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000257 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000258 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000259
260 // If an initial sequence of bits in the result is not needed, the
261 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000262 KnownBits LHSKnown(BitWidth);
263 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
264 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000265
David Majnemer97ddca32014-08-22 00:40:43 +0000266 // Carry in a 1 for a subtract, rather than a 0.
Craig Topper059b98e2017-03-24 05:38:09 +0000267 uint64_t CarryIn = 0;
David Majnemer97ddca32014-08-22 00:40:43 +0000268 if (!Add) {
269 // Sum = LHS + ~RHS + 1
Craig Topperb45eabc2017-04-26 16:39:58 +0000270 std::swap(Known2.Zero, Known2.One);
Craig Topper059b98e2017-03-24 05:38:09 +0000271 CarryIn = 1;
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000272 }
273
Craig Topperb45eabc2017-04-26 16:39:58 +0000274 APInt PossibleSumZero = ~LHSKnown.Zero + ~Known2.Zero + CarryIn;
275 APInt PossibleSumOne = LHSKnown.One + Known2.One + CarryIn;
David Majnemer97ddca32014-08-22 00:40:43 +0000276
277 // Compute known bits of the carry.
Craig Topperb45eabc2017-04-26 16:39:58 +0000278 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnown.Zero ^ Known2.Zero);
279 APInt CarryKnownOne = PossibleSumOne ^ LHSKnown.One ^ Known2.One;
David Majnemer97ddca32014-08-22 00:40:43 +0000280
281 // Compute set of known bits (where all three relevant bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000282 APInt LHSKnownUnion = LHSKnown.Zero | LHSKnown.One;
283 APInt RHSKnownUnion = Known2.Zero | Known2.One;
284 APInt CarryKnownUnion = CarryKnownZero | CarryKnownOne;
285 APInt Known = LHSKnownUnion & RHSKnownUnion & CarryKnownUnion;
David Majnemer97ddca32014-08-22 00:40:43 +0000286
287 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
288 "known bits of sum differ");
289
290 // Compute known bits of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +0000291 KnownOut.Zero = ~PossibleSumOne & Known;
292 KnownOut.One = PossibleSumOne & Known;
David Majnemer97ddca32014-08-22 00:40:43 +0000293
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000294 // Are we still trying to solve for the sign bit?
Craig Topperd23004c2017-04-17 16:38:20 +0000295 if (!Known.isSignBitSet()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000296 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000297 // Adding two non-negative numbers, or subtracting a negative number from
298 // a non-negative one, can't wrap into negative.
Craig Topperb45eabc2017-04-26 16:39:58 +0000299 if (LHSKnown.Zero.isSignBitSet() && Known2.Zero.isSignBitSet())
300 KnownOut.Zero.setSignBit();
David Majnemer97ddca32014-08-22 00:40:43 +0000301 // Adding two negative numbers, or subtracting a non-negative number from
302 // a negative one, can't wrap into non-negative.
Craig Topperb45eabc2017-04-26 16:39:58 +0000303 else if (LHSKnown.One.isSignBitSet() && Known2.One.isSignBitSet())
304 KnownOut.One.setSignBit();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000305 }
306 }
307}
308
Pete Cooper35b00d52016-08-13 01:05:32 +0000309static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000310 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000311 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000312 unsigned BitWidth = Known.getBitWidth();
313 computeKnownBits(Op1, Known, Depth + 1, Q);
314 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000315
316 bool isKnownNegative = false;
317 bool isKnownNonNegative = false;
318 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000319 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000320 if (Op0 == Op1) {
321 // The product of a number with itself is non-negative.
322 isKnownNonNegative = true;
323 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000324 bool isKnownNonNegativeOp1 = Known.Zero.isSignBitSet();
325 bool isKnownNonNegativeOp0 = Known2.Zero.isSignBitSet();
326 bool isKnownNegativeOp1 = Known.One.isSignBitSet();
327 bool isKnownNegativeOp0 = Known2.One.isSignBitSet();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000328 // The product of two numbers with the same sign is non-negative.
329 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
330 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
331 // The product of a negative number and a non-negative number is either
332 // negative or zero.
333 if (!isKnownNonNegative)
334 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000335 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000336 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000337 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000338 }
339 }
340
341 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000342 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000343 // More trickiness is possible, but this is sufficient for the
344 // interesting case of alignment computation.
Craig Topperb45eabc2017-04-26 16:39:58 +0000345 Known.One.clearAllBits();
346 unsigned TrailZ = Known.Zero.countTrailingOnes() +
347 Known2.Zero.countTrailingOnes();
348 unsigned LeadZ = std::max(Known.Zero.countLeadingOnes() +
349 Known2.Zero.countLeadingOnes(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000350 BitWidth) - BitWidth;
351
352 TrailZ = std::min(TrailZ, BitWidth);
353 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +0000354 Known.Zero.clearAllBits();
355 Known.Zero.setLowBits(TrailZ);
356 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000357
358 // Only make use of no-wrap flags if we failed to compute the sign bit
359 // directly. This matters if the multiplication always overflows, in
360 // which case we prefer to follow the result of the direct computation,
361 // though as the program is invoking undefined behaviour we can choose
362 // whatever we like here.
Craig Topperb45eabc2017-04-26 16:39:58 +0000363 if (isKnownNonNegative && !Known.One.isSignBitSet())
364 Known.Zero.setSignBit();
365 else if (isKnownNegative && !Known.Zero.isSignBitSet())
366 Known.One.setSignBit();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000367}
368
Jingyue Wu37fcb592014-06-19 16:50:16 +0000369void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000370 KnownBits &Known) {
371 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000372 unsigned NumRanges = Ranges.getNumOperands() / 2;
373 assert(NumRanges >= 1);
374
Craig Topperf42b23f2017-04-28 06:28:56 +0000375 Known.Zero.setAllBits();
376 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000377
Rafael Espindola53190532012-03-30 15:52:11 +0000378 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000379 ConstantInt *Lower =
380 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
381 ConstantInt *Upper =
382 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000383 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000384
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000385 // The first CommonPrefixBits of all values in Range are equal.
386 unsigned CommonPrefixBits =
387 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
388
389 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000390 Known.One &= Range.getUnsignedMax() & Mask;
391 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000392 }
Rafael Espindola53190532012-03-30 15:52:11 +0000393}
Jay Foad5a29c362014-05-15 12:12:55 +0000394
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000395static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000396 SmallVector<const Value *, 16> WorkSet(1, I);
397 SmallPtrSet<const Value *, 32> Visited;
398 SmallPtrSet<const Value *, 16> EphValues;
399
Hal Finkelf2199b22015-10-23 20:37:08 +0000400 // The instruction defining an assumption's condition itself is always
401 // considered ephemeral to that assumption (even if it has other
402 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000403 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000404 return true;
405
Hal Finkel60db0582014-09-07 18:57:58 +0000406 while (!WorkSet.empty()) {
407 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000408 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000409 continue;
410
411 // If all uses of this value are ephemeral, then so is this value.
David Majnemer0a16c222016-08-11 21:15:00 +0000412 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000413 if (V == E)
414 return true;
415
416 EphValues.insert(V);
417 if (const User *U = dyn_cast<User>(V))
418 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
419 J != JE; ++J) {
420 if (isSafeToSpeculativelyExecute(*J))
421 WorkSet.push_back(*J);
422 }
423 }
424 }
425
426 return false;
427}
428
429// Is this an intrinsic that cannot be speculated but also cannot trap?
430static bool isAssumeLikeIntrinsic(const Instruction *I) {
431 if (const CallInst *CI = dyn_cast<CallInst>(I))
432 if (Function *F = CI->getCalledFunction())
433 switch (F->getIntrinsicID()) {
434 default: break;
435 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
436 case Intrinsic::assume:
437 case Intrinsic::dbg_declare:
438 case Intrinsic::dbg_value:
439 case Intrinsic::invariant_start:
440 case Intrinsic::invariant_end:
441 case Intrinsic::lifetime_start:
442 case Intrinsic::lifetime_end:
443 case Intrinsic::objectsize:
444 case Intrinsic::ptr_annotation:
445 case Intrinsic::var_annotation:
446 return true;
447 }
448
449 return false;
450}
451
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000452bool llvm::isValidAssumeForContext(const Instruction *Inv,
453 const Instruction *CxtI,
454 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000455
456 // There are two restrictions on the use of an assume:
457 // 1. The assume must dominate the context (or the control flow must
458 // reach the assume whenever it reaches the context).
459 // 2. The context must not be in the assume's set of ephemeral values
460 // (otherwise we will use the assume to prove that the condition
461 // feeding the assume is trivially true, thus causing the removal of
462 // the assume).
463
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000464 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000465 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000466 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000467 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
468 // We don't have a DT, but this trivially dominates.
469 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000470 }
471
Pete Cooper54a02552016-08-12 01:00:15 +0000472 // With or without a DT, the only remaining case we will check is if the
473 // instructions are in the same BB. Give up if that is not the case.
474 if (Inv->getParent() != CxtI->getParent())
475 return false;
476
477 // If we have a dom tree, then we now know that the assume doens't dominate
478 // the other instruction. If we don't have a dom tree then we can check if
479 // the assume is first in the BB.
480 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000481 // Search forward from the assume until we reach the context (or the end
482 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000483 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000484 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000485 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000486 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000487 }
488
Pete Cooper54a02552016-08-12 01:00:15 +0000489 // The context comes first, but they're both in the same block. Make sure
490 // there is nothing in between that might interrupt the control flow.
491 for (BasicBlock::const_iterator I =
492 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
493 I != IE; ++I)
494 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
495 return false;
496
497 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000498}
499
Craig Topperb45eabc2017-04-26 16:39:58 +0000500static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
501 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000502 // Use of assumptions is context-sensitive. If we don't have a context, we
503 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000504 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000505 return;
506
Craig Topperb45eabc2017-04-26 16:39:58 +0000507 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000508
Hal Finkel8a9a7832017-01-11 13:24:24 +0000509 // Note that the patterns below need to be kept in sync with the code
510 // in AssumptionCache::updateAffectedValues.
511
512 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000513 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000514 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000515 CallInst *I = cast<CallInst>(AssumeVH);
516 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
517 "Got assumption for the wrong function!");
518 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000519 continue;
520
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000521 // Warning: This loop can end up being somewhat performance sensetive.
522 // We're running this loop for once for each value queried resulting in a
523 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000524
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000525 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
526 "must be an assume intrinsic");
527
528 Value *Arg = I->getArgOperand(0);
529
530 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000531 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperb45eabc2017-04-26 16:39:58 +0000532 Known.Zero.clearAllBits();
533 Known.One.setAllBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000534 return;
535 }
Sanjay Patel96669962017-01-17 18:15:49 +0000536 if (match(Arg, m_Not(m_Specific(V))) &&
537 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
538 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperb45eabc2017-04-26 16:39:58 +0000539 Known.Zero.setAllBits();
540 Known.One.clearAllBits();
Sanjay Patel96669962017-01-17 18:15:49 +0000541 return;
542 }
Hal Finkel60db0582014-09-07 18:57:58 +0000543
David Majnemer9b609752014-12-12 23:59:29 +0000544 // The remaining tests are all recursive, so bail out if we hit the limit.
545 if (Depth == MaxDepth)
546 continue;
547
Hal Finkel60db0582014-09-07 18:57:58 +0000548 Value *A, *B;
549 auto m_V = m_CombineOr(m_Specific(V),
550 m_CombineOr(m_PtrToInt(m_Specific(V)),
551 m_BitCast(m_Specific(V))));
552
553 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000554 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000555 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000556 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000557 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000558 KnownBits RHSKnown(BitWidth);
559 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
560 Known.Zero |= RHSKnown.Zero;
561 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000562 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 } else if (match(Arg,
564 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000565 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000566 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000567 KnownBits RHSKnown(BitWidth);
568 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
569 KnownBits MaskKnown(BitWidth);
570 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000571
572 // For those bits in the mask that are known to be one, we can propagate
573 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000574 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
575 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000576 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000577 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
578 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000579 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000580 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000581 KnownBits RHSKnown(BitWidth);
582 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
583 KnownBits MaskKnown(BitWidth);
584 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000585
586 // For those bits in the mask that are known to be one, we can propagate
587 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000588 Known.Zero |= RHSKnown.One & MaskKnown.One;
589 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000590 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000591 } else if (match(Arg,
592 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000593 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000594 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000595 KnownBits RHSKnown(BitWidth);
596 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
597 KnownBits BKnown(BitWidth);
598 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000599
600 // For those bits in B that are known to be zero, we can propagate known
601 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000602 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
603 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000604 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000605 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
606 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000607 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000608 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000609 KnownBits RHSKnown(BitWidth);
610 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
611 KnownBits BKnown(BitWidth);
612 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000613
614 // For those bits in B that are known to be zero, we can propagate
615 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000616 Known.Zero |= RHSKnown.One & BKnown.Zero;
617 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000618 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000619 } else if (match(Arg,
620 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000621 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000622 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000623 KnownBits RHSKnown(BitWidth);
624 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
625 KnownBits BKnown(BitWidth);
626 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000627
628 // For those bits in B that are known to be zero, we can propagate known
629 // bits from the RHS to V. For those bits in B that are known to be one,
630 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000631 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
632 Known.One |= RHSKnown.One & BKnown.Zero;
633 Known.Zero |= RHSKnown.One & BKnown.One;
634 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000635 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000636 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
637 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000638 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000639 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000640 KnownBits RHSKnown(BitWidth);
641 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
642 KnownBits BKnown(BitWidth);
643 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000644
645 // For those bits in B that are known to be zero, we can propagate
646 // inverted known bits from the RHS to V. For those bits in B that are
647 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000648 Known.Zero |= RHSKnown.One & BKnown.Zero;
649 Known.One |= RHSKnown.Zero & BKnown.Zero;
650 Known.Zero |= RHSKnown.Zero & BKnown.One;
651 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000652 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000653 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
654 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000655 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000656 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000657 KnownBits RHSKnown(BitWidth);
658 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000659 // For those bits in RHS that are known, we can propagate them to known
660 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000661 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
662 Known.Zero |= RHSKnown.Zero;
663 RHSKnown.One.lshrInPlace(C->getZExtValue());
664 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000665 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000666 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
667 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000668 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000669 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000670 KnownBits RHSKnown(BitWidth);
671 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000672 // For those bits in RHS that are known, we can propagate them inverted
673 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000674 RHSKnown.One.lshrInPlace(C->getZExtValue());
675 Known.Zero |= RHSKnown.One;
676 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
677 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000678 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000679 } else if (match(Arg,
680 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 m_AShr(m_V, m_ConstantInt(C))),
682 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000683 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000684 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 KnownBits RHSKnown(BitWidth);
686 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000687 // For those bits in RHS that are known, we can propagate them to known
688 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000689 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
690 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000691 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000692 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000693 m_LShr(m_V, m_ConstantInt(C)),
694 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000695 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000696 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000697 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000698 KnownBits RHSKnown(BitWidth);
699 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000700 // For those bits in RHS that are known, we can propagate them inverted
701 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 Known.Zero |= RHSKnown.One << C->getZExtValue();
703 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000704 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000705 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000706 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000707 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000708 KnownBits RHSKnown(BitWidth);
709 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000710
Craig Topperb45eabc2017-04-26 16:39:58 +0000711 if (RHSKnown.Zero.isSignBitSet()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000712 // We know that the sign bit is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000713 Known.Zero.setSignBit();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000714 }
715 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000716 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000717 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000718 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000719 KnownBits RHSKnown(BitWidth);
720 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000721
Craig Topperb45eabc2017-04-26 16:39:58 +0000722 if (RHSKnown.One.isAllOnesValue() || RHSKnown.Zero.isSignBitSet()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000723 // We know that the sign bit is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000724 Known.Zero.setSignBit();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000725 }
726 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000727 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000728 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000729 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000730 KnownBits RHSKnown(BitWidth);
731 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000732
Craig Topperb45eabc2017-04-26 16:39:58 +0000733 if (RHSKnown.One.isSignBitSet()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000734 // We know that the sign bit is one.
Craig Topperb45eabc2017-04-26 16:39:58 +0000735 Known.One.setSignBit();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000736 }
737 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000738 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000739 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000740 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000741 KnownBits RHSKnown(BitWidth);
742 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000743
Craig Topperb45eabc2017-04-26 16:39:58 +0000744 if (RHSKnown.Zero.isAllOnesValue() || RHSKnown.One.isSignBitSet()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000745 // We know that the sign bit is one.
Craig Topperb45eabc2017-04-26 16:39:58 +0000746 Known.One.setSignBit();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000747 }
748 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000749 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000750 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000751 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000752 KnownBits RHSKnown(BitWidth);
753 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000754
755 // Whatever high bits in c are zero are known to be zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000756 Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes());
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000757 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000758 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000759 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000760 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000761 KnownBits RHSKnown(BitWidth);
762 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000763
764 // Whatever high bits in c are zero are known to be zero (if c is a power
765 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000766 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topperb45eabc2017-04-26 16:39:58 +0000767 Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes()+1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000768 else
Craig Topperb45eabc2017-04-26 16:39:58 +0000769 Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000770 }
771 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000772
773 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000774 // have a logical fallacy. It's possible that the assumption is not reachable,
775 // so this isn't a real bug. On the other hand, the program may have undefined
776 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
777 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000778 if (Known.Zero.intersects(Known.One)) {
779 Known.Zero.clearAllBits();
780 Known.One.clearAllBits();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000781
782 if (Q.ORE) {
783 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
784 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
785 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
786 "have undefined behavior, or compiler may have "
787 "internal error.");
788 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000789 }
Hal Finkel60db0582014-09-07 18:57:58 +0000790}
791
Hal Finkelf2199b22015-10-23 20:37:08 +0000792// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000793// non-constant shift amount. Known is the outputs of this function. Known2 is a
794// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
795// operator-specific functors that, given the known-zero or known-one bits
796// respectively, and a shift amount, compute the implied known-zero or known-one
797// bits of the shift operator's result respectively for that shift amount. The
798// results from calling KZF and KOF are conservatively combined for all
799// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000800static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000801 const Operator *I, KnownBits &Known, KnownBits &Known2,
802 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000803 function_ref<APInt(const APInt &, unsigned)> KZF,
804 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000805 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000806
807 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
808 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
809
Craig Topperb45eabc2017-04-26 16:39:58 +0000810 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
811 Known.Zero = KZF(Known.Zero, ShiftAmt);
812 Known.One = KOF(Known.One, ShiftAmt);
813 // If there is conflict between Known.Zero and Known.One, this must be an
814 // overflowing left shift, so the shift result is undefined. Clear Known
815 // bits so that other code could propagate this undef.
816 if ((Known.Zero & Known.One) != 0) {
817 Known.Zero.clearAllBits();
818 Known.One.clearAllBits();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000819 }
820
Hal Finkelf2199b22015-10-23 20:37:08 +0000821 return;
822 }
823
Craig Topperb45eabc2017-04-26 16:39:58 +0000824 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000825
Oliver Stannard06204112017-03-14 10:13:17 +0000826 // If the shift amount could be greater than or equal to the bit-width of the LHS, the
827 // value could be undef, so we don't know anything about it.
Craig Topperb45eabc2017-04-26 16:39:58 +0000828 if ((~Known.Zero).uge(BitWidth)) {
829 Known.Zero.clearAllBits();
830 Known.One.clearAllBits();
Oliver Stannard06204112017-03-14 10:13:17 +0000831 return;
832 }
833
Craig Topperb45eabc2017-04-26 16:39:58 +0000834 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000835 // BitWidth > 64 and any upper bits are known, we'll end up returning the
836 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000837 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
838 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000839
840 // It would be more-clearly correct to use the two temporaries for this
841 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperb45eabc2017-04-26 16:39:58 +0000842 Known.Zero.clearAllBits();
843 Known.One.clearAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000844
James Molloy493e57d2015-10-26 14:10:46 +0000845 // If we know the shifter operand is nonzero, we can sometimes infer more
846 // known bits. However this is expensive to compute, so be lazy about it and
847 // only compute it when absolutely necessary.
848 Optional<bool> ShifterOperandIsNonZero;
849
Hal Finkelf2199b22015-10-23 20:37:08 +0000850 // Early exit if we can't constrain any well-defined shift amount.
James Molloy493e57d2015-10-26 14:10:46 +0000851 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
852 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000853 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000854 if (!*ShifterOperandIsNonZero)
855 return;
856 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000857
Craig Topperb45eabc2017-04-26 16:39:58 +0000858 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000859
Craig Topperb45eabc2017-04-26 16:39:58 +0000860 Known.Zero.setAllBits();
861 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000862 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
863 // Combine the shifted known input bits only for those shift amounts
864 // compatible with its known constraints.
865 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
866 continue;
867 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
868 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000869 // If we know the shifter is nonzero, we may be able to infer more known
870 // bits. This check is sunk down as far as possible to avoid the expensive
871 // call to isKnownNonZero if the cheaper checks above fail.
872 if (ShiftAmt == 0) {
873 if (!ShifterOperandIsNonZero.hasValue())
874 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000875 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000876 if (*ShifterOperandIsNonZero)
877 continue;
878 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000879
Craig Topperb45eabc2017-04-26 16:39:58 +0000880 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
881 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000882 }
883
884 // If there are no compatible shift amounts, then we've proven that the shift
885 // amount must be >= the BitWidth, and the result is undefined. We could
886 // return anything we'd like, but we need to make sure the sets of known bits
887 // stay disjoint (it should be better for some other code to actually
888 // propagate the undef than to pick a value here using known bits).
Craig Topperb45eabc2017-04-26 16:39:58 +0000889 if (Known.Zero.intersects(Known.One)) {
890 Known.Zero.clearAllBits();
891 Known.One.clearAllBits();
Richard Trieu7a083812016-02-18 22:09:30 +0000892 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000893}
894
Craig Topperb45eabc2017-04-26 16:39:58 +0000895static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
896 unsigned Depth, const Query &Q) {
897 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000898
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000900 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000901 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000902 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000903 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000904 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000905 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000906 case Instruction::And: {
907 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
909 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000910
Chris Lattner965c7692008-06-02 01:18:21 +0000911 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000912 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000913 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000914 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000915
916 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
917 // here we handle the more general case of adding any odd number by
918 // matching the form add(x, add(x, y)) where y is odd.
919 // TODO: This could be generalized to clearing any bit set in y where the
920 // following bit is known to be unset in y.
921 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000922 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000923 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
924 m_Value(Y))) ||
925 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
926 m_Value(Y))))) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000927 Known2.Zero.clearAllBits(); Known2.One.clearAllBits();
928 computeKnownBits(Y, Known2, Depth + 1, Q);
929 if (Known2.One.countTrailingOnes() > 0)
930 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000931 }
Jay Foad5a29c362014-05-15 12:12:55 +0000932 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000933 }
934 case Instruction::Or: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000935 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
936 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000937
Chris Lattner965c7692008-06-02 01:18:21 +0000938 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000939 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000940 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000942 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000943 }
944 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000945 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
946 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000947
Chris Lattner965c7692008-06-02 01:18:21 +0000948 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000949 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000950 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000951 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
952 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000953 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000954 }
955 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000956 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000957 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
958 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000959 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000960 }
961 case Instruction::UDiv: {
962 // For the purposes of computing leading zeros we can conservatively
963 // treat a udiv as a logical right shift by the power of 2 known to
964 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000965 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
966 unsigned LeadZ = Known2.Zero.countLeadingOnes();
Chris Lattner965c7692008-06-02 01:18:21 +0000967
Craig Topperb45eabc2017-04-26 16:39:58 +0000968 Known2.One.clearAllBits();
969 Known2.Zero.clearAllBits();
970 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
971 unsigned RHSUnknownLeadingOnes = Known2.One.countLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000972 if (RHSUnknownLeadingOnes != BitWidth)
973 LeadZ = std::min(BitWidth,
974 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
975
Craig Topperb45eabc2017-04-26 16:39:58 +0000976 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000977 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000978 }
David Majnemera19d0f22016-08-06 08:16:00 +0000979 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000980 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000981 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
982 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000983 computeKnownBits(RHS, Known, Depth + 1, Q);
984 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000985 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
987 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000988 }
989
990 unsigned MaxHighOnes = 0;
991 unsigned MaxHighZeros = 0;
992 if (SPF == SPF_SMAX) {
993 // If both sides are negative, the result is negative.
Craig Topperb45eabc2017-04-26 16:39:58 +0000994 if (Known.One.isSignBitSet() && Known2.One.isSignBitSet())
David Majnemera19d0f22016-08-06 08:16:00 +0000995 // We can derive a lower bound on the result by taking the max of the
996 // leading one bits.
Craig Topperb45eabc2017-04-26 16:39:58 +0000997 MaxHighOnes = std::max(Known.One.countLeadingOnes(),
998 Known2.One.countLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000999 // If either side is non-negative, the result is non-negative.
Craig Topperb45eabc2017-04-26 16:39:58 +00001000 else if (Known.Zero.isSignBitSet() || Known2.Zero.isSignBitSet())
David Majnemera19d0f22016-08-06 08:16:00 +00001001 MaxHighZeros = 1;
1002 } else if (SPF == SPF_SMIN) {
1003 // If both sides are non-negative, the result is non-negative.
Craig Topperb45eabc2017-04-26 16:39:58 +00001004 if (Known.Zero.isSignBitSet() && Known2.Zero.isSignBitSet())
David Majnemera19d0f22016-08-06 08:16:00 +00001005 // We can derive an upper bound on the result by taking the max of the
1006 // leading zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001007 MaxHighZeros = std::max(Known.Zero.countLeadingOnes(),
1008 Known2.Zero.countLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001009 // If either side is negative, the result is negative.
Craig Topperb45eabc2017-04-26 16:39:58 +00001010 else if (Known.One.isSignBitSet() || Known2.One.isSignBitSet())
David Majnemera19d0f22016-08-06 08:16:00 +00001011 MaxHighOnes = 1;
1012 } else if (SPF == SPF_UMAX) {
1013 // We can derive a lower bound on the result by taking the max of the
1014 // leading one bits.
1015 MaxHighOnes =
Craig Topperb45eabc2017-04-26 16:39:58 +00001016 std::max(Known.One.countLeadingOnes(), Known2.One.countLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001017 } else if (SPF == SPF_UMIN) {
1018 // We can derive an upper bound on the result by taking the max of the
1019 // leading zero bits.
1020 MaxHighZeros =
Craig Topperb45eabc2017-04-26 16:39:58 +00001021 std::max(Known.Zero.countLeadingOnes(), Known2.Zero.countLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001022 }
1023
Chris Lattner965c7692008-06-02 01:18:21 +00001024 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001025 Known.One &= Known2.One;
1026 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001027 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001028 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001029 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001030 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001031 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001032 }
Chris Lattner965c7692008-06-02 01:18:21 +00001033 case Instruction::FPTrunc:
1034 case Instruction::FPExt:
1035 case Instruction::FPToUI:
1036 case Instruction::FPToSI:
1037 case Instruction::SIToFP:
1038 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001039 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001040 case Instruction::PtrToInt:
1041 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001042 // Fall through and handle them the same as zext/trunc.
1043 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001044 case Instruction::ZExt:
1045 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001046 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001047
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001048 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001049 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1050 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001051 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001052
1053 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperb45eabc2017-04-26 16:39:58 +00001054 Known.Zero = Known.Zero.zextOrTrunc(SrcBitWidth);
1055 Known.One = Known.One.zextOrTrunc(SrcBitWidth);
1056 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1057 Known.Zero = Known.Zero.zextOrTrunc(BitWidth);
1058 Known.One = Known.One.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001059 // Any top bits are known to be zero.
1060 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001061 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001062 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001063 }
1064 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001065 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001066 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001067 // TODO: For now, not handling conversions like:
1068 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001069 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001070 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001071 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001072 }
1073 break;
1074 }
1075 case Instruction::SExt: {
1076 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001077 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001078
Craig Topperb45eabc2017-04-26 16:39:58 +00001079 Known.Zero = Known.Zero.trunc(SrcBitWidth);
1080 Known.One = Known.One.trunc(SrcBitWidth);
1081 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001082 // If the sign bit of the input is known set or clear, then we know the
1083 // top bits of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001084 Known.Zero = Known.Zero.sext(BitWidth);
1085 Known.One = Known.One.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001086 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001087 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001088 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001089 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001090 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001091 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1092 APInt KZResult = KnownZero << ShiftAmt;
1093 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001094 // If this shift has "nsw" keyword, then the result is either a poison
1095 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001096 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001097 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001098 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001099 };
1100
Craig Topperd73c6b42017-03-23 07:06:39 +00001101 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001102 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001103 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001104 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001105 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001106 };
1107
Craig Topperb45eabc2017-04-26 16:39:58 +00001108 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001109 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001110 }
1111 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001112 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001113 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1114 APInt KZResult = KnownZero.lshr(ShiftAmt);
1115 // High bits known zero.
1116 KZResult.setHighBits(ShiftAmt);
1117 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001118 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001119
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001120 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001121 return KnownOne.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001122 };
1123
Craig Topperb45eabc2017-04-26 16:39:58 +00001124 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001125 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001126 }
1127 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001128 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001129 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001130 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001131 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001132
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001133 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001134 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001135 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001136
Craig Topperb45eabc2017-04-26 16:39:58 +00001137 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001138 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001139 }
Chris Lattner965c7692008-06-02 01:18:21 +00001140 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001141 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001142 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001143 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001144 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001145 }
Chris Lattner965c7692008-06-02 01:18:21 +00001146 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001147 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001148 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001149 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001150 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001151 }
1152 case Instruction::SRem:
1153 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001154 APInt RA = Rem->getValue().abs();
1155 if (RA.isPowerOf2()) {
1156 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001157 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001158
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001159 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001160 Known.Zero = Known2.Zero & LowBits;
1161 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001162
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001163 // If the first operand is non-negative or has all low bits zero, then
1164 // the upper bits are all zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001165 if (Known2.Zero.isSignBitSet() || ((Known2.Zero & LowBits) == LowBits))
1166 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001167
1168 // If the first operand is negative and not all low bits are zero, then
1169 // the upper bits are all one.
Craig Topperb45eabc2017-04-26 16:39:58 +00001170 if (Known2.One.isSignBitSet() && ((Known2.One & LowBits) != 0))
1171 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001172
Craig Topperb45eabc2017-04-26 16:39:58 +00001173 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001174 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001175 }
1176 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001177
1178 // The sign bit is the LHS's sign bit, except when the result of the
1179 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001180 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001181 // If it's known zero, our sign bit is also zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001182 if (Known2.Zero.isSignBitSet())
1183 Known.Zero.setSignBit();
Nick Lewyckye4679792011-03-07 01:50:10 +00001184
Chris Lattner965c7692008-06-02 01:18:21 +00001185 break;
1186 case Instruction::URem: {
1187 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001188 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001189 if (RA.isPowerOf2()) {
1190 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001191 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1192 Known.Zero |= ~LowBits;
1193 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001194 break;
1195 }
1196 }
1197
1198 // Since the result is less than or equal to either operand, any leading
1199 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001200 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1201 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001202
Craig Topperb45eabc2017-04-26 16:39:58 +00001203 unsigned Leaders = std::max(Known.Zero.countLeadingOnes(),
1204 Known2.Zero.countLeadingOnes());
1205 Known.One.clearAllBits();
1206 Known.Zero.clearAllBits();
1207 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001208 break;
1209 }
1210
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001211 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001212 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001213 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001214 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001215 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001216
Chris Lattner965c7692008-06-02 01:18:21 +00001217 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001218 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001219 break;
1220 }
1221 case Instruction::GetElementPtr: {
1222 // Analyze all of the subscripts of this getelementptr instruction
1223 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001224 KnownBits LocalKnown(BitWidth);
1225 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
1226 unsigned TrailZ = LocalKnown.Zero.countTrailingOnes();
Chris Lattner965c7692008-06-02 01:18:21 +00001227
1228 gep_type_iterator GTI = gep_type_begin(I);
1229 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1230 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001231 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001232 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001233
1234 // Handle case when index is vector zeroinitializer
1235 Constant *CIndex = cast<Constant>(Index);
1236 if (CIndex->isZeroValue())
1237 continue;
1238
1239 if (CIndex->getType()->isVectorTy())
1240 Index = CIndex->getSplatValue();
1241
Chris Lattner965c7692008-06-02 01:18:21 +00001242 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001243 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001244 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001245 TrailZ = std::min<unsigned>(TrailZ,
1246 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001247 } else {
1248 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001249 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001250 if (!IndexedTy->isSized()) {
1251 TrailZ = 0;
1252 break;
1253 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001254 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001255 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001256 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1257 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001258 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001259 unsigned(countTrailingZeros(TypeSize) +
Craig Topperb45eabc2017-04-26 16:39:58 +00001260 LocalKnown.Zero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001261 }
1262 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001263
Craig Topperb45eabc2017-04-26 16:39:58 +00001264 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001265 break;
1266 }
1267 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001268 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001269 // Handle the case of a simple two-predecessor recurrence PHI.
1270 // There's a lot more that could theoretically be done here, but
1271 // this is sufficient to catch some interesting cases.
1272 if (P->getNumIncomingValues() == 2) {
1273 for (unsigned i = 0; i != 2; ++i) {
1274 Value *L = P->getIncomingValue(i);
1275 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001276 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001277 if (!LU)
1278 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001279 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001280 // Check for operations that have the property that if
1281 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001282 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001283 if (Opcode == Instruction::Add ||
1284 Opcode == Instruction::Sub ||
1285 Opcode == Instruction::And ||
1286 Opcode == Instruction::Or ||
1287 Opcode == Instruction::Mul) {
1288 Value *LL = LU->getOperand(0);
1289 Value *LR = LU->getOperand(1);
1290 // Find a recurrence.
1291 if (LL == I)
1292 L = LR;
1293 else if (LR == I)
1294 L = LL;
1295 else
1296 break;
1297 // Ok, we have a PHI of the form L op= R. Check for low
1298 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001299 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001300
1301 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001302 KnownBits Known3(Known);
1303 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001304
Craig Topperb45eabc2017-04-26 16:39:58 +00001305 Known.Zero.setLowBits(std::min(Known2.Zero.countTrailingOnes(),
1306 Known3.Zero.countTrailingOnes()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001307
1308 if (DontImproveNonNegativePhiBits)
1309 break;
1310
1311 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1312 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1313 // If initial value of recurrence is nonnegative, and we are adding
1314 // a nonnegative number with nsw, the result can only be nonnegative
1315 // or poison value regardless of the number of times we execute the
1316 // add in phi recurrence. If initial value is negative and we are
1317 // adding a negative number with nsw, the result can only be
1318 // negative or poison value. Similar arguments apply to sub and mul.
1319 //
1320 // (add non-negative, non-negative) --> non-negative
1321 // (add negative, negative) --> negative
1322 if (Opcode == Instruction::Add) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001323 if (Known2.Zero.isSignBitSet() && Known3.Zero.isSignBitSet())
1324 Known.Zero.setSignBit();
1325 else if (Known2.One.isSignBitSet() && Known3.One.isSignBitSet())
1326 Known.One.setSignBit();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001327 }
1328
1329 // (sub nsw non-negative, negative) --> non-negative
1330 // (sub nsw negative, non-negative) --> negative
1331 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001332 if (Known2.Zero.isSignBitSet() && Known3.One.isSignBitSet())
1333 Known.Zero.setSignBit();
1334 else if (Known2.One.isSignBitSet() && Known3.Zero.isSignBitSet())
1335 Known.One.setSignBit();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001336 }
1337
1338 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperb45eabc2017-04-26 16:39:58 +00001339 else if (Opcode == Instruction::Mul && Known2.Zero.isSignBitSet() &&
1340 Known3.Zero.isSignBitSet())
1341 Known.Zero.setSignBit();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001342 }
1343
Chris Lattner965c7692008-06-02 01:18:21 +00001344 break;
1345 }
1346 }
1347 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001348
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001349 // Unreachable blocks may have zero-operand PHI nodes.
1350 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001351 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001352
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001353 // Otherwise take the unions of the known bit sets of the operands,
1354 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001355 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001356 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001357 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001358 break;
1359
Craig Topperb45eabc2017-04-26 16:39:58 +00001360 Known.Zero.setAllBits();
1361 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001362 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001363 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001364 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001365
Craig Topperb45eabc2017-04-26 16:39:58 +00001366 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001367 // Recurse, but cap the recursion to one level, because we don't
1368 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001369 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1370 Known.Zero &= Known2.Zero;
1371 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001372 // If all bits have been ruled out, there's no need to check
1373 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001374 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001375 break;
1376 }
1377 }
Chris Lattner965c7692008-06-02 01:18:21 +00001378 break;
1379 }
1380 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001381 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001382 // If range metadata is attached to this call, set known bits from that,
1383 // and then intersect with known bits based on other properties of the
1384 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001385 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001386 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001387 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001388 computeKnownBits(RV, Known2, Depth + 1, Q);
1389 Known.Zero |= Known2.Zero;
1390 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001391 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001392 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001393 switch (II->getIntrinsicID()) {
1394 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001395 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001396 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1397 Known.Zero |= Known2.Zero.reverseBits();
1398 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001399 break;
Philip Reames675418e2015-10-06 20:20:45 +00001400 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001401 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1402 Known.Zero |= Known2.Zero.byteSwap();
1403 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001404 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001405 case Intrinsic::ctlz:
1406 case Intrinsic::cttz: {
1407 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001408 // If this call is undefined for 0, the result will be less than 2^n.
1409 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1410 LowBits -= 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001411 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001412 break;
1413 }
1414 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001415 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001416 // We can bound the space the count needs. Also, bits known to be zero
1417 // can't contribute to the population.
Craig Topperb45eabc2017-04-26 16:39:58 +00001418 unsigned BitsPossiblySet = BitWidth - Known2.Zero.countPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001419 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001420 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001421 // TODO: we could bound KnownOne using the lower bound on the number
1422 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001423 break;
1424 }
Chad Rosierb3628842011-05-26 23:13:19 +00001425 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001426 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001427 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001428 }
1429 }
1430 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001431 case Instruction::ExtractElement:
1432 // Look through extract element. At the moment we keep this simple and skip
1433 // tracking the specific element. But at least we might find information
1434 // valid for all elements of the vector (for example if vector is sign
1435 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001436 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001437 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001438 case Instruction::ExtractValue:
1439 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001440 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001441 if (EVI->getNumIndices() != 1) break;
1442 if (EVI->getIndices()[0] == 0) {
1443 switch (II->getIntrinsicID()) {
1444 default: break;
1445 case Intrinsic::uadd_with_overflow:
1446 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001447 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001448 II->getArgOperand(1), false, Known, Known2,
1449 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001450 break;
1451 case Intrinsic::usub_with_overflow:
1452 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001453 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001454 II->getArgOperand(1), false, Known, Known2,
1455 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001456 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001457 case Intrinsic::umul_with_overflow:
1458 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001459 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001460 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001461 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001462 }
1463 }
1464 }
Chris Lattner965c7692008-06-02 01:18:21 +00001465 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001466}
1467
1468/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001469/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001470///
1471/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1472/// we cannot optimize based on the assumption that it is zero without changing
1473/// it to be an explicit zero. If we don't change it to zero, other code could
1474/// optimized based on the contradictory assumption that it is non-zero.
1475/// Because instcombine aggressively folds operations with undef args anyway,
1476/// this won't lose us code quality.
1477///
1478/// This function is defined on values with integer type, values with pointer
1479/// type, and vectors of integers. In the case
1480/// where V is a vector, known zero, and known one values are the
1481/// same width as the vector element, and the bit is set only if it is true
1482/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001483void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1484 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001485 assert(V && "No Value?");
1486 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001487 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001488
1489 assert((V->getType()->isIntOrIntVectorTy() ||
1490 V->getType()->getScalarType()->isPointerTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001491 "Not integer or pointer type!");
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001492 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Jingyue Wu12b0c282015-06-15 05:46:29 +00001493 (!V->getType()->isIntOrIntVectorTy() ||
1494 V->getType()->getScalarSizeInBits() == BitWidth) &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001495 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001496 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001497
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001498 const APInt *C;
1499 if (match(V, m_APInt(C))) {
1500 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001501 Known.One = *C;
1502 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001503 return;
1504 }
1505 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001506 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001507 Known.One.clearAllBits();
1508 Known.Zero.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001509 return;
1510 }
1511 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001512 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001513 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001514 // We know that CDS must be a vector of integers. Take the intersection of
1515 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001516 Known.Zero.setAllBits(); Known.One.setAllBits();
Craig Topper9c932d32017-04-25 16:48:03 +00001517 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001518 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1519 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001520 Known.Zero &= ~Elt;
1521 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001522 }
1523 return;
1524 }
1525
Pete Cooper35b00d52016-08-13 01:05:32 +00001526 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001527 // We know that CV must be a vector of integers. Take the intersection of
1528 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001529 Known.Zero.setAllBits(); Known.One.setAllBits();
1530 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001531 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1532 Constant *Element = CV->getAggregateElement(i);
1533 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1534 if (!ElementCI) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001535 Known.Zero.clearAllBits();
1536 Known.One.clearAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001537 return;
1538 }
1539 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001540 Known.Zero &= ~Elt;
1541 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001542 }
1543 return;
1544 }
1545
Jingyue Wu12b0c282015-06-15 05:46:29 +00001546 // Start out not knowing anything.
Craig Topperb45eabc2017-04-26 16:39:58 +00001547 Known.Zero.clearAllBits(); Known.One.clearAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001548
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001549 // We can't imply anything about undefs.
1550 if (isa<UndefValue>(V))
1551 return;
1552
1553 // There's no point in looking through other users of ConstantData for
1554 // assumptions. Confirm that we've handled them all.
1555 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1556
Jingyue Wu12b0c282015-06-15 05:46:29 +00001557 // Limit search depth.
1558 // All recursive calls that increase depth must come after this.
1559 if (Depth == MaxDepth)
1560 return;
1561
1562 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1563 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001564 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001565 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001566 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001567 return;
1568 }
1569
Pete Cooper35b00d52016-08-13 01:05:32 +00001570 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001571 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001572
Craig Topperb45eabc2017-04-26 16:39:58 +00001573 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001574 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001575 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001576 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001577 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001578 }
1579
Craig Topperb45eabc2017-04-26 16:39:58 +00001580 // computeKnownBitsFromAssume strictly refines Known.
1581 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001582
1583 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001584 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001585
Craig Topperb45eabc2017-04-26 16:39:58 +00001586 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001587}
1588
Sanjay Patelaee84212014-11-04 16:27:42 +00001589/// Determine whether the sign bit is known to be zero or one.
1590/// Convenience wrapper around computeKnownBits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001591void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001592 unsigned Depth, const Query &Q) {
1593 unsigned BitWidth = getBitWidth(V->getType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001594 if (!BitWidth) {
1595 KnownZero = false;
1596 KnownOne = false;
1597 return;
1598 }
Craig Topperb45eabc2017-04-26 16:39:58 +00001599 KnownBits Bits(BitWidth);
1600 computeKnownBits(V, Bits, Depth, Q);
1601 KnownOne = Bits.One.isSignBitSet();
1602 KnownZero = Bits.Zero.isSignBitSet();
Duncan Sandsd3951082011-01-25 09:38:29 +00001603}
1604
Sanjay Patelaee84212014-11-04 16:27:42 +00001605/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001606/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001607/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001608/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001609bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001610 const Query &Q) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001611 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001612 if (C->isNullValue())
1613 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001614
1615 const APInt *ConstIntOrConstSplatInt;
1616 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1617 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001618 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001619
1620 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1621 // it is shifted off the end then the result is undefined.
1622 if (match(V, m_Shl(m_One(), m_Value())))
1623 return true;
1624
Craig Topperbcfd2d12017-04-20 16:56:25 +00001625 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1626 // the bottom. If it is shifted off the bottom then the result is undefined.
1627 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001628 return true;
1629
1630 // The remaining tests are all recursive, so bail out if we hit the limit.
1631 if (Depth++ == MaxDepth)
1632 return false;
1633
Craig Topper9f008862014-04-15 04:59:12 +00001634 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001635 // A shift left or a logical shift right of a power of two is a power of two
1636 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001637 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001638 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001639 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001640
Pete Cooper35b00d52016-08-13 01:05:32 +00001641 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001642 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001643
Pete Cooper35b00d52016-08-13 01:05:32 +00001644 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001645 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1646 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001647
Duncan Sandsba286d72011-10-26 20:55:21 +00001648 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1649 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001650 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1651 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001652 return true;
1653 // X & (-X) is always a power of two or zero.
1654 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1655 return true;
1656 return false;
1657 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001658
David Majnemerb7d54092013-07-30 21:01:36 +00001659 // Adding a power-of-two or zero to the same power-of-two or zero yields
1660 // either the original power-of-two, a larger power-of-two or zero.
1661 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001662 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001663 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1664 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1665 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001666 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001667 return true;
1668 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1669 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001670 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001671 return true;
1672
1673 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001674 KnownBits LHSBits(BitWidth);
1675 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001676
Craig Topperb45eabc2017-04-26 16:39:58 +00001677 KnownBits RHSBits(BitWidth);
1678 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001679 // If i8 V is a power of two or zero:
1680 // ZeroBits: 1 1 1 0 1 1 1 1
1681 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001682 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001683 // If OrZero isn't set, we cannot give back a zero result.
1684 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001685 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001686 return true;
1687 }
1688 }
David Majnemerbeab5672013-05-18 19:30:37 +00001689
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001690 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001691 // is a power of two only if the first operand is a power of two and not
1692 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001693 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1694 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001695 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001696 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001697 }
1698
Duncan Sandsd3951082011-01-25 09:38:29 +00001699 return false;
1700}
1701
Chandler Carruth80d3e562012-12-07 02:08:58 +00001702/// \brief Test whether a GEP's result is known to be non-null.
1703///
1704/// Uses properties inherent in a GEP to try to determine whether it is known
1705/// to be non-null.
1706///
1707/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001708static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001709 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001710 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1711 return false;
1712
1713 // FIXME: Support vector-GEPs.
1714 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1715
1716 // If the base pointer is non-null, we cannot walk to a null address with an
1717 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001718 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001719 return true;
1720
Chandler Carruth80d3e562012-12-07 02:08:58 +00001721 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1722 // If so, then the GEP cannot produce a null pointer, as doing so would
1723 // inherently violate the inbounds contract within address space zero.
1724 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1725 GTI != GTE; ++GTI) {
1726 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001727 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001728 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1729 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001730 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001731 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1732 if (ElementOffset > 0)
1733 return true;
1734 continue;
1735 }
1736
1737 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001738 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001739 continue;
1740
1741 // Fast path the constant operand case both for efficiency and so we don't
1742 // increment Depth when just zipping down an all-constant GEP.
1743 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1744 if (!OpC->isZero())
1745 return true;
1746 continue;
1747 }
1748
1749 // We post-increment Depth here because while isKnownNonZero increments it
1750 // as well, when we pop back up that increment won't persist. We don't want
1751 // to recurse 10k times just because we have 10k GEP operands. We don't
1752 // bail completely out because we want to handle constant GEPs regardless
1753 // of depth.
1754 if (Depth++ >= MaxDepth)
1755 continue;
1756
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001757 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001758 return true;
1759 }
1760
1761 return false;
1762}
1763
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001764/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1765/// ensure that the value it's attached to is never Value? 'RangeType' is
1766/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001767static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001768 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1769 assert(NumRanges >= 1);
1770 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001771 ConstantInt *Lower =
1772 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1773 ConstantInt *Upper =
1774 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001775 ConstantRange Range(Lower->getValue(), Upper->getValue());
1776 if (Range.contains(Value))
1777 return false;
1778 }
1779 return true;
1780}
1781
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001782/// Return true if the given value is known to be non-zero when defined. For
1783/// vectors, return true if every element is known to be non-zero when
1784/// defined. For pointers, if the context instruction and dominator tree are
1785/// specified, perform context-sensitive analysis and return true if the
1786/// pointer couldn't possibly be null at the specified instruction.
1787/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001788bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001789 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001790 if (C->isNullValue())
1791 return false;
1792 if (isa<ConstantInt>(C))
1793 // Must be non-zero due to null test above.
1794 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001795
1796 // For constant vectors, check that all elements are undefined or known
1797 // non-zero to determine that the whole vector is known non-zero.
1798 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1799 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1800 Constant *Elt = C->getAggregateElement(i);
1801 if (!Elt || Elt->isNullValue())
1802 return false;
1803 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1804 return false;
1805 }
1806 return true;
1807 }
1808
Duncan Sandsd3951082011-01-25 09:38:29 +00001809 return false;
1810 }
1811
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001812 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001813 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001814 // If the possible ranges don't contain zero, then the value is
1815 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001816 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001817 const APInt ZeroValue(Ty->getBitWidth(), 0);
1818 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1819 return true;
1820 }
1821 }
1822 }
1823
Duncan Sandsd3951082011-01-25 09:38:29 +00001824 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001825 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001826 return false;
1827
Chandler Carruth80d3e562012-12-07 02:08:58 +00001828 // Check for pointer simplifications.
1829 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001830 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001831 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001832 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001833 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001834 return true;
1835 }
1836
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001837 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001838
1839 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001840 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001841 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001842 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001843
1844 // ext X != 0 if X != 0.
1845 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001846 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001847
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001848 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001849 // if the lowest bit is shifted off the end.
1850 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001851 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001852 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001853 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001854 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001855
Craig Topperb45eabc2017-04-26 16:39:58 +00001856 KnownBits Known(BitWidth);
1857 computeKnownBits(X, Known, Depth, Q);
1858 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001859 return true;
1860 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001861 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001862 // defined if the sign bit is shifted off the end.
1863 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001864 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001865 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001866 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001867 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001868
Duncan Sandsd3951082011-01-25 09:38:29 +00001869 bool XKnownNonNegative, XKnownNegative;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001870 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001871 if (XKnownNegative)
1872 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001873
1874 // If the shifter operand is a constant, and all of the bits shifted
1875 // out are known to be zero, and X is known non-zero then at least one
1876 // non-zero bit must remain.
1877 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001878 KnownBits Known(BitWidth);
1879 computeKnownBits(X, Known, Depth, Q);
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001880
James Molloyb6be1eb2015-09-24 16:06:32 +00001881 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1882 // Is there a known one in the portion not shifted out?
Craig Topperb45eabc2017-04-26 16:39:58 +00001883 if (Known.One.countLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001884 return true;
1885 // Are all the bits to be shifted out known zero?
Craig Topperb45eabc2017-04-26 16:39:58 +00001886 if (Known.Zero.countTrailingOnes() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001887 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001888 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001889 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001890 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001891 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001892 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001893 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001894 // X + Y.
1895 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1896 bool XKnownNonNegative, XKnownNegative;
1897 bool YKnownNonNegative, YKnownNegative;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001898 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1899 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001900
1901 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001902 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001903 if (XKnownNonNegative && YKnownNonNegative)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001904 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001905 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001906
1907 // If X and Y are both negative (as signed values) then their sum is not
1908 // zero unless both X and Y equal INT_MIN.
1909 if (BitWidth && XKnownNegative && YKnownNegative) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001910 KnownBits Known(BitWidth);
Duncan Sandsd3951082011-01-25 09:38:29 +00001911 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1912 // The sign bit of X is set. If some other bit is set then X is not equal
1913 // to INT_MIN.
Craig Topperb45eabc2017-04-26 16:39:58 +00001914 computeKnownBits(X, Known, Depth, Q);
1915 if (Known.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001916 return true;
1917 // The sign bit of Y is set. If some other bit is set then Y is not equal
1918 // to INT_MIN.
Craig Topperb45eabc2017-04-26 16:39:58 +00001919 computeKnownBits(Y, Known, Depth, Q);
1920 if (Known.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001921 return true;
1922 }
1923
1924 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001925 if (XKnownNonNegative &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001926 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001927 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00001928 if (YKnownNonNegative &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001929 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001930 return true;
1931 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001932 // X * Y.
1933 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001934 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001935 // If X and Y are non-zero then so is X * Y as long as the multiplication
1936 // does not overflow.
1937 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001938 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001939 return true;
1940 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001941 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001942 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001943 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1944 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001945 return true;
1946 }
James Molloy897048b2015-09-29 14:08:45 +00001947 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001948 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001949 // Try and detect a recurrence that monotonically increases from a
1950 // starting value, as these are common as induction variables.
1951 if (PN->getNumIncomingValues() == 2) {
1952 Value *Start = PN->getIncomingValue(0);
1953 Value *Induction = PN->getIncomingValue(1);
1954 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1955 std::swap(Start, Induction);
1956 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1957 if (!C->isZero() && !C->isNegative()) {
1958 ConstantInt *X;
1959 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1960 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1961 !X->isNegative())
1962 return true;
1963 }
1964 }
1965 }
Jun Bum Limca832662016-02-01 17:03:07 +00001966 // Check if all incoming values are non-zero constant.
1967 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1968 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
1969 });
1970 if (AllNonZeroConstants)
1971 return true;
James Molloy897048b2015-09-29 14:08:45 +00001972 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001973
1974 if (!BitWidth) return false;
Craig Topperb45eabc2017-04-26 16:39:58 +00001975 KnownBits Known(BitWidth);
1976 computeKnownBits(V, Known, Depth, Q);
1977 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001978}
1979
James Molloy1d88d6f2015-10-22 13:18:42 +00001980/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001981static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1982 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001983 if (!BO || BO->getOpcode() != Instruction::Add)
1984 return false;
1985 Value *Op = nullptr;
1986 if (V2 == BO->getOperand(0))
1987 Op = BO->getOperand(1);
1988 else if (V2 == BO->getOperand(1))
1989 Op = BO->getOperand(0);
1990 else
1991 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001992 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001993}
1994
1995/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001996static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001997 if (V1->getType()->isVectorTy() || V1 == V2)
1998 return false;
1999 if (V1->getType() != V2->getType())
2000 // We can't look through casts yet.
2001 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002002 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002003 return true;
2004
2005 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
2006 // Are any known bits in V1 contradictory to known bits in V2? If V1
2007 // has a known zero where V2 has a known one, they must not be equal.
2008 auto BitWidth = Ty->getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00002009 KnownBits Known1(BitWidth);
2010 computeKnownBits(V1, Known1, 0, Q);
2011 KnownBits Known2(BitWidth);
2012 computeKnownBits(V2, Known2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002013
Craig Topperb45eabc2017-04-26 16:39:58 +00002014 APInt OppositeBits = (Known1.Zero & Known2.One) |
2015 (Known2.Zero & Known1.One);
James Molloy1d88d6f2015-10-22 13:18:42 +00002016 if (OppositeBits.getBoolValue())
2017 return true;
2018 }
2019 return false;
2020}
2021
Sanjay Patelaee84212014-11-04 16:27:42 +00002022/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2023/// simplify operations downstream. Mask is known to be zero for bits that V
2024/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002025///
2026/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002027/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002028/// where V is a vector, the mask, known zero, and known one values are the
2029/// same width as the vector element, and the bit is set only if it is true
2030/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002031bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002032 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002033 KnownBits Known(Mask.getBitWidth());
2034 computeKnownBits(V, Known, Depth, Q);
2035 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002036}
2037
Sanjay Patela06d9892016-06-22 19:20:59 +00002038/// For vector constants, loop over the elements and find the constant with the
2039/// minimum number of sign bits. Return 0 if the value is not a vector constant
2040/// or if any element was not analyzed; otherwise, return the count for the
2041/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002042static unsigned computeNumSignBitsVectorConstant(const Value *V,
2043 unsigned TyBits) {
2044 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002045 if (!CV || !CV->getType()->isVectorTy())
2046 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002047
Sanjay Patela06d9892016-06-22 19:20:59 +00002048 unsigned MinSignBits = TyBits;
2049 unsigned NumElts = CV->getType()->getVectorNumElements();
2050 for (unsigned i = 0; i != NumElts; ++i) {
2051 // If we find a non-ConstantInt, bail out.
2052 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2053 if (!Elt)
2054 return 0;
2055
2056 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2057 APInt EltVal = Elt->getValue();
2058 if (EltVal.isNegative())
2059 EltVal = ~EltVal;
2060 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2061 }
2062
2063 return MinSignBits;
2064}
Chris Lattner965c7692008-06-02 01:18:21 +00002065
Sanjoy Das39a684d2017-02-25 20:30:45 +00002066static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2067 const Query &Q);
2068
2069static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2070 const Query &Q) {
2071 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2072 assert(Result > 0 && "At least one sign bit needs to be present!");
2073 return Result;
2074}
2075
Sanjay Patelaee84212014-11-04 16:27:42 +00002076/// Return the number of times the sign bit of the register is replicated into
2077/// the other bits. We know that at least 1 bit is always equal to the sign bit
2078/// (itself), but other cases can give us information. For example, immediately
2079/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002080/// other, so we return 3. For vectors, return the number of sign bits for the
2081/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002082static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2083 const Query &Q) {
2084
2085 // We return the minimum number of sign bits that are guaranteed to be present
2086 // in V, so for undef we have to conservatively return 1. We don't have the
2087 // same behavior for poison though -- that's a FIXME today.
2088
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002089 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002090 unsigned Tmp, Tmp2;
2091 unsigned FirstAnswer = 1;
2092
Jay Foada0653a32014-05-14 21:14:37 +00002093 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002094 // below.
2095
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002096 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002097 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002098
Pete Cooper35b00d52016-08-13 01:05:32 +00002099 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002100 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002101 default: break;
2102 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002103 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002104 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002105
Nadav Rotemc99a3872015-03-06 00:23:58 +00002106 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002107 const APInt *Denominator;
2108 // sdiv X, C -> adds log(C) sign bits.
2109 if (match(U->getOperand(1), m_APInt(Denominator))) {
2110
2111 // Ignore non-positive denominator.
2112 if (!Denominator->isStrictlyPositive())
2113 break;
2114
2115 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002116 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002117
2118 // Add floor(log(C)) bits to the numerator bits.
2119 return std::min(TyBits, NumBits + Denominator->logBase2());
2120 }
2121 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002122 }
2123
2124 case Instruction::SRem: {
2125 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002126 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2127 // positive constant. This let us put a lower bound on the number of sign
2128 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002129 if (match(U->getOperand(1), m_APInt(Denominator))) {
2130
2131 // Ignore non-positive denominator.
2132 if (!Denominator->isStrictlyPositive())
2133 break;
2134
2135 // Calculate the incoming numerator bits. SRem by a positive constant
2136 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002137 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002138 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002139
2140 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002141 // denominator. Given that the denominator is positive, there are two
2142 // cases:
2143 //
2144 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2145 // (1 << ceilLogBase2(C)).
2146 //
2147 // 2. the numerator is negative. Then the result range is (-C,0] and
2148 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2149 //
2150 // Thus a lower bound on the number of sign bits is `TyBits -
2151 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002152
Sanjoy Dase561fee2015-03-25 22:33:53 +00002153 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002154 return std::max(NumrBits, ResBits);
2155 }
2156 break;
2157 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002158
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002159 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002160 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002161 // ashr X, C -> adds C sign bits. Vectors too.
2162 const APInt *ShAmt;
2163 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002164 unsigned ShAmtLimited = ShAmt->getZExtValue();
2165 if (ShAmtLimited >= TyBits)
2166 break; // Bad shift.
2167 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002168 if (Tmp > TyBits) Tmp = TyBits;
2169 }
2170 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002171 }
2172 case Instruction::Shl: {
2173 const APInt *ShAmt;
2174 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002175 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002176 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002177 Tmp2 = ShAmt->getZExtValue();
2178 if (Tmp2 >= TyBits || // Bad shift.
2179 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2180 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002181 }
2182 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002183 }
Chris Lattner965c7692008-06-02 01:18:21 +00002184 case Instruction::And:
2185 case Instruction::Or:
2186 case Instruction::Xor: // NOT is handled here.
2187 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002188 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002189 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002190 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002191 FirstAnswer = std::min(Tmp, Tmp2);
2192 // We computed what we know about the sign bits as our first
2193 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002194 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002195 }
2196 break;
2197
2198 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002199 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002200 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002201 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002202 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002203
Chris Lattner965c7692008-06-02 01:18:21 +00002204 case Instruction::Add:
2205 // Add can have at most one carry bit. Thus we know that the output
2206 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002207 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002208 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002209
Chris Lattner965c7692008-06-02 01:18:21 +00002210 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002211 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002212 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002213 KnownBits Known(TyBits);
2214 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002215
Chris Lattner965c7692008-06-02 01:18:21 +00002216 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2217 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002218 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002219 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002220
Chris Lattner965c7692008-06-02 01:18:21 +00002221 // If we are subtracting one from a positive number, there is no carry
2222 // out of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00002223 if (Known.Zero.isSignBitSet())
Chris Lattner965c7692008-06-02 01:18:21 +00002224 return Tmp;
2225 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002226
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002227 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002228 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002229 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002230
Chris Lattner965c7692008-06-02 01:18:21 +00002231 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002232 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002233 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002234
Chris Lattner965c7692008-06-02 01:18:21 +00002235 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002236 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002237 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002238 KnownBits Known(TyBits);
2239 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002240 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2241 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002242 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002243 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002244
Chris Lattner965c7692008-06-02 01:18:21 +00002245 // If the input is known to be positive (the sign bit is known clear),
2246 // the output of the NEG has the same number of sign bits as the input.
Craig Topperb45eabc2017-04-26 16:39:58 +00002247 if (Known.Zero.isSignBitSet())
Chris Lattner965c7692008-06-02 01:18:21 +00002248 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002249
Chris Lattner965c7692008-06-02 01:18:21 +00002250 // Otherwise, we treat this like a SUB.
2251 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002252
Chris Lattner965c7692008-06-02 01:18:21 +00002253 // Sub can have at most one carry bit. Thus we know that the output
2254 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002255 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002256 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002257 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002258
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002259 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002260 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002261 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002262 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002263 if (NumIncomingValues > 4) break;
2264 // Unreachable blocks may have zero-operand PHI nodes.
2265 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002266
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002267 // Take the minimum of all incoming values. This can't infinitely loop
2268 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002269 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002270 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002271 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002272 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002273 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002274 }
2275 return Tmp;
2276 }
2277
Chris Lattner965c7692008-06-02 01:18:21 +00002278 case Instruction::Trunc:
2279 // FIXME: it's tricky to do anything useful for this, but it is an important
2280 // case for targets like X86.
2281 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002282
2283 case Instruction::ExtractElement:
2284 // Look through extract element. At the moment we keep this simple and skip
2285 // tracking the specific element. But at least we might find information
2286 // valid for all elements of the vector (for example if vector is sign
2287 // extended, shifted, etc).
2288 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002289 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002290
Chris Lattner965c7692008-06-02 01:18:21 +00002291 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2292 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002293
2294 // If we can examine all elements of a vector constant successfully, we're
2295 // done (we can't do any better than that). If not, keep trying.
2296 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2297 return VecSignBits;
2298
Craig Topperb45eabc2017-04-26 16:39:58 +00002299 KnownBits Known(TyBits);
2300 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002301
Sanjay Patele0536212016-06-23 17:41:59 +00002302 // If we know that the sign bit is either zero or one, determine the number of
2303 // identical bits in the top of the input value.
Craig Topperb45eabc2017-04-26 16:39:58 +00002304 if (Known.Zero.isSignBitSet())
2305 return std::max(FirstAnswer, Known.Zero.countLeadingOnes());
Craig Topper1bef2c82012-12-22 19:15:35 +00002306
Craig Topperb45eabc2017-04-26 16:39:58 +00002307 if (Known.One.isSignBitSet())
2308 return std::max(FirstAnswer, Known.One.countLeadingOnes());
Sanjay Patele0536212016-06-23 17:41:59 +00002309
2310 // computeKnownBits gave us no extra information about the top bits.
2311 return FirstAnswer;
Chris Lattner965c7692008-06-02 01:18:21 +00002312}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002313
Sanjay Patelaee84212014-11-04 16:27:42 +00002314/// This function computes the integer multiple of Base that equals V.
2315/// If successful, it returns true and returns the multiple in
2316/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002317/// through SExt instructions only if LookThroughSExt is true.
2318bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002319 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002320 const unsigned MaxDepth = 6;
2321
Dan Gohman6a976bb2009-11-18 00:58:27 +00002322 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002323 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002324 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002325
Chris Lattner229907c2011-07-18 04:54:35 +00002326 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002327
Dan Gohman6a976bb2009-11-18 00:58:27 +00002328 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002329
2330 if (Base == 0)
2331 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002332
Victor Hernandez47444882009-11-10 08:28:35 +00002333 if (Base == 1) {
2334 Multiple = V;
2335 return true;
2336 }
2337
2338 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2339 Constant *BaseVal = ConstantInt::get(T, Base);
2340 if (CO && CO == BaseVal) {
2341 // Multiple is 1.
2342 Multiple = ConstantInt::get(T, 1);
2343 return true;
2344 }
2345
2346 if (CI && CI->getZExtValue() % Base == 0) {
2347 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002348 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002349 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002350
Victor Hernandez47444882009-11-10 08:28:35 +00002351 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002352
Victor Hernandez47444882009-11-10 08:28:35 +00002353 Operator *I = dyn_cast<Operator>(V);
2354 if (!I) return false;
2355
2356 switch (I->getOpcode()) {
2357 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002358 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002359 if (!LookThroughSExt) return false;
2360 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002361 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002362 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2363 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002364 case Instruction::Shl:
2365 case Instruction::Mul: {
2366 Value *Op0 = I->getOperand(0);
2367 Value *Op1 = I->getOperand(1);
2368
2369 if (I->getOpcode() == Instruction::Shl) {
2370 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2371 if (!Op1CI) return false;
2372 // Turn Op0 << Op1 into Op0 * 2^Op1
2373 APInt Op1Int = Op1CI->getValue();
2374 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002375 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002376 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002377 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002378 }
2379
Craig Topper9f008862014-04-15 04:59:12 +00002380 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002381 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2382 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2383 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002384 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002385 MulC->getType()->getPrimitiveSizeInBits())
2386 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002387 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002388 MulC->getType()->getPrimitiveSizeInBits())
2389 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002390
Chris Lattner72d283c2010-09-05 17:20:46 +00002391 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2392 Multiple = ConstantExpr::getMul(MulC, Op1C);
2393 return true;
2394 }
Victor Hernandez47444882009-11-10 08:28:35 +00002395
2396 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2397 if (Mul0CI->getValue() == 1) {
2398 // V == Base * Op1, so return Op1
2399 Multiple = Op1;
2400 return true;
2401 }
2402 }
2403
Craig Topper9f008862014-04-15 04:59:12 +00002404 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002405 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2406 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2407 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002408 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002409 MulC->getType()->getPrimitiveSizeInBits())
2410 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002411 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002412 MulC->getType()->getPrimitiveSizeInBits())
2413 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002414
Chris Lattner72d283c2010-09-05 17:20:46 +00002415 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2416 Multiple = ConstantExpr::getMul(MulC, Op0C);
2417 return true;
2418 }
Victor Hernandez47444882009-11-10 08:28:35 +00002419
2420 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2421 if (Mul1CI->getValue() == 1) {
2422 // V == Base * Op0, so return Op0
2423 Multiple = Op0;
2424 return true;
2425 }
2426 }
Victor Hernandez47444882009-11-10 08:28:35 +00002427 }
2428 }
2429
2430 // We could not determine if V is a multiple of Base.
2431 return false;
2432}
2433
David Majnemerb4b27232016-04-19 19:10:21 +00002434Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2435 const TargetLibraryInfo *TLI) {
2436 const Function *F = ICS.getCalledFunction();
2437 if (!F)
2438 return Intrinsic::not_intrinsic;
2439
2440 if (F->isIntrinsic())
2441 return F->getIntrinsicID();
2442
2443 if (!TLI)
2444 return Intrinsic::not_intrinsic;
2445
David L. Jonesd21529f2017-01-23 23:16:46 +00002446 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002447 // We're going to make assumptions on the semantics of the functions, check
2448 // that the target knows that it's available in this environment and it does
2449 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002450 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2451 return Intrinsic::not_intrinsic;
2452
2453 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002454 return Intrinsic::not_intrinsic;
2455
2456 // Otherwise check if we have a call to a function that can be turned into a
2457 // vector intrinsic.
2458 switch (Func) {
2459 default:
2460 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002461 case LibFunc_sin:
2462 case LibFunc_sinf:
2463 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002464 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_cos:
2466 case LibFunc_cosf:
2467 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002468 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002469 case LibFunc_exp:
2470 case LibFunc_expf:
2471 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002472 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002473 case LibFunc_exp2:
2474 case LibFunc_exp2f:
2475 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002476 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_log:
2478 case LibFunc_logf:
2479 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002480 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002481 case LibFunc_log10:
2482 case LibFunc_log10f:
2483 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002484 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 case LibFunc_log2:
2486 case LibFunc_log2f:
2487 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002488 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_fabs:
2490 case LibFunc_fabsf:
2491 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002492 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002493 case LibFunc_fmin:
2494 case LibFunc_fminf:
2495 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002496 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002497 case LibFunc_fmax:
2498 case LibFunc_fmaxf:
2499 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002500 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002501 case LibFunc_copysign:
2502 case LibFunc_copysignf:
2503 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002504 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002505 case LibFunc_floor:
2506 case LibFunc_floorf:
2507 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002508 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002509 case LibFunc_ceil:
2510 case LibFunc_ceilf:
2511 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002512 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002513 case LibFunc_trunc:
2514 case LibFunc_truncf:
2515 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002516 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002517 case LibFunc_rint:
2518 case LibFunc_rintf:
2519 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002520 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002521 case LibFunc_nearbyint:
2522 case LibFunc_nearbyintf:
2523 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002524 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002525 case LibFunc_round:
2526 case LibFunc_roundf:
2527 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002528 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002529 case LibFunc_pow:
2530 case LibFunc_powf:
2531 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002532 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002533 case LibFunc_sqrt:
2534 case LibFunc_sqrtf:
2535 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002536 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002537 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002538 return Intrinsic::not_intrinsic;
2539 }
2540
2541 return Intrinsic::not_intrinsic;
2542}
2543
Sanjay Patelaee84212014-11-04 16:27:42 +00002544/// Return true if we can prove that the specified FP value is never equal to
2545/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002546///
2547/// NOTE: this function will need to be revisited when we support non-default
2548/// rounding modes!
2549///
David Majnemer3ee5f342016-04-13 06:55:52 +00002550bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2551 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002552 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2553 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002554
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002555 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002556 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002557
Dan Gohman80ca01c2009-07-17 20:47:02 +00002558 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002559 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002560
2561 // Check if the nsz fast-math flag is set
2562 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2563 if (FPO->hasNoSignedZeros())
2564 return true;
2565
Chris Lattnera12a6de2008-06-02 01:29:46 +00002566 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002567 if (I->getOpcode() == Instruction::FAdd)
2568 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2569 if (CFP->isNullValue())
2570 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002571
Chris Lattnera12a6de2008-06-02 01:29:46 +00002572 // sitofp and uitofp turn into +0.0 for zero.
2573 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2574 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002575
David Majnemer3ee5f342016-04-13 06:55:52 +00002576 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002577 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002578 switch (IID) {
2579 default:
2580 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002581 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002582 case Intrinsic::sqrt:
2583 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2584 // fabs(x) != -0.0
2585 case Intrinsic::fabs:
2586 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002587 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002588 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002589
Chris Lattnera12a6de2008-06-02 01:29:46 +00002590 return false;
2591}
2592
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002593/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2594/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2595/// bit despite comparing equal.
2596static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2597 const TargetLibraryInfo *TLI,
2598 bool SignBitOnly,
2599 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002600 // TODO: This function does not do the right thing when SignBitOnly is true
2601 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2602 // which flips the sign bits of NaNs. See
2603 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2604
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002605 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2606 return !CFP->getValueAPF().isNegative() ||
2607 (!SignBitOnly && CFP->getValueAPF().isZero());
2608 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002609
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002610 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002611 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002612
2613 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002614 if (!I)
2615 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002616
2617 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002618 default:
2619 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002620 // Unsigned integers are always nonnegative.
2621 case Instruction::UIToFP:
2622 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002623 case Instruction::FMul:
2624 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002625 if (I->getOperand(0) == I->getOperand(1) &&
2626 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002627 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002628
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002629 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002630 case Instruction::FAdd:
2631 case Instruction::FDiv:
2632 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002633 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2634 Depth + 1) &&
2635 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2636 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002637 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002638 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2639 Depth + 1) &&
2640 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2641 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002642 case Instruction::FPExt:
2643 case Instruction::FPTrunc:
2644 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002645 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2646 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002647 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002648 const auto *CI = cast<CallInst>(I);
2649 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002650 switch (IID) {
2651 default:
2652 break;
2653 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002654 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2655 Depth + 1) ||
2656 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2657 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002658 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002659 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2660 Depth + 1) &&
2661 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2662 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002663 case Intrinsic::exp:
2664 case Intrinsic::exp2:
2665 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002666 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002667
2668 case Intrinsic::sqrt:
2669 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2670 if (!SignBitOnly)
2671 return true;
2672 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2673 CannotBeNegativeZero(CI->getOperand(0), TLI));
2674
David Majnemer3ee5f342016-04-13 06:55:52 +00002675 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002676 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002677 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002678 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002679 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002680 }
Justin Lebar322c1272017-01-27 00:58:34 +00002681 // TODO: This is not correct. Given that exp is an integer, here are the
2682 // ways that pow can return a negative value:
2683 //
2684 // pow(x, exp) --> negative if exp is odd and x is negative.
2685 // pow(-0, exp) --> -inf if exp is negative odd.
2686 // pow(-0, exp) --> -0 if exp is positive odd.
2687 // pow(-inf, exp) --> -0 if exp is negative odd.
2688 // pow(-inf, exp) --> -inf if exp is positive odd.
2689 //
2690 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2691 // but we must return false if x == -0. Unfortunately we do not currently
2692 // have a way of expressing this constraint. See details in
2693 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002694 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2695 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002696
David Majnemer3ee5f342016-04-13 06:55:52 +00002697 case Intrinsic::fma:
2698 case Intrinsic::fmuladd:
2699 // x*x+y is non-negative if y is non-negative.
2700 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002701 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2702 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2703 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002704 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002705 break;
2706 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002707 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002708}
2709
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002710bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2711 const TargetLibraryInfo *TLI) {
2712 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2713}
2714
2715bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2716 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2717}
2718
Sanjay Patelaee84212014-11-04 16:27:42 +00002719/// If the specified value can be set by repeating the same byte in memory,
2720/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002721/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2722/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2723/// byte store (e.g. i16 0x1234), return null.
2724Value *llvm::isBytewiseValue(Value *V) {
2725 // All byte-wide stores are splatable, even of arbitrary variables.
2726 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002727
2728 // Handle 'null' ConstantArrayZero etc.
2729 if (Constant *C = dyn_cast<Constant>(V))
2730 if (C->isNullValue())
2731 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002732
Chris Lattner9cb10352010-12-26 20:15:01 +00002733 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002734 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002735 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2736 if (CFP->getType()->isFloatTy())
2737 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2738 if (CFP->getType()->isDoubleTy())
2739 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2740 // Don't handle long double formats, which have strange constraints.
2741 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002742
Benjamin Kramer17d90152015-02-07 19:29:02 +00002743 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002744 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002745 if (CI->getBitWidth() % 8 == 0) {
2746 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002747
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002748 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002749 return nullptr;
2750 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002751 }
2752 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002753
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002754 // A ConstantDataArray/Vector is splatable if all its members are equal and
2755 // also splatable.
2756 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2757 Value *Elt = CA->getElementAsConstant(0);
2758 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002759 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002760 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002761
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002762 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2763 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002764 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002765
Chris Lattner9cb10352010-12-26 20:15:01 +00002766 return Val;
2767 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002768
Chris Lattner9cb10352010-12-26 20:15:01 +00002769 // Conceptually, we could handle things like:
2770 // %a = zext i8 %X to i16
2771 // %b = shl i16 %a, 8
2772 // %c = or i16 %a, %b
2773 // but until there is an example that actually needs this, it doesn't seem
2774 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002775 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002776}
2777
2778
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002779// This is the recursive version of BuildSubAggregate. It takes a few different
2780// arguments. Idxs is the index within the nested struct From that we are
2781// looking at now (which is of type IndexedType). IdxSkip is the number of
2782// indices from Idxs that should be left out when inserting into the resulting
2783// struct. To is the result struct built so far, new insertvalue instructions
2784// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002785static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002786 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002787 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002788 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002789 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002790 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002791 // Save the original To argument so we can modify it
2792 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002793 // General case, the type indexed by Idxs is a struct
2794 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2795 // Process each struct element recursively
2796 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002797 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002798 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002799 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002800 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002801 if (!To) {
2802 // Couldn't find any inserted value for this index? Cleanup
2803 while (PrevTo != OrigTo) {
2804 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2805 PrevTo = Del->getAggregateOperand();
2806 Del->eraseFromParent();
2807 }
2808 // Stop processing elements
2809 break;
2810 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002811 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002812 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002813 if (To)
2814 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002815 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002816 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2817 // the struct's elements had a value that was inserted directly. In the latter
2818 // case, perhaps we can't determine each of the subelements individually, but
2819 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002820
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002821 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002822 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002823
2824 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002825 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002826
2827 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002828 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002829 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002830}
2831
2832// This helper takes a nested struct and extracts a part of it (which is again a
2833// struct) into a new value. For example, given the struct:
2834// { a, { b, { c, d }, e } }
2835// and the indices "1, 1" this returns
2836// { c, d }.
2837//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002838// It does this by inserting an insertvalue for each element in the resulting
2839// struct, as opposed to just inserting a single struct. This will only work if
2840// each of the elements of the substruct are known (ie, inserted into From by an
2841// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002842//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002843// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002844static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002845 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002846 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002847 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002848 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002849 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002850 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002851 unsigned IdxSkip = Idxs.size();
2852
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002853 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002854}
2855
Sanjay Patelaee84212014-11-04 16:27:42 +00002856/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002857/// the scalar value indexed is already around as a register, for example if it
2858/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002859///
2860/// If InsertBefore is not null, this function will duplicate (modified)
2861/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002862Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2863 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002864 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002865 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002866 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002867 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002868 // We have indices, so V should have an indexable type.
2869 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2870 "Not looking at a struct or array?");
2871 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2872 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002873
Chris Lattner67058832012-01-25 06:48:06 +00002874 if (Constant *C = dyn_cast<Constant>(V)) {
2875 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002876 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002877 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2878 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002879
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002880 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002881 // Loop the indices for the insertvalue instruction in parallel with the
2882 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002883 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002884 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2885 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002886 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002887 // We can't handle this without inserting insertvalues
2888 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002889 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002890
2891 // The requested index identifies a part of a nested aggregate. Handle
2892 // this specially. For example,
2893 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2894 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2895 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2896 // This can be changed into
2897 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2898 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2899 // which allows the unused 0,0 element from the nested struct to be
2900 // removed.
2901 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2902 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002903 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002904
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002905 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002906 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002907 // looking for, then.
2908 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002909 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002910 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002911 }
2912 // If we end up here, the indices of the insertvalue match with those
2913 // requested (though possibly only partially). Now we recursively look at
2914 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002915 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002916 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002917 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002918 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002919
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002920 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002921 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002922 // something else, we can extract from that something else directly instead.
2923 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002924
2925 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002926 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002927 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002928 SmallVector<unsigned, 5> Idxs;
2929 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002930 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002931 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002932
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002933 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002934 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002935
Craig Topper1bef2c82012-12-22 19:15:35 +00002936 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002937 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002938
Jay Foad57aa6362011-07-13 10:26:04 +00002939 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002940 }
2941 // Otherwise, we don't know (such as, extracting from a function return value
2942 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002943 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002944}
Evan Chengda3db112008-06-30 07:31:25 +00002945
Sanjay Patelaee84212014-11-04 16:27:42 +00002946/// Analyze the specified pointer to see if it can be expressed as a base
2947/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002948Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002949 const DataLayout &DL) {
2950 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002951 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002952
2953 // We walk up the defs but use a visited set to handle unreachable code. In
2954 // that case, we stop after accumulating the cycle once (not that it
2955 // matters).
2956 SmallPtrSet<Value *, 16> Visited;
2957 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002958 if (Ptr->getType()->isVectorTy())
2959 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002960
Nuno Lopes368c4d02012-12-31 20:48:35 +00002961 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002962 // If one of the values we have visited is an addrspacecast, then
2963 // the pointer type of this GEP may be different from the type
2964 // of the Ptr parameter which was passed to this function. This
2965 // means when we construct GEPOffset, we need to use the size
2966 // of GEP's pointer type rather than the size of the original
2967 // pointer type.
2968 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002969 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2970 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002971
Tom Stellard17eb3412016-10-07 14:23:29 +00002972 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002973
Nuno Lopes368c4d02012-12-31 20:48:35 +00002974 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002975 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2976 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002977 Ptr = cast<Operator>(Ptr)->getOperand(0);
2978 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002979 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002980 break;
2981 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002982 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002983 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002984 }
2985 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002986 Offset = ByteOffset.getSExtValue();
2987 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002988}
2989
David L Kreitzer752c1442016-04-13 14:31:06 +00002990bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP) {
2991 // Make sure the GEP has exactly three arguments.
2992 if (GEP->getNumOperands() != 3)
2993 return false;
2994
2995 // Make sure the index-ee is a pointer to array of i8.
2996 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2997 if (!AT || !AT->getElementType()->isIntegerTy(8))
2998 return false;
2999
3000 // Check to make sure that the first operand of the GEP is an integer and
3001 // has value 0 so that we are sure we're indexing into the initializer.
3002 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3003 if (!FirstIdx || !FirstIdx->isZero())
3004 return false;
3005
3006 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003007}
Chris Lattnere28618d2010-11-30 22:25:26 +00003008
Sanjay Patelaee84212014-11-04 16:27:42 +00003009/// This function computes the length of a null-terminated C string pointed to
3010/// by V. If successful, it returns true and returns the string in Str.
3011/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003012bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3013 uint64_t Offset, bool TrimAtNul) {
3014 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003015
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003016 // Look through bitcast instructions and geps.
3017 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003018
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003019 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003020 // offset.
3021 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003022 // The GEP operator should be based on a pointer to string constant, and is
3023 // indexing into the string constant.
3024 if (!isGEPBasedOnPointerToString(GEP))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003025 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003026
Evan Chengda3db112008-06-30 07:31:25 +00003027 // If the second index isn't a ConstantInt, then this is a variable index
3028 // into the array. If this occurs, we can't say anything meaningful about
3029 // the string.
3030 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003031 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003032 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003033 else
3034 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003035 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
3036 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00003037 }
Nick Lewycky46209882011-10-20 00:34:35 +00003038
Evan Chengda3db112008-06-30 07:31:25 +00003039 // The GEP instruction, constant or instruction, must reference a global
3040 // variable that is a constant and is initialized. The referenced constant
3041 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003042 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003043 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003044 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003045
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003046 // Handle the all-zeros case.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003047 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00003048 // This is a degenerate case. The initializer is constant zero so the
3049 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003050 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003051 return true;
3052 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003053
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003054 // This must be a ConstantDataArray.
3055 const auto *Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00003056 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003057 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003058
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003059 // Get the number of elements in the array.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003060 uint64_t NumElts = Array->getType()->getArrayNumElements();
3061
3062 // Start out with the entire array in the StringRef.
3063 Str = Array->getAsString();
3064
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003065 if (Offset > NumElts)
3066 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003067
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003068 // Skip over 'offset' bytes.
3069 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003070
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003071 if (TrimAtNul) {
3072 // Trim off the \0 and anything after it. If the array is not nul
3073 // terminated, we just return the whole end of string. The client may know
3074 // some other way that the string is length-bound.
3075 Str = Str.substr(0, Str.find('\0'));
3076 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003077 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003078}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003079
3080// These next two are very similar to the above, but also look through PHI
3081// nodes.
3082// TODO: See if we can integrate these two together.
3083
Sanjay Patelaee84212014-11-04 16:27:42 +00003084/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003085/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003086static uint64_t GetStringLengthH(const Value *V,
3087 SmallPtrSetImpl<const PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003088 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003089 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003090
3091 // If this is a PHI node, there are two cases: either we have already seen it
3092 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003093 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003094 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003095 return ~0ULL; // already in the set.
3096
3097 // If it was new, see if all the input strings are the same length.
3098 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003099 for (Value *IncValue : PN->incoming_values()) {
3100 uint64_t Len = GetStringLengthH(IncValue, PHIs);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003101 if (Len == 0) return 0; // Unknown length -> unknown.
3102
3103 if (Len == ~0ULL) continue;
3104
3105 if (Len != LenSoFar && LenSoFar != ~0ULL)
3106 return 0; // Disagree -> unknown.
3107 LenSoFar = Len;
3108 }
3109
3110 // Success, all agree.
3111 return LenSoFar;
3112 }
3113
3114 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003115 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003116 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
3117 if (Len1 == 0) return 0;
3118 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
3119 if (Len2 == 0) return 0;
3120 if (Len1 == ~0ULL) return Len2;
3121 if (Len2 == ~0ULL) return Len1;
3122 if (Len1 != Len2) return 0;
3123 return Len1;
3124 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003125
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003126 // Otherwise, see if we can read the string.
3127 StringRef StrData;
3128 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003129 return 0;
3130
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003131 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003132}
3133
Sanjay Patelaee84212014-11-04 16:27:42 +00003134/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003135/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003136uint64_t llvm::GetStringLength(const Value *V) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003137 if (!V->getType()->isPointerTy()) return 0;
3138
Pete Cooper35b00d52016-08-13 01:05:32 +00003139 SmallPtrSet<const PHINode*, 32> PHIs;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003140 uint64_t Len = GetStringLengthH(V, PHIs);
3141 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3142 // an empty string as a length.
3143 return Len == ~0ULL ? 1 : Len;
3144}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003145
Adam Nemete2b885c2015-04-23 20:09:20 +00003146/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3147/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003148static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3149 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003150 // Find the loop-defined value.
3151 Loop *L = LI->getLoopFor(PN->getParent());
3152 if (PN->getNumIncomingValues() != 2)
3153 return true;
3154
3155 // Find the value from previous iteration.
3156 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3157 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3158 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3159 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3160 return true;
3161
3162 // If a new pointer is loaded in the loop, the pointer references a different
3163 // object in every iteration. E.g.:
3164 // for (i)
3165 // int *p = a[i];
3166 // ...
3167 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3168 if (!L->isLoopInvariant(Load->getPointerOperand()))
3169 return false;
3170 return true;
3171}
3172
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003173Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3174 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003175 if (!V->getType()->isPointerTy())
3176 return V;
3177 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3178 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3179 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003180 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3181 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003182 V = cast<Operator>(V)->getOperand(0);
3183 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003184 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003185 return V;
3186 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003187 } else if (isa<AllocaInst>(V)) {
3188 // An alloca can't be further simplified.
3189 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003190 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003191 if (auto CS = CallSite(V))
3192 if (Value *RV = CS.getReturnedArgOperand()) {
3193 V = RV;
3194 continue;
3195 }
3196
Dan Gohman05b18f12010-12-15 20:49:55 +00003197 // See if InstructionSimplify knows any relevant tricks.
3198 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003199 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003200 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003201 V = Simplified;
3202 continue;
3203 }
3204
Dan Gohmana4fcd242010-12-15 20:02:24 +00003205 return V;
3206 }
3207 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3208 }
3209 return V;
3210}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003211
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003212void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003213 const DataLayout &DL, LoopInfo *LI,
3214 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003215 SmallPtrSet<Value *, 4> Visited;
3216 SmallVector<Value *, 4> Worklist;
3217 Worklist.push_back(V);
3218 do {
3219 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003220 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003221
David Blaikie70573dc2014-11-19 07:49:26 +00003222 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003223 continue;
3224
3225 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3226 Worklist.push_back(SI->getTrueValue());
3227 Worklist.push_back(SI->getFalseValue());
3228 continue;
3229 }
3230
3231 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003232 // If this PHI changes the underlying object in every iteration of the
3233 // loop, don't look through it. Consider:
3234 // int **A;
3235 // for (i) {
3236 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3237 // Curr = A[i];
3238 // *Prev, *Curr;
3239 //
3240 // Prev is tracking Curr one iteration behind so they refer to different
3241 // underlying objects.
3242 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3243 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003244 for (Value *IncValue : PN->incoming_values())
3245 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003246 continue;
3247 }
3248
3249 Objects.push_back(P);
3250 } while (!Worklist.empty());
3251}
3252
Sanjay Patelaee84212014-11-04 16:27:42 +00003253/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003254bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003255 for (const User *U : V->users()) {
3256 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003257 if (!II) return false;
3258
3259 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3260 II->getIntrinsicID() != Intrinsic::lifetime_end)
3261 return false;
3262 }
3263 return true;
3264}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003265
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003266bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3267 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003268 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003269 const Operator *Inst = dyn_cast<Operator>(V);
3270 if (!Inst)
3271 return false;
3272
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003273 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3274 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3275 if (C->canTrap())
3276 return false;
3277
3278 switch (Inst->getOpcode()) {
3279 default:
3280 return true;
3281 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003282 case Instruction::URem: {
3283 // x / y is undefined if y == 0.
3284 const APInt *V;
3285 if (match(Inst->getOperand(1), m_APInt(V)))
3286 return *V != 0;
3287 return false;
3288 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003289 case Instruction::SDiv:
3290 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003291 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003292 const APInt *Numerator, *Denominator;
3293 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3294 return false;
3295 // We cannot hoist this division if the denominator is 0.
3296 if (*Denominator == 0)
3297 return false;
3298 // It's safe to hoist if the denominator is not 0 or -1.
3299 if (*Denominator != -1)
3300 return true;
3301 // At this point we know that the denominator is -1. It is safe to hoist as
3302 // long we know that the numerator is not INT_MIN.
3303 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3304 return !Numerator->isMinSignedValue();
3305 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003306 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003307 }
3308 case Instruction::Load: {
3309 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003310 if (!LI->isUnordered() ||
3311 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003312 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003313 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003314 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003315 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003316 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003317 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3318 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003319 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003320 case Instruction::Call: {
David Majnemer0a92f862015-08-28 21:13:39 +00003321 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3322 switch (II->getIntrinsicID()) {
3323 // These synthetic intrinsics have no side-effects and just mark
3324 // information about their operands.
3325 // FIXME: There are other no-op synthetic instructions that potentially
3326 // should be considered at least *safe* to speculate...
3327 case Intrinsic::dbg_declare:
3328 case Intrinsic::dbg_value:
3329 return true;
3330
Xin Tongc13a8e82017-01-09 17:57:08 +00003331 case Intrinsic::bitreverse:
David Majnemer0a92f862015-08-28 21:13:39 +00003332 case Intrinsic::bswap:
3333 case Intrinsic::ctlz:
3334 case Intrinsic::ctpop:
3335 case Intrinsic::cttz:
3336 case Intrinsic::objectsize:
3337 case Intrinsic::sadd_with_overflow:
3338 case Intrinsic::smul_with_overflow:
3339 case Intrinsic::ssub_with_overflow:
3340 case Intrinsic::uadd_with_overflow:
3341 case Intrinsic::umul_with_overflow:
3342 case Intrinsic::usub_with_overflow:
3343 return true;
Peter Zotov0218d0f2016-04-03 12:30:46 +00003344 // These intrinsics are defined to have the same behavior as libm
3345 // functions except for setting errno.
David Majnemer0a92f862015-08-28 21:13:39 +00003346 case Intrinsic::sqrt:
3347 case Intrinsic::fma:
3348 case Intrinsic::fmuladd:
Peter Zotov0218d0f2016-04-03 12:30:46 +00003349 return true;
3350 // These intrinsics are defined to have the same behavior as libm
3351 // functions, and the corresponding libm functions never set errno.
3352 case Intrinsic::trunc:
3353 case Intrinsic::copysign:
David Majnemer0a92f862015-08-28 21:13:39 +00003354 case Intrinsic::fabs:
3355 case Intrinsic::minnum:
3356 case Intrinsic::maxnum:
3357 return true;
Peter Zotov0218d0f2016-04-03 12:30:46 +00003358 // These intrinsics are defined to have the same behavior as libm
3359 // functions, which never overflow when operating on the IEEE754 types
3360 // that we support, and never set errno otherwise.
3361 case Intrinsic::ceil:
3362 case Intrinsic::floor:
3363 case Intrinsic::nearbyint:
3364 case Intrinsic::rint:
3365 case Intrinsic::round:
3366 return true;
whitequark16f1e5f2017-01-25 09:32:30 +00003367 // These intrinsics do not correspond to any libm function, and
3368 // do not set errno.
3369 case Intrinsic::powi:
3370 return true;
David Majnemer0a92f862015-08-28 21:13:39 +00003371 // TODO: are convert_{from,to}_fp16 safe?
3372 // TODO: can we list target-specific intrinsics here?
3373 default: break;
3374 }
3375 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003376 return false; // The called function could have undefined behavior or
David Majnemer0a92f862015-08-28 21:13:39 +00003377 // side-effects, even if marked readnone nounwind.
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003378 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003379 case Instruction::VAArg:
3380 case Instruction::Alloca:
3381 case Instruction::Invoke:
3382 case Instruction::PHI:
3383 case Instruction::Store:
3384 case Instruction::Ret:
3385 case Instruction::Br:
3386 case Instruction::IndirectBr:
3387 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003388 case Instruction::Unreachable:
3389 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003390 case Instruction::AtomicRMW:
3391 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003392 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003393 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003394 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003395 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003396 case Instruction::CatchRet:
3397 case Instruction::CleanupPad:
3398 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003399 return false; // Misc instructions which have effects
3400 }
3401}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003402
Quentin Colombet6443cce2015-08-06 18:44:34 +00003403bool llvm::mayBeMemoryDependent(const Instruction &I) {
3404 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3405}
3406
Sanjay Patelaee84212014-11-04 16:27:42 +00003407/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003408bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003409 assert(V->getType()->isPointerTy() && "V must be pointer type");
3410
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003411 // Alloca never returns null, malloc might.
3412 if (isa<AllocaInst>(V)) return true;
3413
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003414 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003415 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003416 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003417
Peter Collingbourne235c2752016-12-08 19:01:00 +00003418 // A global variable in address space 0 is non null unless extern weak
3419 // or an absolute symbol reference. Other address spaces may have null as a
3420 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003421 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003422 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003423 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003424
Sanjoy Das5056e192016-05-07 02:08:22 +00003425 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003426 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003427 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003428
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003429 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003430 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003431 return true;
3432
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003433 return false;
3434}
David Majnemer491331a2015-01-02 07:29:43 +00003435
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003436static bool isKnownNonNullFromDominatingCondition(const Value *V,
3437 const Instruction *CtxI,
3438 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003439 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003440 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003441 assert(CtxI && "Context instruction required for analysis");
3442 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003443
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003444 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003445 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003446 // Avoid massive lists
3447 if (NumUsesExplored >= DomConditionsMaxUses)
3448 break;
3449 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003450
3451 // If the value is used as an argument to a call or invoke, then argument
3452 // attributes may provide an answer about null-ness.
3453 if (auto CS = ImmutableCallSite(U))
3454 if (auto *CalledFunc = CS.getCalledFunction())
3455 for (const Argument &Arg : CalledFunc->args())
3456 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3457 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3458 return true;
3459
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003460 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003461 CmpInst::Predicate Pred;
3462 if (!match(const_cast<User *>(U),
3463 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3464 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003465 continue;
3466
Sanjoy Das987aaa12016-05-07 02:08:24 +00003467 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003468 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3469 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003470
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003471 BasicBlock *NonNullSuccessor =
3472 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3473 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3474 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3475 return true;
3476 } else if (Pred == ICmpInst::ICMP_NE &&
3477 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3478 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003479 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003480 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003481 }
3482 }
3483
3484 return false;
3485}
3486
3487bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003488 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003489 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3490 return false;
3491
Sean Silva45835e72016-07-02 23:47:27 +00003492 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003493 return true;
3494
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003495 if (!CtxI || !DT)
3496 return false;
3497
3498 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003499}
3500
Pete Cooper35b00d52016-08-13 01:05:32 +00003501OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3502 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003503 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003504 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003505 const Instruction *CxtI,
3506 const DominatorTree *DT) {
3507 // Multiplying n * m significant bits yields a result of n + m significant
3508 // bits. If the total number of significant bits does not exceed the
3509 // result bit width (minus 1), there is no overflow.
3510 // This means if we have enough leading zero bits in the operands
3511 // we can guarantee that the result does not overflow.
3512 // Ref: "Hacker's Delight" by Henry Warren
3513 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003514 KnownBits LHSKnown(BitWidth);
3515 KnownBits RHSKnown(BitWidth);
3516 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3517 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003518 // Note that underestimating the number of zero bits gives a more
3519 // conservative answer.
Craig Topperb45eabc2017-04-26 16:39:58 +00003520 unsigned ZeroBits = LHSKnown.Zero.countLeadingOnes() +
3521 RHSKnown.Zero.countLeadingOnes();
David Majnemer491331a2015-01-02 07:29:43 +00003522 // First handle the easy case: if we have enough zero bits there's
3523 // definitely no overflow.
3524 if (ZeroBits >= BitWidth)
3525 return OverflowResult::NeverOverflows;
3526
3527 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003528 APInt LHSMax = ~LHSKnown.Zero;
3529 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003530
3531 // We know the multiply operation doesn't overflow if the maximum values for
3532 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003533 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003534 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003535 if (!MaxOverflow)
3536 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003537
David Majnemerc8a576b2015-01-02 07:29:47 +00003538 // We know it always overflows if multiplying the smallest possible values for
3539 // the operands also results in overflow.
3540 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003541 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003542 if (MinOverflow)
3543 return OverflowResult::AlwaysOverflows;
3544
3545 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003546}
David Majnemer5310c1e2015-01-07 00:39:50 +00003547
Pete Cooper35b00d52016-08-13 01:05:32 +00003548OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3549 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003550 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003551 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003552 const Instruction *CxtI,
3553 const DominatorTree *DT) {
3554 bool LHSKnownNonNegative, LHSKnownNegative;
3555 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003556 AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003557 if (LHSKnownNonNegative || LHSKnownNegative) {
3558 bool RHSKnownNonNegative, RHSKnownNegative;
3559 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003560 AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003561
3562 if (LHSKnownNegative && RHSKnownNegative) {
3563 // The sign bit is set in both cases: this MUST overflow.
3564 // Create a simple add instruction, and insert it into the struct.
3565 return OverflowResult::AlwaysOverflows;
3566 }
3567
3568 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3569 // The sign bit is clear in both cases: this CANNOT overflow.
3570 // Create a simple add instruction, and insert it into the struct.
3571 return OverflowResult::NeverOverflows;
3572 }
3573 }
3574
3575 return OverflowResult::MayOverflow;
3576}
James Molloy71b91c22015-05-11 14:42:20 +00003577
Pete Cooper35b00d52016-08-13 01:05:32 +00003578static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3579 const Value *RHS,
3580 const AddOperator *Add,
3581 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003582 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003583 const Instruction *CxtI,
3584 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003585 if (Add && Add->hasNoSignedWrap()) {
3586 return OverflowResult::NeverOverflows;
3587 }
3588
3589 bool LHSKnownNonNegative, LHSKnownNegative;
3590 bool RHSKnownNonNegative, RHSKnownNegative;
3591 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003592 AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003593 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003594 AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003595
3596 if ((LHSKnownNonNegative && RHSKnownNegative) ||
3597 (LHSKnownNegative && RHSKnownNonNegative)) {
3598 // The sign bits are opposite: this CANNOT overflow.
3599 return OverflowResult::NeverOverflows;
3600 }
3601
3602 // The remaining code needs Add to be available. Early returns if not so.
3603 if (!Add)
3604 return OverflowResult::MayOverflow;
3605
3606 // If the sign of Add is the same as at least one of the operands, this add
3607 // CANNOT overflow. This is particularly useful when the sum is
3608 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3609 // operands.
3610 bool LHSOrRHSKnownNonNegative =
3611 (LHSKnownNonNegative || RHSKnownNonNegative);
3612 bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3613 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3614 bool AddKnownNonNegative, AddKnownNegative;
3615 ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003616 /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003617 if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3618 (AddKnownNegative && LHSOrRHSKnownNegative)) {
3619 return OverflowResult::NeverOverflows;
3620 }
3621 }
3622
3623 return OverflowResult::MayOverflow;
3624}
3625
Pete Cooper35b00d52016-08-13 01:05:32 +00003626bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3627 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003628#ifndef NDEBUG
3629 auto IID = II->getIntrinsicID();
3630 assert((IID == Intrinsic::sadd_with_overflow ||
3631 IID == Intrinsic::uadd_with_overflow ||
3632 IID == Intrinsic::ssub_with_overflow ||
3633 IID == Intrinsic::usub_with_overflow ||
3634 IID == Intrinsic::smul_with_overflow ||
3635 IID == Intrinsic::umul_with_overflow) &&
3636 "Not an overflow intrinsic!");
3637#endif
3638
Pete Cooper35b00d52016-08-13 01:05:32 +00003639 SmallVector<const BranchInst *, 2> GuardingBranches;
3640 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003641
Pete Cooper35b00d52016-08-13 01:05:32 +00003642 for (const User *U : II->users()) {
3643 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003644 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3645
3646 if (EVI->getIndices()[0] == 0)
3647 Results.push_back(EVI);
3648 else {
3649 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3650
Pete Cooper35b00d52016-08-13 01:05:32 +00003651 for (const auto *U : EVI->users())
3652 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003653 assert(B->isConditional() && "How else is it using an i1?");
3654 GuardingBranches.push_back(B);
3655 }
3656 }
3657 } else {
3658 // We are using the aggregate directly in a way we don't want to analyze
3659 // here (storing it to a global, say).
3660 return false;
3661 }
3662 }
3663
Pete Cooper35b00d52016-08-13 01:05:32 +00003664 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003665 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3666 if (!NoWrapEdge.isSingleEdge())
3667 return false;
3668
3669 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003670 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003671 // If the extractvalue itself is not executed on overflow, the we don't
3672 // need to check each use separately, since domination is transitive.
3673 if (DT.dominates(NoWrapEdge, Result->getParent()))
3674 continue;
3675
3676 for (auto &RU : Result->uses())
3677 if (!DT.dominates(NoWrapEdge, RU))
3678 return false;
3679 }
3680
3681 return true;
3682 };
3683
3684 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3685}
3686
3687
Pete Cooper35b00d52016-08-13 01:05:32 +00003688OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003689 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003690 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003691 const Instruction *CxtI,
3692 const DominatorTree *DT) {
3693 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003694 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003695}
3696
Pete Cooper35b00d52016-08-13 01:05:32 +00003697OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3698 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003699 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003700 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003701 const Instruction *CxtI,
3702 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003703 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003704}
3705
Jingyue Wu42f1d672015-07-28 18:22:40 +00003706bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003707 // A memory operation returns normally if it isn't volatile. A volatile
3708 // operation is allowed to trap.
3709 //
3710 // An atomic operation isn't guaranteed to return in a reasonable amount of
3711 // time because it's possible for another thread to interfere with it for an
3712 // arbitrary length of time, but programs aren't allowed to rely on that.
3713 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3714 return !LI->isVolatile();
3715 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3716 return !SI->isVolatile();
3717 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3718 return !CXI->isVolatile();
3719 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3720 return !RMWI->isVolatile();
3721 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3722 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003723
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003724 // If there is no successor, then execution can't transfer to it.
3725 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3726 return !CRI->unwindsToCaller();
3727 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3728 return !CatchSwitch->unwindsToCaller();
3729 if (isa<ResumeInst>(I))
3730 return false;
3731 if (isa<ReturnInst>(I))
3732 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003733 if (isa<UnreachableInst>(I))
3734 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003735
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003736 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003737 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003738 // Call sites that throw have implicit non-local control flow.
3739 if (!CS.doesNotThrow())
3740 return false;
3741
3742 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3743 // etc. and thus not return. However, LLVM already assumes that
3744 //
3745 // - Thread exiting actions are modeled as writes to memory invisible to
3746 // the program.
3747 //
3748 // - Loops that don't have side effects (side effects are volatile/atomic
3749 // stores and IO) always terminate (see http://llvm.org/PR965).
3750 // Furthermore IO itself is also modeled as writes to memory invisible to
3751 // the program.
3752 //
3753 // We rely on those assumptions here, and use the memory effects of the call
3754 // target as a proxy for checking that it always returns.
3755
3756 // FIXME: This isn't aggressive enough; a call which only writes to a global
3757 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003758 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3759 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003760 }
3761
3762 // Other instructions return normally.
3763 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003764}
3765
3766bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3767 const Loop *L) {
3768 // The loop header is guaranteed to be executed for every iteration.
3769 //
3770 // FIXME: Relax this constraint to cover all basic blocks that are
3771 // guaranteed to be executed at every iteration.
3772 if (I->getParent() != L->getHeader()) return false;
3773
3774 for (const Instruction &LI : *L->getHeader()) {
3775 if (&LI == I) return true;
3776 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3777 }
3778 llvm_unreachable("Instruction not contained in its own parent basic block.");
3779}
3780
3781bool llvm::propagatesFullPoison(const Instruction *I) {
3782 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003783 case Instruction::Add:
3784 case Instruction::Sub:
3785 case Instruction::Xor:
3786 case Instruction::Trunc:
3787 case Instruction::BitCast:
3788 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003789 case Instruction::Mul:
3790 case Instruction::Shl:
3791 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003792 // These operations all propagate poison unconditionally. Note that poison
3793 // is not any particular value, so xor or subtraction of poison with
3794 // itself still yields poison, not zero.
3795 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003796
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003797 case Instruction::AShr:
3798 case Instruction::SExt:
3799 // For these operations, one bit of the input is replicated across
3800 // multiple output bits. A replicated poison bit is still poison.
3801 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003802
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003803 case Instruction::ICmp:
3804 // Comparing poison with any value yields poison. This is why, for
3805 // instance, x s< (x +nsw 1) can be folded to true.
3806 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003807
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003808 default:
3809 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003810 }
3811}
3812
3813const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3814 switch (I->getOpcode()) {
3815 case Instruction::Store:
3816 return cast<StoreInst>(I)->getPointerOperand();
3817
3818 case Instruction::Load:
3819 return cast<LoadInst>(I)->getPointerOperand();
3820
3821 case Instruction::AtomicCmpXchg:
3822 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3823
3824 case Instruction::AtomicRMW:
3825 return cast<AtomicRMWInst>(I)->getPointerOperand();
3826
3827 case Instruction::UDiv:
3828 case Instruction::SDiv:
3829 case Instruction::URem:
3830 case Instruction::SRem:
3831 return I->getOperand(1);
3832
3833 default:
3834 return nullptr;
3835 }
3836}
3837
3838bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3839 // We currently only look for uses of poison values within the same basic
3840 // block, as that makes it easier to guarantee that the uses will be
3841 // executed given that PoisonI is executed.
3842 //
3843 // FIXME: Expand this to consider uses beyond the same basic block. To do
3844 // this, look out for the distinction between post-dominance and strong
3845 // post-dominance.
3846 const BasicBlock *BB = PoisonI->getParent();
3847
3848 // Set of instructions that we have proved will yield poison if PoisonI
3849 // does.
3850 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003851 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003852 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003853 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003854
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003855 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003856
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003857 unsigned Iter = 0;
3858 while (Iter++ < MaxDepth) {
3859 for (auto &I : make_range(Begin, End)) {
3860 if (&I != PoisonI) {
3861 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3862 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3863 return true;
3864 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3865 return false;
3866 }
3867
3868 // Mark poison that propagates from I through uses of I.
3869 if (YieldsPoison.count(&I)) {
3870 for (const User *User : I.users()) {
3871 const Instruction *UserI = cast<Instruction>(User);
3872 if (propagatesFullPoison(UserI))
3873 YieldsPoison.insert(User);
3874 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003875 }
3876 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003877
3878 if (auto *NextBB = BB->getSingleSuccessor()) {
3879 if (Visited.insert(NextBB).second) {
3880 BB = NextBB;
3881 Begin = BB->getFirstNonPHI()->getIterator();
3882 End = BB->end();
3883 continue;
3884 }
3885 }
3886
3887 break;
3888 };
Jingyue Wu42f1d672015-07-28 18:22:40 +00003889 return false;
3890}
3891
Pete Cooper35b00d52016-08-13 01:05:32 +00003892static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003893 if (FMF.noNaNs())
3894 return true;
3895
3896 if (auto *C = dyn_cast<ConstantFP>(V))
3897 return !C->isNaN();
3898 return false;
3899}
3900
Pete Cooper35b00d52016-08-13 01:05:32 +00003901static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003902 if (auto *C = dyn_cast<ConstantFP>(V))
3903 return !C->isZero();
3904 return false;
3905}
3906
Sanjay Patel819f0962016-11-13 19:30:19 +00003907/// Match non-obvious integer minimum and maximum sequences.
3908static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
3909 Value *CmpLHS, Value *CmpRHS,
3910 Value *TrueVal, Value *FalseVal,
3911 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00003912 // Assume success. If there's no match, callers should not use these anyway.
3913 LHS = TrueVal;
3914 RHS = FalseVal;
3915
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003916 // Recognize variations of:
3917 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
3918 const APInt *C1;
3919 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
3920 const APInt *C2;
3921
3922 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
3923 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003924 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003925 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003926
3927 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
3928 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003929 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003930 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003931
3932 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
3933 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003934 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003935 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003936
3937 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
3938 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003939 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003940 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003941 }
3942
Sanjay Patel819f0962016-11-13 19:30:19 +00003943 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
3944 return {SPF_UNKNOWN, SPNB_NA, false};
3945
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003946 // Z = X -nsw Y
3947 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
3948 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
3949 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003950 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003951 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003952
3953 // Z = X -nsw Y
3954 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
3955 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
3956 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003957 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003958 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003959
Sanjay Patel819f0962016-11-13 19:30:19 +00003960 if (!match(CmpRHS, m_APInt(C1)))
3961 return {SPF_UNKNOWN, SPNB_NA, false};
3962
3963 // An unsigned min/max can be written with a signed compare.
3964 const APInt *C2;
3965 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
3966 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
3967 // Is the sign bit set?
3968 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
3969 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00003970 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003971 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003972
3973 // Is the sign bit clear?
3974 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
3975 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
3976 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003977 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003978 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003979 }
3980
3981 // Look through 'not' ops to find disguised signed min/max.
3982 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
3983 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
3984 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003985 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003986 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003987
3988 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
3989 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
3990 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003991 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003992 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003993
3994 return {SPF_UNKNOWN, SPNB_NA, false};
3995}
3996
James Molloy134bec22015-08-11 09:12:57 +00003997static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3998 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00003999 Value *CmpLHS, Value *CmpRHS,
4000 Value *TrueVal, Value *FalseVal,
4001 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004002 LHS = CmpLHS;
4003 RHS = CmpRHS;
4004
James Molloy134bec22015-08-11 09:12:57 +00004005 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4006 // return inconsistent results between implementations.
4007 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4008 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4009 // Therefore we behave conservatively and only proceed if at least one of the
4010 // operands is known to not be zero, or if we don't care about signed zeroes.
4011 switch (Pred) {
4012 default: break;
4013 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4014 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4015 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4016 !isKnownNonZero(CmpRHS))
4017 return {SPF_UNKNOWN, SPNB_NA, false};
4018 }
4019
4020 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4021 bool Ordered = false;
4022
4023 // When given one NaN and one non-NaN input:
4024 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4025 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4026 // ordered comparison fails), which could be NaN or non-NaN.
4027 // so here we discover exactly what NaN behavior is required/accepted.
4028 if (CmpInst::isFPPredicate(Pred)) {
4029 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4030 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4031
4032 if (LHSSafe && RHSSafe) {
4033 // Both operands are known non-NaN.
4034 NaNBehavior = SPNB_RETURNS_ANY;
4035 } else if (CmpInst::isOrdered(Pred)) {
4036 // An ordered comparison will return false when given a NaN, so it
4037 // returns the RHS.
4038 Ordered = true;
4039 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004040 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004041 NaNBehavior = SPNB_RETURNS_NAN;
4042 else if (RHSSafe)
4043 NaNBehavior = SPNB_RETURNS_OTHER;
4044 else
4045 // Completely unsafe.
4046 return {SPF_UNKNOWN, SPNB_NA, false};
4047 } else {
4048 Ordered = false;
4049 // An unordered comparison will return true when given a NaN, so it
4050 // returns the LHS.
4051 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004052 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004053 NaNBehavior = SPNB_RETURNS_OTHER;
4054 else if (RHSSafe)
4055 NaNBehavior = SPNB_RETURNS_NAN;
4056 else
4057 // Completely unsafe.
4058 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004059 }
4060 }
4061
James Molloy71b91c22015-05-11 14:42:20 +00004062 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004063 std::swap(CmpLHS, CmpRHS);
4064 Pred = CmpInst::getSwappedPredicate(Pred);
4065 if (NaNBehavior == SPNB_RETURNS_NAN)
4066 NaNBehavior = SPNB_RETURNS_OTHER;
4067 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4068 NaNBehavior = SPNB_RETURNS_NAN;
4069 Ordered = !Ordered;
4070 }
4071
4072 // ([if]cmp X, Y) ? X : Y
4073 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004074 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004075 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004076 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004077 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004078 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004079 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004080 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004081 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004082 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004083 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4084 case FCmpInst::FCMP_UGT:
4085 case FCmpInst::FCMP_UGE:
4086 case FCmpInst::FCMP_OGT:
4087 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4088 case FCmpInst::FCMP_ULT:
4089 case FCmpInst::FCMP_ULE:
4090 case FCmpInst::FCMP_OLT:
4091 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004092 }
4093 }
4094
Sanjay Patele372aec2016-10-27 15:26:10 +00004095 const APInt *C1;
4096 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004097 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4098 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4099
4100 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4101 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004102 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004103 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004104 }
4105
4106 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4107 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004108 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004109 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004110 }
4111 }
James Molloy71b91c22015-05-11 14:42:20 +00004112 }
4113
Sanjay Patel819f0962016-11-13 19:30:19 +00004114 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004115}
James Molloy270ef8c2015-05-15 16:04:50 +00004116
James Molloy569cea62015-09-02 17:25:25 +00004117static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4118 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004119 auto *Cast1 = dyn_cast<CastInst>(V1);
4120 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004121 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004122
Sanjay Patel14a4b812017-01-29 16:34:57 +00004123 *CastOp = Cast1->getOpcode();
4124 Type *SrcTy = Cast1->getSrcTy();
4125 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4126 // If V1 and V2 are both the same cast from the same type, look through V1.
4127 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4128 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004129 return nullptr;
4130 }
4131
Sanjay Patel14a4b812017-01-29 16:34:57 +00004132 auto *C = dyn_cast<Constant>(V2);
4133 if (!C)
4134 return nullptr;
4135
David Majnemerd2a074b2016-04-29 18:40:34 +00004136 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004137 switch (*CastOp) {
4138 case Instruction::ZExt:
4139 if (CmpI->isUnsigned())
4140 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4141 break;
4142 case Instruction::SExt:
4143 if (CmpI->isSigned())
4144 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4145 break;
4146 case Instruction::Trunc:
4147 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4148 break;
4149 case Instruction::FPTrunc:
4150 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4151 break;
4152 case Instruction::FPExt:
4153 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4154 break;
4155 case Instruction::FPToUI:
4156 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4157 break;
4158 case Instruction::FPToSI:
4159 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4160 break;
4161 case Instruction::UIToFP:
4162 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4163 break;
4164 case Instruction::SIToFP:
4165 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4166 break;
4167 default:
4168 break;
4169 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004170
4171 if (!CastedTo)
4172 return nullptr;
4173
David Majnemerd2a074b2016-04-29 18:40:34 +00004174 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004175 Constant *CastedBack =
4176 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004177 if (CastedBack != C)
4178 return nullptr;
4179
4180 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004181}
4182
Sanjay Patele8dc0902016-05-23 17:57:54 +00004183SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004184 Instruction::CastOps *CastOp) {
4185 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004186 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004187
James Molloy134bec22015-08-11 09:12:57 +00004188 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4189 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004190
James Molloy134bec22015-08-11 09:12:57 +00004191 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004192 Value *CmpLHS = CmpI->getOperand(0);
4193 Value *CmpRHS = CmpI->getOperand(1);
4194 Value *TrueVal = SI->getTrueValue();
4195 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004196 FastMathFlags FMF;
4197 if (isa<FPMathOperator>(CmpI))
4198 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004199
4200 // Bail out early.
4201 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004202 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004203
4204 // Deal with type mismatches.
4205 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004206 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004207 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004208 cast<CastInst>(TrueVal)->getOperand(0), C,
4209 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004210 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004211 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004212 C, cast<CastInst>(FalseVal)->getOperand(0),
4213 LHS, RHS);
4214 }
James Molloy134bec22015-08-11 09:12:57 +00004215 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004216 LHS, RHS);
4217}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004218
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004219/// Return true if "icmp Pred LHS RHS" is always true.
Pete Cooper35b00d52016-08-13 01:05:32 +00004220static bool isTruePredicate(CmpInst::Predicate Pred,
4221 const Value *LHS, const Value *RHS,
Sanjoy Das55ea67c2015-11-06 19:01:08 +00004222 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004223 AssumptionCache *AC, const Instruction *CxtI,
4224 const DominatorTree *DT) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004225 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004226 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4227 return true;
4228
4229 switch (Pred) {
4230 default:
4231 return false;
4232
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004233 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004234 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004235
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004236 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004237 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004238 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004239 return false;
4240 }
4241
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004242 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004243 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004244
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004245 // LHS u<= LHS +_{nuw} C for any C
4246 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004247 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004248
4249 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004250 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4251 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004252 const APInt *&CA, const APInt *&CB) {
4253 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4254 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4255 return true;
4256
4257 // If X & C == 0 then (X | C) == X +_{nuw} C
4258 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4259 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004260 KnownBits Known(CA->getBitWidth());
4261 computeKnownBits(X, Known, DL, Depth + 1, AC, CxtI, DT);
Sanjoy Das92568102015-11-10 23:56:20 +00004262
Craig Topperb45eabc2017-04-26 16:39:58 +00004263 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004264 return true;
4265 }
4266
4267 return false;
4268 };
4269
Pete Cooper35b00d52016-08-13 01:05:32 +00004270 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004271 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004272 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4273 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004274
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004275 return false;
4276 }
4277 }
4278}
4279
4280/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004281/// ALHS ARHS" is true. Otherwise, return None.
4282static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004283isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4284 const Value *ARHS, const Value *BLHS,
4285 const Value *BRHS, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004286 unsigned Depth, AssumptionCache *AC,
4287 const Instruction *CxtI, const DominatorTree *DT) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004288 switch (Pred) {
4289 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004290 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004291
4292 case CmpInst::ICMP_SLT:
4293 case CmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004294 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004295 DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004296 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004297 return true;
4298 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004299
4300 case CmpInst::ICMP_ULT:
4301 case CmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004302 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
4303 DT) &&
4304 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004305 return true;
4306 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004307 }
4308}
4309
Chad Rosier226a7342016-05-05 17:41:19 +00004310/// Return true if the operands of the two compares match. IsSwappedOps is true
4311/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004312static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4313 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004314 bool &IsSwappedOps) {
4315
4316 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4317 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4318 return IsMatchingOps || IsSwappedOps;
4319}
4320
Chad Rosier41dd31f2016-04-20 19:15:26 +00004321/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4322/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4323/// BRHS" is false. Otherwise, return None if we can't infer anything.
4324static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004325 const Value *ALHS,
4326 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004327 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004328 const Value *BLHS,
4329 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004330 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004331 // Canonicalize the operands so they're matching.
4332 if (IsSwappedOps) {
4333 std::swap(BLHS, BRHS);
4334 BPred = ICmpInst::getSwappedPredicate(BPred);
4335 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004336 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004337 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004338 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004339 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004340
Chad Rosier41dd31f2016-04-20 19:15:26 +00004341 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004342}
4343
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004344/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4345/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4346/// C2" is false. Otherwise, return None if we can't infer anything.
4347static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004348isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4349 const ConstantInt *C1,
4350 CmpInst::Predicate BPred,
4351 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004352 assert(ALHS == BLHS && "LHS operands must match.");
4353 ConstantRange DomCR =
4354 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4355 ConstantRange CR =
4356 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4357 ConstantRange Intersection = DomCR.intersectWith(CR);
4358 ConstantRange Difference = DomCR.difference(CR);
4359 if (Intersection.isEmptySet())
4360 return false;
4361 if (Difference.isEmptySet())
4362 return true;
4363 return None;
4364}
4365
Pete Cooper35b00d52016-08-13 01:05:32 +00004366Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosiere2cbd132016-04-25 17:23:36 +00004367 const DataLayout &DL, bool InvertAPred,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004368 unsigned Depth, AssumptionCache *AC,
4369 const Instruction *CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004370 const DominatorTree *DT) {
Chad Rosiercd62bf52016-04-29 21:12:31 +00004371 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example.
4372 if (LHS->getType() != RHS->getType())
4373 return None;
4374
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004375 Type *OpTy = LHS->getType();
4376 assert(OpTy->getScalarType()->isIntegerTy(1));
4377
4378 // LHS ==> RHS by definition
Chad Rosiere2cbd132016-04-25 17:23:36 +00004379 if (!InvertAPred && LHS == RHS)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004380 return true;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004381
4382 if (OpTy->isVectorTy())
4383 // TODO: extending the code below to handle vectors
Chad Rosier41dd31f2016-04-20 19:15:26 +00004384 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004385 assert(OpTy->isIntegerTy(1) && "implied by above");
4386
4387 ICmpInst::Predicate APred, BPred;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004388 Value *ALHS, *ARHS;
4389 Value *BLHS, *BRHS;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004390
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004391 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
4392 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004393 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004394
Chad Rosiere2cbd132016-04-25 17:23:36 +00004395 if (InvertAPred)
4396 APred = CmpInst::getInversePredicate(APred);
4397
Chad Rosier226a7342016-05-05 17:41:19 +00004398 // Can we infer anything when the two compares have matching operands?
4399 bool IsSwappedOps;
4400 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4401 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4402 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004403 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004404 // No amount of additional analysis will infer the second condition, so
4405 // early exit.
4406 return None;
4407 }
4408
4409 // Can we infer anything when the LHS operands match and the RHS operands are
4410 // constants (not necessarily matching)?
4411 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4412 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4413 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4414 cast<ConstantInt>(BRHS)))
4415 return Implication;
4416 // No amount of additional analysis will infer the second condition, so
4417 // early exit.
4418 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004419 }
4420
Chad Rosier41dd31f2016-04-20 19:15:26 +00004421 if (APred == BPred)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004422 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
4423 CxtI, DT);
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004424
Chad Rosier41dd31f2016-04-20 19:15:26 +00004425 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004426}