blob: 38bcb0f6c71b1f624cefdcd73dc6cf655a597ab6 [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
Craig Topper6b3940a2017-05-03 22:25:19 +000062/// Returns the bitwidth of the given scalar or pointer type. For vector types,
63/// 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
Craig Topper6e11a052017-05-08 16:22:48 +000091 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
92 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +000093 std::array<const Value *, MaxDepth> Excluded;
Matthias Braun37e5d792016-01-28 06:29:33 +000094 unsigned NumExcluded;
95
Daniel Jasperaec2fa32016-12-19 08:22:17 +000096 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +000097 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
98 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), NumExcluded(0) {}
Hal Finkel60db0582014-09-07 18:57:58 +000099
100 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000101 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
102 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000103 Excluded = Q.Excluded;
104 Excluded[NumExcluded++] = NewExcl;
105 assert(NumExcluded <= Excluded.size());
106 }
107
108 bool isExcluded(const Value *Value) const {
109 if (NumExcluded == 0)
110 return false;
111 auto End = Excluded.begin() + NumExcluded;
112 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000113 }
114};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000115} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000116
Sanjay Patel547e9752014-11-04 16:09:50 +0000117// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000118// the preferred context instruction (if any).
119static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
120 // If we've been provided with a context instruction, then use that (provided
121 // it has been inserted).
122 if (CxtI && CxtI->getParent())
123 return CxtI;
124
125 // If the value is really an already-inserted instruction, then use that.
126 CxtI = dyn_cast<Instruction>(V);
127 if (CxtI && CxtI->getParent())
128 return CxtI;
129
130 return nullptr;
131}
132
Craig Topperb45eabc2017-04-26 16:39:58 +0000133static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000134 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000135
Craig Topperb45eabc2017-04-26 16:39:58 +0000136void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000137 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000138 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000139 const DominatorTree *DT,
140 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000141 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000142 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000143}
144
Craig Topper6e11a052017-05-08 16:22:48 +0000145static KnownBits computeKnownBits(const Value *V, unsigned Depth,
146 const Query &Q);
147
148KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
149 unsigned Depth, AssumptionCache *AC,
150 const Instruction *CxtI,
151 const DominatorTree *DT) {
152 return ::computeKnownBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
153}
154
Pete Cooper35b00d52016-08-13 01:05:32 +0000155bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
156 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000157 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000158 const DominatorTree *DT) {
159 assert(LHS->getType() == RHS->getType() &&
160 "LHS and RHS should have the same type");
161 assert(LHS->getType()->isIntOrIntVectorTy() &&
162 "LHS and RHS should be integers");
163 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000164 KnownBits LHSKnown(IT->getBitWidth());
165 KnownBits RHSKnown(IT->getBitWidth());
166 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
167 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
168 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000169}
170
Hal Finkel60db0582014-09-07 18:57:58 +0000171
Pete Cooper35b00d52016-08-13 01:05:32 +0000172void llvm::ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000174 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000175 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000176 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
177 KnownZero = Known.isNonNegative();
178 KnownOne = Known.isNegative();
Hal Finkel60db0582014-09-07 18:57:58 +0000179}
180
Pete Cooper35b00d52016-08-13 01:05:32 +0000181static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000182 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000183
Pete Cooper35b00d52016-08-13 01:05:32 +0000184bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
185 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000186 unsigned Depth, AssumptionCache *AC,
187 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000188 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000189 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000190 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000191}
192
Pete Cooper35b00d52016-08-13 01:05:32 +0000193static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000194
Pete Cooper35b00d52016-08-13 01:05:32 +0000195bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000196 AssumptionCache *AC, const Instruction *CxtI,
197 const DominatorTree *DT) {
198 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000199}
200
Pete Cooper35b00d52016-08-13 01:05:32 +0000201bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000202 unsigned Depth,
203 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000204 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000205 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
206 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000207}
208
Pete Cooper35b00d52016-08-13 01:05:32 +0000209bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000210 AssumptionCache *AC, const Instruction *CxtI,
211 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000212 if (auto *CI = dyn_cast<ConstantInt>(V))
213 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000214
Philip Reames8f12eba2016-03-09 21:31:47 +0000215 // TODO: We'd doing two recursive queries here. We should factor this such
216 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000217 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
218 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000219}
220
Pete Cooper35b00d52016-08-13 01:05:32 +0000221bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000222 AssumptionCache *AC, const Instruction *CxtI,
223 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000224 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
225 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000226}
227
Pete Cooper35b00d52016-08-13 01:05:32 +0000228static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000229
Pete Cooper35b00d52016-08-13 01:05:32 +0000230bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000231 const DataLayout &DL,
232 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000233 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000234 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
235 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000236 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000237}
238
Pete Cooper35b00d52016-08-13 01:05:32 +0000239static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000240 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000241
Pete Cooper35b00d52016-08-13 01:05:32 +0000242bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
243 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000244 unsigned Depth, AssumptionCache *AC,
245 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000246 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000247 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248}
249
Pete Cooper35b00d52016-08-13 01:05:32 +0000250static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
251 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000252
Pete Cooper35b00d52016-08-13 01:05:32 +0000253unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000254 unsigned Depth, AssumptionCache *AC,
255 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000256 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000257 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000258}
259
Craig Topper8fbb74b2017-03-24 22:12:10 +0000260static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
261 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000262 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000263 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000264 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000265
266 // If an initial sequence of bits in the result is not needed, the
267 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000268 KnownBits LHSKnown(BitWidth);
269 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
270 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000271
David Majnemer97ddca32014-08-22 00:40:43 +0000272 // Carry in a 1 for a subtract, rather than a 0.
Craig Topper059b98e2017-03-24 05:38:09 +0000273 uint64_t CarryIn = 0;
David Majnemer97ddca32014-08-22 00:40:43 +0000274 if (!Add) {
275 // Sum = LHS + ~RHS + 1
Craig Topperb45eabc2017-04-26 16:39:58 +0000276 std::swap(Known2.Zero, Known2.One);
Craig Topper059b98e2017-03-24 05:38:09 +0000277 CarryIn = 1;
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000278 }
279
Craig Topperb45eabc2017-04-26 16:39:58 +0000280 APInt PossibleSumZero = ~LHSKnown.Zero + ~Known2.Zero + CarryIn;
281 APInt PossibleSumOne = LHSKnown.One + Known2.One + CarryIn;
David Majnemer97ddca32014-08-22 00:40:43 +0000282
283 // Compute known bits of the carry.
Craig Topperb45eabc2017-04-26 16:39:58 +0000284 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnown.Zero ^ Known2.Zero);
285 APInt CarryKnownOne = PossibleSumOne ^ LHSKnown.One ^ Known2.One;
David Majnemer97ddca32014-08-22 00:40:43 +0000286
287 // Compute set of known bits (where all three relevant bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000288 APInt LHSKnownUnion = LHSKnown.Zero | LHSKnown.One;
289 APInt RHSKnownUnion = Known2.Zero | Known2.One;
290 APInt CarryKnownUnion = CarryKnownZero | CarryKnownOne;
291 APInt Known = LHSKnownUnion & RHSKnownUnion & CarryKnownUnion;
David Majnemer97ddca32014-08-22 00:40:43 +0000292
293 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
294 "known bits of sum differ");
295
296 // Compute known bits of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +0000297 KnownOut.Zero = ~PossibleSumOne & Known;
298 KnownOut.One = PossibleSumOne & Known;
David Majnemer97ddca32014-08-22 00:40:43 +0000299
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000300 // Are we still trying to solve for the sign bit?
Craig Topperd23004c2017-04-17 16:38:20 +0000301 if (!Known.isSignBitSet()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000302 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000303 // Adding two non-negative numbers, or subtracting a negative number from
304 // a non-negative one, can't wrap into negative.
Craig Topperca48af32017-04-29 16:43:11 +0000305 if (LHSKnown.isNonNegative() && Known2.isNonNegative())
306 KnownOut.makeNonNegative();
David Majnemer97ddca32014-08-22 00:40:43 +0000307 // Adding two negative numbers, or subtracting a non-negative number from
308 // a negative one, can't wrap into non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000309 else if (LHSKnown.isNegative() && Known2.isNegative())
310 KnownOut.makeNegative();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000311 }
312 }
313}
314
Pete Cooper35b00d52016-08-13 01:05:32 +0000315static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000316 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000317 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000318 unsigned BitWidth = Known.getBitWidth();
319 computeKnownBits(Op1, Known, Depth + 1, Q);
320 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000321
322 bool isKnownNegative = false;
323 bool isKnownNonNegative = false;
324 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000325 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000326 if (Op0 == Op1) {
327 // The product of a number with itself is non-negative.
328 isKnownNonNegative = true;
329 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000330 bool isKnownNonNegativeOp1 = Known.isNonNegative();
331 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
332 bool isKnownNegativeOp1 = Known.isNegative();
333 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000334 // The product of two numbers with the same sign is non-negative.
335 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
336 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
337 // The product of a negative number and a non-negative number is either
338 // negative or zero.
339 if (!isKnownNonNegative)
340 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000341 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000342 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000343 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000344 }
345 }
346
347 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000348 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000349 // More trickiness is possible, but this is sufficient for the
350 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000351 unsigned TrailZ = Known.countMinTrailingZeros() +
352 Known2.countMinTrailingZeros();
353 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
354 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000355 BitWidth) - BitWidth;
356
357 TrailZ = std::min(TrailZ, BitWidth);
358 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000359 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000360 Known.Zero.setLowBits(TrailZ);
361 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000362
363 // Only make use of no-wrap flags if we failed to compute the sign bit
364 // directly. This matters if the multiplication always overflows, in
365 // which case we prefer to follow the result of the direct computation,
366 // though as the program is invoking undefined behaviour we can choose
367 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000368 if (isKnownNonNegative && !Known.isNegative())
369 Known.makeNonNegative();
370 else if (isKnownNegative && !Known.isNonNegative())
371 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000372}
373
Jingyue Wu37fcb592014-06-19 16:50:16 +0000374void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000375 KnownBits &Known) {
376 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000377 unsigned NumRanges = Ranges.getNumOperands() / 2;
378 assert(NumRanges >= 1);
379
Craig Topperf42b23f2017-04-28 06:28:56 +0000380 Known.Zero.setAllBits();
381 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000382
Rafael Espindola53190532012-03-30 15:52:11 +0000383 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000384 ConstantInt *Lower =
385 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
386 ConstantInt *Upper =
387 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000388 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000389
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000390 // The first CommonPrefixBits of all values in Range are equal.
391 unsigned CommonPrefixBits =
392 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
393
394 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000395 Known.One &= Range.getUnsignedMax() & Mask;
396 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000397 }
Rafael Espindola53190532012-03-30 15:52:11 +0000398}
Jay Foad5a29c362014-05-15 12:12:55 +0000399
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000400static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000401 SmallVector<const Value *, 16> WorkSet(1, I);
402 SmallPtrSet<const Value *, 32> Visited;
403 SmallPtrSet<const Value *, 16> EphValues;
404
Hal Finkelf2199b22015-10-23 20:37:08 +0000405 // The instruction defining an assumption's condition itself is always
406 // considered ephemeral to that assumption (even if it has other
407 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000408 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000409 return true;
410
Hal Finkel60db0582014-09-07 18:57:58 +0000411 while (!WorkSet.empty()) {
412 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000413 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000414 continue;
415
416 // If all uses of this value are ephemeral, then so is this value.
David Majnemer0a16c222016-08-11 21:15:00 +0000417 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000418 if (V == E)
419 return true;
420
421 EphValues.insert(V);
422 if (const User *U = dyn_cast<User>(V))
423 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
424 J != JE; ++J) {
425 if (isSafeToSpeculativelyExecute(*J))
426 WorkSet.push_back(*J);
427 }
428 }
429 }
430
431 return false;
432}
433
434// Is this an intrinsic that cannot be speculated but also cannot trap?
435static bool isAssumeLikeIntrinsic(const Instruction *I) {
436 if (const CallInst *CI = dyn_cast<CallInst>(I))
437 if (Function *F = CI->getCalledFunction())
438 switch (F->getIntrinsicID()) {
439 default: break;
440 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
441 case Intrinsic::assume:
442 case Intrinsic::dbg_declare:
443 case Intrinsic::dbg_value:
444 case Intrinsic::invariant_start:
445 case Intrinsic::invariant_end:
446 case Intrinsic::lifetime_start:
447 case Intrinsic::lifetime_end:
448 case Intrinsic::objectsize:
449 case Intrinsic::ptr_annotation:
450 case Intrinsic::var_annotation:
451 return true;
452 }
453
454 return false;
455}
456
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000457bool llvm::isValidAssumeForContext(const Instruction *Inv,
458 const Instruction *CxtI,
459 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000460
461 // There are two restrictions on the use of an assume:
462 // 1. The assume must dominate the context (or the control flow must
463 // reach the assume whenever it reaches the context).
464 // 2. The context must not be in the assume's set of ephemeral values
465 // (otherwise we will use the assume to prove that the condition
466 // feeding the assume is trivially true, thus causing the removal of
467 // the assume).
468
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000469 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000470 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000471 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000472 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
473 // We don't have a DT, but this trivially dominates.
474 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000475 }
476
Pete Cooper54a02552016-08-12 01:00:15 +0000477 // With or without a DT, the only remaining case we will check is if the
478 // instructions are in the same BB. Give up if that is not the case.
479 if (Inv->getParent() != CxtI->getParent())
480 return false;
481
482 // If we have a dom tree, then we now know that the assume doens't dominate
483 // the other instruction. If we don't have a dom tree then we can check if
484 // the assume is first in the BB.
485 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000486 // Search forward from the assume until we reach the context (or the end
487 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000488 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000489 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000490 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000491 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000492 }
493
Pete Cooper54a02552016-08-12 01:00:15 +0000494 // The context comes first, but they're both in the same block. Make sure
495 // there is nothing in between that might interrupt the control flow.
496 for (BasicBlock::const_iterator I =
497 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
498 I != IE; ++I)
499 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
500 return false;
501
502 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000503}
504
Craig Topperb45eabc2017-04-26 16:39:58 +0000505static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
506 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000507 // Use of assumptions is context-sensitive. If we don't have a context, we
508 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000509 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000510 return;
511
Craig Topperb45eabc2017-04-26 16:39:58 +0000512 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000513
Hal Finkel8a9a7832017-01-11 13:24:24 +0000514 // Note that the patterns below need to be kept in sync with the code
515 // in AssumptionCache::updateAffectedValues.
516
517 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000518 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000519 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000520 CallInst *I = cast<CallInst>(AssumeVH);
521 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
522 "Got assumption for the wrong function!");
523 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000524 continue;
525
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000526 // Warning: This loop can end up being somewhat performance sensetive.
527 // We're running this loop for once for each value queried resulting in a
528 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000529
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000530 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
531 "must be an assume intrinsic");
532
533 Value *Arg = I->getArgOperand(0);
534
535 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000536 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000537 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000538 return;
539 }
Sanjay Patel96669962017-01-17 18:15:49 +0000540 if (match(Arg, m_Not(m_Specific(V))) &&
541 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
542 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000543 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000544 return;
545 }
Hal Finkel60db0582014-09-07 18:57:58 +0000546
David Majnemer9b609752014-12-12 23:59:29 +0000547 // The remaining tests are all recursive, so bail out if we hit the limit.
548 if (Depth == MaxDepth)
549 continue;
550
Hal Finkel60db0582014-09-07 18:57:58 +0000551 Value *A, *B;
552 auto m_V = m_CombineOr(m_Specific(V),
553 m_CombineOr(m_PtrToInt(m_Specific(V)),
554 m_BitCast(m_Specific(V))));
555
556 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000557 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000558 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000559 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000560 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000561 KnownBits RHSKnown(BitWidth);
562 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
563 Known.Zero |= RHSKnown.Zero;
564 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000565 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000566 } else if (match(Arg,
567 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000568 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000569 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000570 KnownBits RHSKnown(BitWidth);
571 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
572 KnownBits MaskKnown(BitWidth);
573 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000574
575 // For those bits in the mask that are known to be one, we can propagate
576 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000577 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
578 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000579 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000580 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
581 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000582 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000583 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000584 KnownBits RHSKnown(BitWidth);
585 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
586 KnownBits MaskKnown(BitWidth);
587 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000588
589 // For those bits in the mask that are known to be one, we can propagate
590 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000591 Known.Zero |= RHSKnown.One & MaskKnown.One;
592 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000593 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000594 } else if (match(Arg,
595 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000596 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000597 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000598 KnownBits RHSKnown(BitWidth);
599 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
600 KnownBits BKnown(BitWidth);
601 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000602
603 // For those bits in B that are known to be zero, we can propagate known
604 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000605 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
606 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000607 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000608 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
609 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000610 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000611 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000612 KnownBits RHSKnown(BitWidth);
613 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
614 KnownBits BKnown(BitWidth);
615 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000616
617 // For those bits in B that are known to be zero, we can propagate
618 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000619 Known.Zero |= RHSKnown.One & BKnown.Zero;
620 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000621 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 } else if (match(Arg,
623 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000624 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000625 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000626 KnownBits RHSKnown(BitWidth);
627 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
628 KnownBits BKnown(BitWidth);
629 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000630
631 // For those bits in B that are known to be zero, we can propagate known
632 // bits from the RHS to V. For those bits in B that are known to be one,
633 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000634 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
635 Known.One |= RHSKnown.One & BKnown.Zero;
636 Known.Zero |= RHSKnown.One & BKnown.One;
637 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000638 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000639 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
640 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000641 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000642 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000643 KnownBits RHSKnown(BitWidth);
644 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
645 KnownBits BKnown(BitWidth);
646 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000647
648 // For those bits in B that are known to be zero, we can propagate
649 // inverted known bits from the RHS to V. For those bits in B that are
650 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000651 Known.Zero |= RHSKnown.One & BKnown.Zero;
652 Known.One |= RHSKnown.Zero & BKnown.Zero;
653 Known.Zero |= RHSKnown.Zero & BKnown.One;
654 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000655 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000656 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
657 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000658 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000659 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000660 KnownBits RHSKnown(BitWidth);
661 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000662 // For those bits in RHS that are known, we can propagate them to known
663 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000664 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
665 Known.Zero |= RHSKnown.Zero;
666 RHSKnown.One.lshrInPlace(C->getZExtValue());
667 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000668 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000669 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
670 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000671 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000672 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000673 KnownBits RHSKnown(BitWidth);
674 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000675 // For those bits in RHS that are known, we can propagate them inverted
676 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000677 RHSKnown.One.lshrInPlace(C->getZExtValue());
678 Known.Zero |= RHSKnown.One;
679 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
680 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000681 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000682 } else if (match(Arg,
683 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000684 m_AShr(m_V, m_ConstantInt(C))),
685 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000686 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000687 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000688 KnownBits RHSKnown(BitWidth);
689 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000690 // For those bits in RHS that are known, we can propagate them to known
691 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000692 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
693 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000694 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000695 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000696 m_LShr(m_V, m_ConstantInt(C)),
697 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000698 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000699 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000700 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000701 KnownBits RHSKnown(BitWidth);
702 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000703 // For those bits in RHS that are known, we can propagate them inverted
704 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000705 Known.Zero |= RHSKnown.One << C->getZExtValue();
706 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000707 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000708 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000709 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000710 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000711 KnownBits RHSKnown(BitWidth);
712 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000713
Craig Topperca48af32017-04-29 16:43:11 +0000714 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000715 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000716 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000717 }
718 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000719 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000720 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000721 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000722 KnownBits RHSKnown(BitWidth);
723 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000724
Craig Topperf0aeee02017-05-05 17:36:09 +0000725 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000726 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000727 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000728 }
729 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000730 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000731 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000732 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000733 KnownBits RHSKnown(BitWidth);
734 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000735
Craig Topperca48af32017-04-29 16:43:11 +0000736 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000737 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000738 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000739 }
740 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000741 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000742 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000743 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000744 KnownBits RHSKnown(BitWidth);
745 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000746
Craig Topperf0aeee02017-05-05 17:36:09 +0000747 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000748 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000749 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000750 }
751 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000752 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000753 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000754 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000755 KnownBits RHSKnown(BitWidth);
756 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000757
758 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000759 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
760 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000761 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000762 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000763 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000764 KnownBits RHSKnown(BitWidth);
765 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000766
767 // Whatever high bits in c are zero are known to be zero (if c is a power
768 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000769 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000770 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000771 else
Craig Topper8df66c62017-05-12 17:20:30 +0000772 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000773 }
774 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000775
776 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000777 // have a logical fallacy. It's possible that the assumption is not reachable,
778 // so this isn't a real bug. On the other hand, the program may have undefined
779 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
780 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000781 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000782 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000783
784 if (Q.ORE) {
785 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
786 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
787 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
788 "have undefined behavior, or compiler may have "
789 "internal error.");
790 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000791 }
Hal Finkel60db0582014-09-07 18:57:58 +0000792}
793
Hal Finkelf2199b22015-10-23 20:37:08 +0000794// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000795// non-constant shift amount. Known is the outputs of this function. Known2 is a
796// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
797// operator-specific functors that, given the known-zero or known-one bits
798// respectively, and a shift amount, compute the implied known-zero or known-one
799// bits of the shift operator's result respectively for that shift amount. The
800// results from calling KZF and KOF are conservatively combined for all
801// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000802static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000803 const Operator *I, KnownBits &Known, KnownBits &Known2,
804 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000805 function_ref<APInt(const APInt &, unsigned)> KZF,
806 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000807 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000808
809 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
810 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
811
Craig Topperb45eabc2017-04-26 16:39:58 +0000812 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
813 Known.Zero = KZF(Known.Zero, ShiftAmt);
814 Known.One = KOF(Known.One, ShiftAmt);
815 // If there is conflict between Known.Zero and Known.One, this must be an
816 // overflowing left shift, so the shift result is undefined. Clear Known
817 // bits so that other code could propagate this undef.
Craig Topperf0aeee02017-05-05 17:36:09 +0000818 if ((Known.Zero & Known.One) != 0)
819 Known.resetAll();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000820
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)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000829 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000830 return;
831 }
832
Craig Topperb45eabc2017-04-26 16:39:58 +0000833 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000834 // BitWidth > 64 and any upper bits are known, we'll end up returning the
835 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000836 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
837 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000838
839 // It would be more-clearly correct to use the two temporaries for this
840 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000841 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000842
James Molloy493e57d2015-10-26 14:10:46 +0000843 // If we know the shifter operand is nonzero, we can sometimes infer more
844 // known bits. However this is expensive to compute, so be lazy about it and
845 // only compute it when absolutely necessary.
846 Optional<bool> ShifterOperandIsNonZero;
847
Hal Finkelf2199b22015-10-23 20:37:08 +0000848 // Early exit if we can't constrain any well-defined shift amount.
James Molloy493e57d2015-10-26 14:10:46 +0000849 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
850 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000851 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000852 if (!*ShifterOperandIsNonZero)
853 return;
854 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000855
Craig Topperb45eabc2017-04-26 16:39:58 +0000856 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000857
Craig Topperb45eabc2017-04-26 16:39:58 +0000858 Known.Zero.setAllBits();
859 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000860 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
861 // Combine the shifted known input bits only for those shift amounts
862 // compatible with its known constraints.
863 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
864 continue;
865 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
866 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000867 // If we know the shifter is nonzero, we may be able to infer more known
868 // bits. This check is sunk down as far as possible to avoid the expensive
869 // call to isKnownNonZero if the cheaper checks above fail.
870 if (ShiftAmt == 0) {
871 if (!ShifterOperandIsNonZero.hasValue())
872 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000873 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000874 if (*ShifterOperandIsNonZero)
875 continue;
876 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000877
Craig Topperb45eabc2017-04-26 16:39:58 +0000878 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
879 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000880 }
881
882 // If there are no compatible shift amounts, then we've proven that the shift
883 // amount must be >= the BitWidth, and the result is undefined. We could
884 // return anything we'd like, but we need to make sure the sets of known bits
885 // stay disjoint (it should be better for some other code to actually
886 // propagate the undef than to pick a value here using known bits).
Craig Topperf0aeee02017-05-05 17:36:09 +0000887 if (Known.Zero.intersects(Known.One))
888 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000889}
890
Craig Topperb45eabc2017-04-26 16:39:58 +0000891static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
892 unsigned Depth, const Query &Q) {
893 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000894
Craig Topperb45eabc2017-04-26 16:39:58 +0000895 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000896 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000897 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000898 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000899 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000900 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000901 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000902 case Instruction::And: {
903 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000904 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
905 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000906
Chris Lattner965c7692008-06-02 01:18:21 +0000907 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000909 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000910 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000911
912 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
913 // here we handle the more general case of adding any odd number by
914 // matching the form add(x, add(x, y)) where y is odd.
915 // TODO: This could be generalized to clearing any bit set in y where the
916 // following bit is known to be unset in y.
917 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000918 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000919 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
920 m_Value(Y))) ||
921 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
922 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000923 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000924 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000925 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000926 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000927 }
Jay Foad5a29c362014-05-15 12:12:55 +0000928 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000929 }
930 case Instruction::Or: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000931 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
932 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000933
Chris Lattner965c7692008-06-02 01:18:21 +0000934 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000935 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000936 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000937 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000938 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000939 }
940 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
942 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000943
Chris Lattner965c7692008-06-02 01:18:21 +0000944 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000945 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000946 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000947 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
948 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000949 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000950 }
951 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000952 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000953 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
954 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000955 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000956 }
957 case Instruction::UDiv: {
958 // For the purposes of computing leading zeros we can conservatively
959 // treat a udiv as a logical right shift by the power of 2 known to
960 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000961 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000962 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000963
Craig Topperf0aeee02017-05-05 17:36:09 +0000964 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000965 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000966 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
967 if (RHSMaxLeadingZeros != BitWidth)
968 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000969
Craig Topperb45eabc2017-04-26 16:39:58 +0000970 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000971 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000972 }
David Majnemera19d0f22016-08-06 08:16:00 +0000973 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000974 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000975 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
976 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000977 computeKnownBits(RHS, Known, Depth + 1, Q);
978 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000979 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000980 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
981 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000982 }
983
984 unsigned MaxHighOnes = 0;
985 unsigned MaxHighZeros = 0;
986 if (SPF == SPF_SMAX) {
987 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000988 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000989 // We can derive a lower bound on the result by taking the max of the
990 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000991 MaxHighOnes =
992 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000993 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000994 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000995 MaxHighZeros = 1;
996 } else if (SPF == SPF_SMIN) {
997 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000998 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000999 // We can derive an upper bound on the result by taking the max of the
1000 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001001 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1002 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001003 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001004 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001005 MaxHighOnes = 1;
1006 } else if (SPF == SPF_UMAX) {
1007 // We can derive a lower bound on the result by taking the max of the
1008 // leading one bits.
1009 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001010 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001011 } else if (SPF == SPF_UMIN) {
1012 // We can derive an upper bound on the result by taking the max of the
1013 // leading zero bits.
1014 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001015 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001016 }
1017
Chris Lattner965c7692008-06-02 01:18:21 +00001018 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001019 Known.One &= Known2.One;
1020 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001021 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001022 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001023 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001024 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001025 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001026 }
Chris Lattner965c7692008-06-02 01:18:21 +00001027 case Instruction::FPTrunc:
1028 case Instruction::FPExt:
1029 case Instruction::FPToUI:
1030 case Instruction::FPToSI:
1031 case Instruction::SIToFP:
1032 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001033 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001034 case Instruction::PtrToInt:
1035 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001036 // Fall through and handle them the same as zext/trunc.
1037 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001038 case Instruction::ZExt:
1039 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001040 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001041
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001042 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001043 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1044 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001045 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001046
1047 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001048 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001049 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001050 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001051 // Any top bits are known to be zero.
1052 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001053 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001054 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001055 }
1056 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001057 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001058 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001059 // TODO: For now, not handling conversions like:
1060 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001061 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001062 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001063 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001064 }
1065 break;
1066 }
1067 case Instruction::SExt: {
1068 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001069 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001070
Craig Topperd938fd12017-05-03 22:07:25 +00001071 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001072 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001073 // If the sign bit of the input is known set or clear, then we know the
1074 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001075 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001076 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001077 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001078 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001079 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001080 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001081 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1082 APInt KZResult = KnownZero << ShiftAmt;
1083 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001084 // If this shift has "nsw" keyword, then the result is either a poison
1085 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001086 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001087 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001088 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001089 };
1090
Craig Topperd73c6b42017-03-23 07:06:39 +00001091 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001092 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001093 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001094 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001095 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001096 };
1097
Craig Topperb45eabc2017-04-26 16:39:58 +00001098 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001099 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001100 }
1101 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001102 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001103 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1104 APInt KZResult = KnownZero.lshr(ShiftAmt);
1105 // High bits known zero.
1106 KZResult.setHighBits(ShiftAmt);
1107 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001108 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001109
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001110 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001111 return KnownOne.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001112 };
1113
Craig Topperb45eabc2017-04-26 16:39:58 +00001114 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001115 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001116 }
1117 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001118 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001119 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001120 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001121 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001122
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001123 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001124 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001125 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001126
Craig Topperb45eabc2017-04-26 16:39:58 +00001127 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001128 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001129 }
Chris Lattner965c7692008-06-02 01:18:21 +00001130 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001131 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001132 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001133 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001134 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001135 }
Chris Lattner965c7692008-06-02 01:18:21 +00001136 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001137 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001138 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001139 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001140 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001141 }
1142 case Instruction::SRem:
1143 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001144 APInt RA = Rem->getValue().abs();
1145 if (RA.isPowerOf2()) {
1146 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001147 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001148
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001149 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001150 Known.Zero = Known2.Zero & LowBits;
1151 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001152
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001153 // If the first operand is non-negative or has all low bits zero, then
1154 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001155 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001156 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001157
1158 // If the first operand is negative and not all low bits are zero, then
1159 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001160 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001161 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001162
Craig Topperb45eabc2017-04-26 16:39:58 +00001163 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001164 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001165 }
1166 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001167
1168 // The sign bit is the LHS's sign bit, except when the result of the
1169 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001170 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001171 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001172 if (Known2.isNonNegative())
1173 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001174
Chris Lattner965c7692008-06-02 01:18:21 +00001175 break;
1176 case Instruction::URem: {
1177 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001178 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001179 if (RA.isPowerOf2()) {
1180 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001181 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1182 Known.Zero |= ~LowBits;
1183 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001184 break;
1185 }
1186 }
1187
1188 // Since the result is less than or equal to either operand, any leading
1189 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001190 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1191 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001192
Craig Topper8df66c62017-05-12 17:20:30 +00001193 unsigned Leaders =
1194 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001195 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001196 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001197 break;
1198 }
1199
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001200 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001201 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001202 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001203 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001204 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001205
Chris Lattner965c7692008-06-02 01:18:21 +00001206 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001207 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001208 break;
1209 }
1210 case Instruction::GetElementPtr: {
1211 // Analyze all of the subscripts of this getelementptr instruction
1212 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001213 KnownBits LocalKnown(BitWidth);
1214 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001215 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001216
1217 gep_type_iterator GTI = gep_type_begin(I);
1218 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1219 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001220 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001221 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001222
1223 // Handle case when index is vector zeroinitializer
1224 Constant *CIndex = cast<Constant>(Index);
1225 if (CIndex->isZeroValue())
1226 continue;
1227
1228 if (CIndex->getType()->isVectorTy())
1229 Index = CIndex->getSplatValue();
1230
Chris Lattner965c7692008-06-02 01:18:21 +00001231 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001232 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001233 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001234 TrailZ = std::min<unsigned>(TrailZ,
1235 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001236 } else {
1237 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001238 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001239 if (!IndexedTy->isSized()) {
1240 TrailZ = 0;
1241 break;
1242 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001243 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001244 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001245 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1246 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001247 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001248 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001249 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001250 }
1251 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001252
Craig Topperb45eabc2017-04-26 16:39:58 +00001253 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001254 break;
1255 }
1256 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001257 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001258 // Handle the case of a simple two-predecessor recurrence PHI.
1259 // There's a lot more that could theoretically be done here, but
1260 // this is sufficient to catch some interesting cases.
1261 if (P->getNumIncomingValues() == 2) {
1262 for (unsigned i = 0; i != 2; ++i) {
1263 Value *L = P->getIncomingValue(i);
1264 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001265 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001266 if (!LU)
1267 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001268 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001269 // Check for operations that have the property that if
1270 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001271 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001272 if (Opcode == Instruction::Add ||
1273 Opcode == Instruction::Sub ||
1274 Opcode == Instruction::And ||
1275 Opcode == Instruction::Or ||
1276 Opcode == Instruction::Mul) {
1277 Value *LL = LU->getOperand(0);
1278 Value *LR = LU->getOperand(1);
1279 // Find a recurrence.
1280 if (LL == I)
1281 L = LR;
1282 else if (LR == I)
1283 L = LL;
1284 else
1285 break;
1286 // Ok, we have a PHI of the form L op= R. Check for low
1287 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001288 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001289
1290 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001291 KnownBits Known3(Known);
1292 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001293
Craig Topper8df66c62017-05-12 17:20:30 +00001294 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1295 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001296
1297 if (DontImproveNonNegativePhiBits)
1298 break;
1299
1300 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1301 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1302 // If initial value of recurrence is nonnegative, and we are adding
1303 // a nonnegative number with nsw, the result can only be nonnegative
1304 // or poison value regardless of the number of times we execute the
1305 // add in phi recurrence. If initial value is negative and we are
1306 // adding a negative number with nsw, the result can only be
1307 // negative or poison value. Similar arguments apply to sub and mul.
1308 //
1309 // (add non-negative, non-negative) --> non-negative
1310 // (add negative, negative) --> negative
1311 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001312 if (Known2.isNonNegative() && Known3.isNonNegative())
1313 Known.makeNonNegative();
1314 else if (Known2.isNegative() && Known3.isNegative())
1315 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001316 }
1317
1318 // (sub nsw non-negative, negative) --> non-negative
1319 // (sub nsw negative, non-negative) --> negative
1320 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001321 if (Known2.isNonNegative() && Known3.isNegative())
1322 Known.makeNonNegative();
1323 else if (Known2.isNegative() && Known3.isNonNegative())
1324 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001325 }
1326
1327 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001328 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1329 Known3.isNonNegative())
1330 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001331 }
1332
Chris Lattner965c7692008-06-02 01:18:21 +00001333 break;
1334 }
1335 }
1336 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001337
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001338 // Unreachable blocks may have zero-operand PHI nodes.
1339 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001340 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001341
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001342 // Otherwise take the unions of the known bit sets of the operands,
1343 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001344 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001345 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001346 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001347 break;
1348
Craig Topperb45eabc2017-04-26 16:39:58 +00001349 Known.Zero.setAllBits();
1350 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001351 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001352 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001353 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001354
Craig Topperb45eabc2017-04-26 16:39:58 +00001355 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001356 // Recurse, but cap the recursion to one level, because we don't
1357 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001358 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1359 Known.Zero &= Known2.Zero;
1360 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001361 // If all bits have been ruled out, there's no need to check
1362 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001363 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001364 break;
1365 }
1366 }
Chris Lattner965c7692008-06-02 01:18:21 +00001367 break;
1368 }
1369 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001370 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001371 // If range metadata is attached to this call, set known bits from that,
1372 // and then intersect with known bits based on other properties of the
1373 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001374 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001375 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001376 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001377 computeKnownBits(RV, Known2, Depth + 1, Q);
1378 Known.Zero |= Known2.Zero;
1379 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001380 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001381 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001382 switch (II->getIntrinsicID()) {
1383 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001384 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001385 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1386 Known.Zero |= Known2.Zero.reverseBits();
1387 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001388 break;
Philip Reames675418e2015-10-06 20:20:45 +00001389 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001390 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1391 Known.Zero |= Known2.Zero.byteSwap();
1392 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001393 break;
Craig Topper868813f2017-05-08 17:22:34 +00001394 case Intrinsic::ctlz: {
1395 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1396 // If we have a known 1, its position is our upper bound.
1397 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001398 // If this call is undefined for 0, the result will be less than 2^n.
1399 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001400 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1401 unsigned LowBits = Log2_32(PossibleLZ)+1;
1402 Known.Zero.setBitsFrom(LowBits);
1403 break;
1404 }
1405 case Intrinsic::cttz: {
1406 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1407 // If we have a known 1, its position is our upper bound.
1408 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1409 // If this call is undefined for 0, the result will be less than 2^n.
1410 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1411 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1412 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001413 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001414 break;
1415 }
1416 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001417 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001418 // We can bound the space the count needs. Also, bits known to be zero
1419 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001420 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001421 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001422 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001423 // TODO: we could bound KnownOne using the lower bound on the number
1424 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001425 break;
1426 }
Chad Rosierb3628842011-05-26 23:13:19 +00001427 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001428 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001429 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001430 }
1431 }
1432 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001433 case Instruction::ExtractElement:
1434 // Look through extract element. At the moment we keep this simple and skip
1435 // tracking the specific element. But at least we might find information
1436 // valid for all elements of the vector (for example if vector is sign
1437 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001438 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001439 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001440 case Instruction::ExtractValue:
1441 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001442 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001443 if (EVI->getNumIndices() != 1) break;
1444 if (EVI->getIndices()[0] == 0) {
1445 switch (II->getIntrinsicID()) {
1446 default: break;
1447 case Intrinsic::uadd_with_overflow:
1448 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001449 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001450 II->getArgOperand(1), false, Known, Known2,
1451 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001452 break;
1453 case Intrinsic::usub_with_overflow:
1454 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001455 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001456 II->getArgOperand(1), false, Known, Known2,
1457 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001458 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001459 case Intrinsic::umul_with_overflow:
1460 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001461 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001462 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001463 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001464 }
1465 }
1466 }
Chris Lattner965c7692008-06-02 01:18:21 +00001467 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001468}
1469
1470/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001471/// them.
1472KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1473 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1474 computeKnownBits(V, Known, Depth, Q);
1475 return Known;
1476}
1477
1478/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001479/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001480///
1481/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1482/// we cannot optimize based on the assumption that it is zero without changing
1483/// it to be an explicit zero. If we don't change it to zero, other code could
1484/// optimized based on the contradictory assumption that it is non-zero.
1485/// Because instcombine aggressively folds operations with undef args anyway,
1486/// this won't lose us code quality.
1487///
1488/// This function is defined on values with integer type, values with pointer
1489/// type, and vectors of integers. In the case
1490/// where V is a vector, known zero, and known one values are the
1491/// same width as the vector element, and the bit is set only if it is true
1492/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001493void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1494 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001495 assert(V && "No Value?");
1496 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001497 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001498
1499 assert((V->getType()->isIntOrIntVectorTy() ||
1500 V->getType()->getScalarType()->isPointerTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001501 "Not integer or pointer type!");
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001502 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Jingyue Wu12b0c282015-06-15 05:46:29 +00001503 (!V->getType()->isIntOrIntVectorTy() ||
1504 V->getType()->getScalarSizeInBits() == BitWidth) &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001505 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001506 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001507
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001508 const APInt *C;
1509 if (match(V, m_APInt(C))) {
1510 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001511 Known.One = *C;
1512 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001513 return;
1514 }
1515 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001516 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001517 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001518 return;
1519 }
1520 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001521 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001522 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001523 // We know that CDS must be a vector of integers. Take the intersection of
1524 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001525 Known.Zero.setAllBits(); Known.One.setAllBits();
Craig Topper9c932d32017-04-25 16:48:03 +00001526 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001527 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1528 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001529 Known.Zero &= ~Elt;
1530 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001531 }
1532 return;
1533 }
1534
Pete Cooper35b00d52016-08-13 01:05:32 +00001535 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001536 // We know that CV must be a vector of integers. Take the intersection of
1537 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001538 Known.Zero.setAllBits(); Known.One.setAllBits();
1539 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001540 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1541 Constant *Element = CV->getAggregateElement(i);
1542 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1543 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001544 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001545 return;
1546 }
1547 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001548 Known.Zero &= ~Elt;
1549 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001550 }
1551 return;
1552 }
1553
Jingyue Wu12b0c282015-06-15 05:46:29 +00001554 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001555 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001556
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001557 // We can't imply anything about undefs.
1558 if (isa<UndefValue>(V))
1559 return;
1560
1561 // There's no point in looking through other users of ConstantData for
1562 // assumptions. Confirm that we've handled them all.
1563 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1564
Jingyue Wu12b0c282015-06-15 05:46:29 +00001565 // Limit search depth.
1566 // All recursive calls that increase depth must come after this.
1567 if (Depth == MaxDepth)
1568 return;
1569
1570 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1571 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001572 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001573 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001574 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001575 return;
1576 }
1577
Pete Cooper35b00d52016-08-13 01:05:32 +00001578 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001579 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001580
Craig Topperb45eabc2017-04-26 16:39:58 +00001581 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001582 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001583 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001584 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001585 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001586 }
1587
Craig Topperb45eabc2017-04-26 16:39:58 +00001588 // computeKnownBitsFromAssume strictly refines Known.
1589 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001590
1591 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001592 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001593
Craig Topperb45eabc2017-04-26 16:39:58 +00001594 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001595}
1596
Sanjay Patelaee84212014-11-04 16:27:42 +00001597/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001598/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001599/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001600/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001601bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001602 const Query &Q) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001603 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001604 if (C->isNullValue())
1605 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001606
1607 const APInt *ConstIntOrConstSplatInt;
1608 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1609 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001610 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001611
1612 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1613 // it is shifted off the end then the result is undefined.
1614 if (match(V, m_Shl(m_One(), m_Value())))
1615 return true;
1616
Craig Topperbcfd2d12017-04-20 16:56:25 +00001617 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1618 // the bottom. If it is shifted off the bottom then the result is undefined.
1619 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001620 return true;
1621
1622 // The remaining tests are all recursive, so bail out if we hit the limit.
1623 if (Depth++ == MaxDepth)
1624 return false;
1625
Craig Topper9f008862014-04-15 04:59:12 +00001626 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001627 // A shift left or a logical shift right of a power of two is a power of two
1628 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001629 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001630 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001631 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001632
Pete Cooper35b00d52016-08-13 01:05:32 +00001633 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001634 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001635
Pete Cooper35b00d52016-08-13 01:05:32 +00001636 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001637 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1638 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001639
Duncan Sandsba286d72011-10-26 20:55:21 +00001640 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1641 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001642 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1643 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001644 return true;
1645 // X & (-X) is always a power of two or zero.
1646 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1647 return true;
1648 return false;
1649 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001650
David Majnemerb7d54092013-07-30 21:01:36 +00001651 // Adding a power-of-two or zero to the same power-of-two or zero yields
1652 // either the original power-of-two, a larger power-of-two or zero.
1653 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001654 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001655 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1656 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1657 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001658 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001659 return true;
1660 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1661 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001662 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001663 return true;
1664
1665 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001666 KnownBits LHSBits(BitWidth);
1667 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001668
Craig Topperb45eabc2017-04-26 16:39:58 +00001669 KnownBits RHSBits(BitWidth);
1670 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001671 // If i8 V is a power of two or zero:
1672 // ZeroBits: 1 1 1 0 1 1 1 1
1673 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001674 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001675 // If OrZero isn't set, we cannot give back a zero result.
1676 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001677 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001678 return true;
1679 }
1680 }
David Majnemerbeab5672013-05-18 19:30:37 +00001681
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001682 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001683 // is a power of two only if the first operand is a power of two and not
1684 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001685 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1686 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001687 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001688 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001689 }
1690
Duncan Sandsd3951082011-01-25 09:38:29 +00001691 return false;
1692}
1693
Chandler Carruth80d3e562012-12-07 02:08:58 +00001694/// \brief Test whether a GEP's result is known to be non-null.
1695///
1696/// Uses properties inherent in a GEP to try to determine whether it is known
1697/// to be non-null.
1698///
1699/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001700static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001701 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001702 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1703 return false;
1704
1705 // FIXME: Support vector-GEPs.
1706 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1707
1708 // If the base pointer is non-null, we cannot walk to a null address with an
1709 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001710 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001711 return true;
1712
Chandler Carruth80d3e562012-12-07 02:08:58 +00001713 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1714 // If so, then the GEP cannot produce a null pointer, as doing so would
1715 // inherently violate the inbounds contract within address space zero.
1716 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1717 GTI != GTE; ++GTI) {
1718 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001719 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001720 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1721 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001722 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001723 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1724 if (ElementOffset > 0)
1725 return true;
1726 continue;
1727 }
1728
1729 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001730 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001731 continue;
1732
1733 // Fast path the constant operand case both for efficiency and so we don't
1734 // increment Depth when just zipping down an all-constant GEP.
1735 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1736 if (!OpC->isZero())
1737 return true;
1738 continue;
1739 }
1740
1741 // We post-increment Depth here because while isKnownNonZero increments it
1742 // as well, when we pop back up that increment won't persist. We don't want
1743 // to recurse 10k times just because we have 10k GEP operands. We don't
1744 // bail completely out because we want to handle constant GEPs regardless
1745 // of depth.
1746 if (Depth++ >= MaxDepth)
1747 continue;
1748
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001749 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001750 return true;
1751 }
1752
1753 return false;
1754}
1755
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001756/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1757/// ensure that the value it's attached to is never Value? 'RangeType' is
1758/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001759static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001760 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1761 assert(NumRanges >= 1);
1762 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001763 ConstantInt *Lower =
1764 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1765 ConstantInt *Upper =
1766 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001767 ConstantRange Range(Lower->getValue(), Upper->getValue());
1768 if (Range.contains(Value))
1769 return false;
1770 }
1771 return true;
1772}
1773
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001774/// Return true if the given value is known to be non-zero when defined. For
1775/// vectors, return true if every element is known to be non-zero when
1776/// defined. For pointers, if the context instruction and dominator tree are
1777/// specified, perform context-sensitive analysis and return true if the
1778/// pointer couldn't possibly be null at the specified instruction.
1779/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001780bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001781 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001782 if (C->isNullValue())
1783 return false;
1784 if (isa<ConstantInt>(C))
1785 // Must be non-zero due to null test above.
1786 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001787
1788 // For constant vectors, check that all elements are undefined or known
1789 // non-zero to determine that the whole vector is known non-zero.
1790 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1791 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1792 Constant *Elt = C->getAggregateElement(i);
1793 if (!Elt || Elt->isNullValue())
1794 return false;
1795 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1796 return false;
1797 }
1798 return true;
1799 }
1800
Duncan Sandsd3951082011-01-25 09:38:29 +00001801 return false;
1802 }
1803
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001804 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001805 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001806 // If the possible ranges don't contain zero, then the value is
1807 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001808 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001809 const APInt ZeroValue(Ty->getBitWidth(), 0);
1810 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1811 return true;
1812 }
1813 }
1814 }
1815
Duncan Sandsd3951082011-01-25 09:38:29 +00001816 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001817 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001818 return false;
1819
Chandler Carruth80d3e562012-12-07 02:08:58 +00001820 // Check for pointer simplifications.
1821 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001822 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001823 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001824 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001825 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001826 return true;
1827 }
1828
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001829 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001830
1831 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001832 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001833 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001834 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001835
1836 // ext X != 0 if X != 0.
1837 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001838 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001839
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001840 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001841 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001842 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001843 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001844 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001845 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001846 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001847
Craig Topperb45eabc2017-04-26 16:39:58 +00001848 KnownBits Known(BitWidth);
1849 computeKnownBits(X, Known, Depth, Q);
1850 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001851 return true;
1852 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001853 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001854 // defined if the sign bit is shifted off the end.
1855 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001856 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001857 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001858 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001859 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001860
Craig Topper6e11a052017-05-08 16:22:48 +00001861 KnownBits Known = computeKnownBits(X, Depth, Q);
1862 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001863 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001864
1865 // If the shifter operand is a constant, and all of the bits shifted
1866 // out are known to be zero, and X is known non-zero then at least one
1867 // non-zero bit must remain.
1868 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001869 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1870 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001871 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001872 return true;
1873 // Are all the bits to be shifted out known zero?
Craig Topper8df66c62017-05-12 17:20:30 +00001874 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001875 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001876 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001877 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001878 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001879 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001880 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001881 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001882 // X + Y.
1883 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001884 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1885 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001886
1887 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001888 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001889 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001890 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001891 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001892
1893 // If X and Y are both negative (as signed values) then their sum is not
1894 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001895 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001896 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1897 // The sign bit of X is set. If some other bit is set then X is not equal
1898 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001899 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 return true;
1901 // The sign bit of Y is set. If some other bit is set then Y is not equal
1902 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001903 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001904 return true;
1905 }
1906
1907 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001908 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001909 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001910 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001911 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001912 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001913 return true;
1914 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001915 // X * Y.
1916 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001917 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001918 // If X and Y are non-zero then so is X * Y as long as the multiplication
1919 // does not overflow.
1920 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001921 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001922 return true;
1923 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001924 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001925 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001926 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1927 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001928 return true;
1929 }
James Molloy897048b2015-09-29 14:08:45 +00001930 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001931 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001932 // Try and detect a recurrence that monotonically increases from a
1933 // starting value, as these are common as induction variables.
1934 if (PN->getNumIncomingValues() == 2) {
1935 Value *Start = PN->getIncomingValue(0);
1936 Value *Induction = PN->getIncomingValue(1);
1937 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1938 std::swap(Start, Induction);
1939 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1940 if (!C->isZero() && !C->isNegative()) {
1941 ConstantInt *X;
1942 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1943 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1944 !X->isNegative())
1945 return true;
1946 }
1947 }
1948 }
Jun Bum Limca832662016-02-01 17:03:07 +00001949 // Check if all incoming values are non-zero constant.
1950 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1951 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
1952 });
1953 if (AllNonZeroConstants)
1954 return true;
James Molloy897048b2015-09-29 14:08:45 +00001955 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001956
Craig Topperb45eabc2017-04-26 16:39:58 +00001957 KnownBits Known(BitWidth);
1958 computeKnownBits(V, Known, Depth, Q);
1959 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001960}
1961
James Molloy1d88d6f2015-10-22 13:18:42 +00001962/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001963static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1964 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001965 if (!BO || BO->getOpcode() != Instruction::Add)
1966 return false;
1967 Value *Op = nullptr;
1968 if (V2 == BO->getOperand(0))
1969 Op = BO->getOperand(1);
1970 else if (V2 == BO->getOperand(1))
1971 Op = BO->getOperand(0);
1972 else
1973 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001974 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001975}
1976
1977/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001978static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001979 if (V1->getType()->isVectorTy() || V1 == V2)
1980 return false;
1981 if (V1->getType() != V2->getType())
1982 // We can't look through casts yet.
1983 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001984 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00001985 return true;
1986
1987 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
1988 // Are any known bits in V1 contradictory to known bits in V2? If V1
1989 // has a known zero where V2 has a known one, they must not be equal.
1990 auto BitWidth = Ty->getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00001991 KnownBits Known1(BitWidth);
1992 computeKnownBits(V1, Known1, 0, Q);
1993 KnownBits Known2(BitWidth);
1994 computeKnownBits(V2, Known2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001995
Craig Topperb45eabc2017-04-26 16:39:58 +00001996 APInt OppositeBits = (Known1.Zero & Known2.One) |
1997 (Known2.Zero & Known1.One);
James Molloy1d88d6f2015-10-22 13:18:42 +00001998 if (OppositeBits.getBoolValue())
1999 return true;
2000 }
2001 return false;
2002}
2003
Sanjay Patelaee84212014-11-04 16:27:42 +00002004/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2005/// simplify operations downstream. Mask is known to be zero for bits that V
2006/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002007///
2008/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002009/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002010/// where V is a vector, the mask, known zero, and known one values are the
2011/// same width as the vector element, and the bit is set only if it is true
2012/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002013bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002014 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002015 KnownBits Known(Mask.getBitWidth());
2016 computeKnownBits(V, Known, Depth, Q);
2017 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002018}
2019
Sanjay Patela06d9892016-06-22 19:20:59 +00002020/// For vector constants, loop over the elements and find the constant with the
2021/// minimum number of sign bits. Return 0 if the value is not a vector constant
2022/// or if any element was not analyzed; otherwise, return the count for the
2023/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002024static unsigned computeNumSignBitsVectorConstant(const Value *V,
2025 unsigned TyBits) {
2026 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002027 if (!CV || !CV->getType()->isVectorTy())
2028 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002029
Sanjay Patela06d9892016-06-22 19:20:59 +00002030 unsigned MinSignBits = TyBits;
2031 unsigned NumElts = CV->getType()->getVectorNumElements();
2032 for (unsigned i = 0; i != NumElts; ++i) {
2033 // If we find a non-ConstantInt, bail out.
2034 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2035 if (!Elt)
2036 return 0;
2037
2038 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2039 APInt EltVal = Elt->getValue();
2040 if (EltVal.isNegative())
2041 EltVal = ~EltVal;
2042 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2043 }
2044
2045 return MinSignBits;
2046}
Chris Lattner965c7692008-06-02 01:18:21 +00002047
Sanjoy Das39a684d2017-02-25 20:30:45 +00002048static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2049 const Query &Q);
2050
2051static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2052 const Query &Q) {
2053 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2054 assert(Result > 0 && "At least one sign bit needs to be present!");
2055 return Result;
2056}
2057
Sanjay Patelaee84212014-11-04 16:27:42 +00002058/// Return the number of times the sign bit of the register is replicated into
2059/// the other bits. We know that at least 1 bit is always equal to the sign bit
2060/// (itself), but other cases can give us information. For example, immediately
2061/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002062/// other, so we return 3. For vectors, return the number of sign bits for the
2063/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002064static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2065 const Query &Q) {
2066
2067 // We return the minimum number of sign bits that are guaranteed to be present
2068 // in V, so for undef we have to conservatively return 1. We don't have the
2069 // same behavior for poison though -- that's a FIXME today.
2070
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002071 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002072 unsigned Tmp, Tmp2;
2073 unsigned FirstAnswer = 1;
2074
Jay Foada0653a32014-05-14 21:14:37 +00002075 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002076 // below.
2077
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002078 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002079 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002080
Pete Cooper35b00d52016-08-13 01:05:32 +00002081 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002082 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002083 default: break;
2084 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002085 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002086 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002087
Nadav Rotemc99a3872015-03-06 00:23:58 +00002088 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002089 const APInt *Denominator;
2090 // sdiv X, C -> adds log(C) sign bits.
2091 if (match(U->getOperand(1), m_APInt(Denominator))) {
2092
2093 // Ignore non-positive denominator.
2094 if (!Denominator->isStrictlyPositive())
2095 break;
2096
2097 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002098 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002099
2100 // Add floor(log(C)) bits to the numerator bits.
2101 return std::min(TyBits, NumBits + Denominator->logBase2());
2102 }
2103 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002104 }
2105
2106 case Instruction::SRem: {
2107 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002108 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2109 // positive constant. This let us put a lower bound on the number of sign
2110 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002111 if (match(U->getOperand(1), m_APInt(Denominator))) {
2112
2113 // Ignore non-positive denominator.
2114 if (!Denominator->isStrictlyPositive())
2115 break;
2116
2117 // Calculate the incoming numerator bits. SRem by a positive constant
2118 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002119 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002120 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002121
2122 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002123 // denominator. Given that the denominator is positive, there are two
2124 // cases:
2125 //
2126 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2127 // (1 << ceilLogBase2(C)).
2128 //
2129 // 2. the numerator is negative. Then the result range is (-C,0] and
2130 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2131 //
2132 // Thus a lower bound on the number of sign bits is `TyBits -
2133 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002134
Sanjoy Dase561fee2015-03-25 22:33:53 +00002135 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002136 return std::max(NumrBits, ResBits);
2137 }
2138 break;
2139 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002140
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002141 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002142 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002143 // ashr X, C -> adds C sign bits. Vectors too.
2144 const APInt *ShAmt;
2145 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002146 unsigned ShAmtLimited = ShAmt->getZExtValue();
2147 if (ShAmtLimited >= TyBits)
2148 break; // Bad shift.
2149 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002150 if (Tmp > TyBits) Tmp = TyBits;
2151 }
2152 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002153 }
2154 case Instruction::Shl: {
2155 const APInt *ShAmt;
2156 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002157 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002158 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002159 Tmp2 = ShAmt->getZExtValue();
2160 if (Tmp2 >= TyBits || // Bad shift.
2161 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2162 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002163 }
2164 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002165 }
Chris Lattner965c7692008-06-02 01:18:21 +00002166 case Instruction::And:
2167 case Instruction::Or:
2168 case Instruction::Xor: // NOT is handled here.
2169 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002170 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002171 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002172 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002173 FirstAnswer = std::min(Tmp, Tmp2);
2174 // We computed what we know about the sign bits as our first
2175 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002176 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002177 }
2178 break;
2179
2180 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002181 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002182 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002183 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002184 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002185
Chris Lattner965c7692008-06-02 01:18:21 +00002186 case Instruction::Add:
2187 // Add can have at most one carry bit. Thus we know that the output
2188 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002189 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002190 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002191
Chris Lattner965c7692008-06-02 01:18:21 +00002192 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002193 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002194 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002195 KnownBits Known(TyBits);
2196 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002197
Chris Lattner965c7692008-06-02 01:18:21 +00002198 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2199 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002200 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002201 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002202
Chris Lattner965c7692008-06-02 01:18:21 +00002203 // If we are subtracting one from a positive number, there is no carry
2204 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002205 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002206 return Tmp;
2207 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002208
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002209 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002210 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002211 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002212
Chris Lattner965c7692008-06-02 01:18:21 +00002213 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002214 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002215 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002216
Chris Lattner965c7692008-06-02 01:18:21 +00002217 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002218 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002219 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002220 KnownBits Known(TyBits);
2221 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002222 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2223 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002224 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002225 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002226
Chris Lattner965c7692008-06-02 01:18:21 +00002227 // If the input is known to be positive (the sign bit is known clear),
2228 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002229 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002230 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002231
Chris Lattner965c7692008-06-02 01:18:21 +00002232 // Otherwise, we treat this like a SUB.
2233 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002234
Chris Lattner965c7692008-06-02 01:18:21 +00002235 // Sub can have at most one carry bit. Thus we know that the output
2236 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002237 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002238 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002239 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002240
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002241 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002242 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002243 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002244 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002245 if (NumIncomingValues > 4) break;
2246 // Unreachable blocks may have zero-operand PHI nodes.
2247 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002248
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002249 // Take the minimum of all incoming values. This can't infinitely loop
2250 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002251 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002252 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002253 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002254 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002255 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002256 }
2257 return Tmp;
2258 }
2259
Chris Lattner965c7692008-06-02 01:18:21 +00002260 case Instruction::Trunc:
2261 // FIXME: it's tricky to do anything useful for this, but it is an important
2262 // case for targets like X86.
2263 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002264
2265 case Instruction::ExtractElement:
2266 // Look through extract element. At the moment we keep this simple and skip
2267 // tracking the specific element. But at least we might find information
2268 // valid for all elements of the vector (for example if vector is sign
2269 // extended, shifted, etc).
2270 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002271 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002272
Chris Lattner965c7692008-06-02 01:18:21 +00002273 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2274 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002275
2276 // If we can examine all elements of a vector constant successfully, we're
2277 // done (we can't do any better than that). If not, keep trying.
2278 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2279 return VecSignBits;
2280
Craig Topperb45eabc2017-04-26 16:39:58 +00002281 KnownBits Known(TyBits);
2282 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002283
Sanjay Patele0536212016-06-23 17:41:59 +00002284 // If we know that the sign bit is either zero or one, determine the number of
2285 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002286 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002287}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002288
Sanjay Patelaee84212014-11-04 16:27:42 +00002289/// This function computes the integer multiple of Base that equals V.
2290/// If successful, it returns true and returns the multiple in
2291/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002292/// through SExt instructions only if LookThroughSExt is true.
2293bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002294 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002295 const unsigned MaxDepth = 6;
2296
Dan Gohman6a976bb2009-11-18 00:58:27 +00002297 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002298 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002299 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002300
Chris Lattner229907c2011-07-18 04:54:35 +00002301 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002302
Dan Gohman6a976bb2009-11-18 00:58:27 +00002303 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002304
2305 if (Base == 0)
2306 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002307
Victor Hernandez47444882009-11-10 08:28:35 +00002308 if (Base == 1) {
2309 Multiple = V;
2310 return true;
2311 }
2312
2313 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2314 Constant *BaseVal = ConstantInt::get(T, Base);
2315 if (CO && CO == BaseVal) {
2316 // Multiple is 1.
2317 Multiple = ConstantInt::get(T, 1);
2318 return true;
2319 }
2320
2321 if (CI && CI->getZExtValue() % Base == 0) {
2322 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002323 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002324 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002325
Victor Hernandez47444882009-11-10 08:28:35 +00002326 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002327
Victor Hernandez47444882009-11-10 08:28:35 +00002328 Operator *I = dyn_cast<Operator>(V);
2329 if (!I) return false;
2330
2331 switch (I->getOpcode()) {
2332 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002333 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002334 if (!LookThroughSExt) return false;
2335 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002336 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002337 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2338 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002339 case Instruction::Shl:
2340 case Instruction::Mul: {
2341 Value *Op0 = I->getOperand(0);
2342 Value *Op1 = I->getOperand(1);
2343
2344 if (I->getOpcode() == Instruction::Shl) {
2345 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2346 if (!Op1CI) return false;
2347 // Turn Op0 << Op1 into Op0 * 2^Op1
2348 APInt Op1Int = Op1CI->getValue();
2349 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002350 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002351 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002352 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002353 }
2354
Craig Topper9f008862014-04-15 04:59:12 +00002355 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002356 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2357 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2358 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002359 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002360 MulC->getType()->getPrimitiveSizeInBits())
2361 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002362 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002363 MulC->getType()->getPrimitiveSizeInBits())
2364 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002365
Chris Lattner72d283c2010-09-05 17:20:46 +00002366 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2367 Multiple = ConstantExpr::getMul(MulC, Op1C);
2368 return true;
2369 }
Victor Hernandez47444882009-11-10 08:28:35 +00002370
2371 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2372 if (Mul0CI->getValue() == 1) {
2373 // V == Base * Op1, so return Op1
2374 Multiple = Op1;
2375 return true;
2376 }
2377 }
2378
Craig Topper9f008862014-04-15 04:59:12 +00002379 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002380 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2381 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2382 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002383 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002384 MulC->getType()->getPrimitiveSizeInBits())
2385 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002386 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002387 MulC->getType()->getPrimitiveSizeInBits())
2388 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002389
Chris Lattner72d283c2010-09-05 17:20:46 +00002390 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2391 Multiple = ConstantExpr::getMul(MulC, Op0C);
2392 return true;
2393 }
Victor Hernandez47444882009-11-10 08:28:35 +00002394
2395 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2396 if (Mul1CI->getValue() == 1) {
2397 // V == Base * Op0, so return Op0
2398 Multiple = Op0;
2399 return true;
2400 }
2401 }
Victor Hernandez47444882009-11-10 08:28:35 +00002402 }
2403 }
2404
2405 // We could not determine if V is a multiple of Base.
2406 return false;
2407}
2408
David Majnemerb4b27232016-04-19 19:10:21 +00002409Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2410 const TargetLibraryInfo *TLI) {
2411 const Function *F = ICS.getCalledFunction();
2412 if (!F)
2413 return Intrinsic::not_intrinsic;
2414
2415 if (F->isIntrinsic())
2416 return F->getIntrinsicID();
2417
2418 if (!TLI)
2419 return Intrinsic::not_intrinsic;
2420
David L. Jonesd21529f2017-01-23 23:16:46 +00002421 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002422 // We're going to make assumptions on the semantics of the functions, check
2423 // that the target knows that it's available in this environment and it does
2424 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002425 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2426 return Intrinsic::not_intrinsic;
2427
2428 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002429 return Intrinsic::not_intrinsic;
2430
2431 // Otherwise check if we have a call to a function that can be turned into a
2432 // vector intrinsic.
2433 switch (Func) {
2434 default:
2435 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002436 case LibFunc_sin:
2437 case LibFunc_sinf:
2438 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002439 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002440 case LibFunc_cos:
2441 case LibFunc_cosf:
2442 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002443 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002444 case LibFunc_exp:
2445 case LibFunc_expf:
2446 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002447 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002448 case LibFunc_exp2:
2449 case LibFunc_exp2f:
2450 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002451 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002452 case LibFunc_log:
2453 case LibFunc_logf:
2454 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002455 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002456 case LibFunc_log10:
2457 case LibFunc_log10f:
2458 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002459 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002460 case LibFunc_log2:
2461 case LibFunc_log2f:
2462 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002463 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002464 case LibFunc_fabs:
2465 case LibFunc_fabsf:
2466 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002467 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002468 case LibFunc_fmin:
2469 case LibFunc_fminf:
2470 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002471 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002472 case LibFunc_fmax:
2473 case LibFunc_fmaxf:
2474 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002475 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002476 case LibFunc_copysign:
2477 case LibFunc_copysignf:
2478 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002479 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002480 case LibFunc_floor:
2481 case LibFunc_floorf:
2482 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002483 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002484 case LibFunc_ceil:
2485 case LibFunc_ceilf:
2486 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002487 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002488 case LibFunc_trunc:
2489 case LibFunc_truncf:
2490 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002491 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002492 case LibFunc_rint:
2493 case LibFunc_rintf:
2494 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002495 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002496 case LibFunc_nearbyint:
2497 case LibFunc_nearbyintf:
2498 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002499 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002500 case LibFunc_round:
2501 case LibFunc_roundf:
2502 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002503 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002504 case LibFunc_pow:
2505 case LibFunc_powf:
2506 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002507 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002508 case LibFunc_sqrt:
2509 case LibFunc_sqrtf:
2510 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002511 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002512 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002513 return Intrinsic::not_intrinsic;
2514 }
2515
2516 return Intrinsic::not_intrinsic;
2517}
2518
Sanjay Patelaee84212014-11-04 16:27:42 +00002519/// Return true if we can prove that the specified FP value is never equal to
2520/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002521///
2522/// NOTE: this function will need to be revisited when we support non-default
2523/// rounding modes!
2524///
David Majnemer3ee5f342016-04-13 06:55:52 +00002525bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2526 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002527 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2528 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002529
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002530 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002531 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002532
Dan Gohman80ca01c2009-07-17 20:47:02 +00002533 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002534 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002535
2536 // Check if the nsz fast-math flag is set
2537 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2538 if (FPO->hasNoSignedZeros())
2539 return true;
2540
Chris Lattnera12a6de2008-06-02 01:29:46 +00002541 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002542 if (I->getOpcode() == Instruction::FAdd)
2543 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2544 if (CFP->isNullValue())
2545 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002546
Chris Lattnera12a6de2008-06-02 01:29:46 +00002547 // sitofp and uitofp turn into +0.0 for zero.
2548 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2549 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002550
David Majnemer3ee5f342016-04-13 06:55:52 +00002551 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002552 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002553 switch (IID) {
2554 default:
2555 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002556 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002557 case Intrinsic::sqrt:
2558 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2559 // fabs(x) != -0.0
2560 case Intrinsic::fabs:
2561 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002562 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002563 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002564
Chris Lattnera12a6de2008-06-02 01:29:46 +00002565 return false;
2566}
2567
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002568/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2569/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2570/// bit despite comparing equal.
2571static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2572 const TargetLibraryInfo *TLI,
2573 bool SignBitOnly,
2574 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002575 // TODO: This function does not do the right thing when SignBitOnly is true
2576 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2577 // which flips the sign bits of NaNs. See
2578 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2579
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002580 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2581 return !CFP->getValueAPF().isNegative() ||
2582 (!SignBitOnly && CFP->getValueAPF().isZero());
2583 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002584
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002585 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002586 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002587
2588 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002589 if (!I)
2590 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002591
2592 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002593 default:
2594 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002595 // Unsigned integers are always nonnegative.
2596 case Instruction::UIToFP:
2597 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002598 case Instruction::FMul:
2599 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002600 if (I->getOperand(0) == I->getOperand(1) &&
2601 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002602 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002603
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002604 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002605 case Instruction::FAdd:
2606 case Instruction::FDiv:
2607 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002608 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2609 Depth + 1) &&
2610 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2611 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002612 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002613 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2614 Depth + 1) &&
2615 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2616 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002617 case Instruction::FPExt:
2618 case Instruction::FPTrunc:
2619 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002620 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2621 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002622 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002623 const auto *CI = cast<CallInst>(I);
2624 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002625 switch (IID) {
2626 default:
2627 break;
2628 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002629 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2630 Depth + 1) ||
2631 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2632 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002633 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002634 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2635 Depth + 1) &&
2636 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2637 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002638 case Intrinsic::exp:
2639 case Intrinsic::exp2:
2640 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002641 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002642
2643 case Intrinsic::sqrt:
2644 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2645 if (!SignBitOnly)
2646 return true;
2647 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2648 CannotBeNegativeZero(CI->getOperand(0), TLI));
2649
David Majnemer3ee5f342016-04-13 06:55:52 +00002650 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002651 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002652 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002653 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002654 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002655 }
Justin Lebar322c1272017-01-27 00:58:34 +00002656 // TODO: This is not correct. Given that exp is an integer, here are the
2657 // ways that pow can return a negative value:
2658 //
2659 // pow(x, exp) --> negative if exp is odd and x is negative.
2660 // pow(-0, exp) --> -inf if exp is negative odd.
2661 // pow(-0, exp) --> -0 if exp is positive odd.
2662 // pow(-inf, exp) --> -0 if exp is negative odd.
2663 // pow(-inf, exp) --> -inf if exp is positive odd.
2664 //
2665 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2666 // but we must return false if x == -0. Unfortunately we do not currently
2667 // have a way of expressing this constraint. See details in
2668 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002669 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2670 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002671
David Majnemer3ee5f342016-04-13 06:55:52 +00002672 case Intrinsic::fma:
2673 case Intrinsic::fmuladd:
2674 // x*x+y is non-negative if y is non-negative.
2675 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002676 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2677 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2678 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002679 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002680 break;
2681 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002682 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002683}
2684
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002685bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2686 const TargetLibraryInfo *TLI) {
2687 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2688}
2689
2690bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2691 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2692}
2693
Sanjay Patelaee84212014-11-04 16:27:42 +00002694/// If the specified value can be set by repeating the same byte in memory,
2695/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002696/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2697/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2698/// byte store (e.g. i16 0x1234), return null.
2699Value *llvm::isBytewiseValue(Value *V) {
2700 // All byte-wide stores are splatable, even of arbitrary variables.
2701 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002702
2703 // Handle 'null' ConstantArrayZero etc.
2704 if (Constant *C = dyn_cast<Constant>(V))
2705 if (C->isNullValue())
2706 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002707
Chris Lattner9cb10352010-12-26 20:15:01 +00002708 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002709 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002710 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2711 if (CFP->getType()->isFloatTy())
2712 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2713 if (CFP->getType()->isDoubleTy())
2714 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2715 // Don't handle long double formats, which have strange constraints.
2716 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002717
Benjamin Kramer17d90152015-02-07 19:29:02 +00002718 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002719 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002720 if (CI->getBitWidth() % 8 == 0) {
2721 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002722
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002723 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002724 return nullptr;
2725 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002726 }
2727 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002728
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002729 // A ConstantDataArray/Vector is splatable if all its members are equal and
2730 // also splatable.
2731 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2732 Value *Elt = CA->getElementAsConstant(0);
2733 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002734 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002735 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002736
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002737 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2738 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002739 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002740
Chris Lattner9cb10352010-12-26 20:15:01 +00002741 return Val;
2742 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002743
Chris Lattner9cb10352010-12-26 20:15:01 +00002744 // Conceptually, we could handle things like:
2745 // %a = zext i8 %X to i16
2746 // %b = shl i16 %a, 8
2747 // %c = or i16 %a, %b
2748 // but until there is an example that actually needs this, it doesn't seem
2749 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002750 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002751}
2752
2753
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002754// This is the recursive version of BuildSubAggregate. It takes a few different
2755// arguments. Idxs is the index within the nested struct From that we are
2756// looking at now (which is of type IndexedType). IdxSkip is the number of
2757// indices from Idxs that should be left out when inserting into the resulting
2758// struct. To is the result struct built so far, new insertvalue instructions
2759// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002760static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002761 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002762 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002763 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002764 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002765 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002766 // Save the original To argument so we can modify it
2767 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002768 // General case, the type indexed by Idxs is a struct
2769 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2770 // Process each struct element recursively
2771 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002772 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002773 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002774 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002775 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002776 if (!To) {
2777 // Couldn't find any inserted value for this index? Cleanup
2778 while (PrevTo != OrigTo) {
2779 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2780 PrevTo = Del->getAggregateOperand();
2781 Del->eraseFromParent();
2782 }
2783 // Stop processing elements
2784 break;
2785 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002786 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002787 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002788 if (To)
2789 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002790 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002791 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2792 // the struct's elements had a value that was inserted directly. In the latter
2793 // case, perhaps we can't determine each of the subelements individually, but
2794 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002795
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002796 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002797 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002798
2799 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002800 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002801
2802 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002803 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002804 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002805}
2806
2807// This helper takes a nested struct and extracts a part of it (which is again a
2808// struct) into a new value. For example, given the struct:
2809// { a, { b, { c, d }, e } }
2810// and the indices "1, 1" this returns
2811// { c, d }.
2812//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002813// It does this by inserting an insertvalue for each element in the resulting
2814// struct, as opposed to just inserting a single struct. This will only work if
2815// each of the elements of the substruct are known (ie, inserted into From by an
2816// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002817//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002818// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002819static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002820 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002821 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002822 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002823 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002824 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002825 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002826 unsigned IdxSkip = Idxs.size();
2827
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002828 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002829}
2830
Sanjay Patelaee84212014-11-04 16:27:42 +00002831/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002832/// the scalar value indexed is already around as a register, for example if it
2833/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002834///
2835/// If InsertBefore is not null, this function will duplicate (modified)
2836/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002837Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2838 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002839 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002840 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002841 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002842 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002843 // We have indices, so V should have an indexable type.
2844 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2845 "Not looking at a struct or array?");
2846 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2847 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002848
Chris Lattner67058832012-01-25 06:48:06 +00002849 if (Constant *C = dyn_cast<Constant>(V)) {
2850 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002851 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002852 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2853 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002854
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002855 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002856 // Loop the indices for the insertvalue instruction in parallel with the
2857 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002858 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002859 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2860 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002861 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002862 // We can't handle this without inserting insertvalues
2863 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002864 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002865
2866 // The requested index identifies a part of a nested aggregate. Handle
2867 // this specially. For example,
2868 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2869 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2870 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2871 // This can be changed into
2872 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2873 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2874 // which allows the unused 0,0 element from the nested struct to be
2875 // removed.
2876 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2877 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002878 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002879
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002880 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002881 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002882 // looking for, then.
2883 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002884 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002885 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002886 }
2887 // If we end up here, the indices of the insertvalue match with those
2888 // requested (though possibly only partially). Now we recursively look at
2889 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002890 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002891 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002892 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002893 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002894
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002895 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002896 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002897 // something else, we can extract from that something else directly instead.
2898 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002899
2900 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002901 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002902 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002903 SmallVector<unsigned, 5> Idxs;
2904 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002905 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002906 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002907
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002908 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002909 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002910
Craig Topper1bef2c82012-12-22 19:15:35 +00002911 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002912 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002913
Jay Foad57aa6362011-07-13 10:26:04 +00002914 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002915 }
2916 // Otherwise, we don't know (such as, extracting from a function return value
2917 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002918 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002919}
Evan Chengda3db112008-06-30 07:31:25 +00002920
Sanjay Patelaee84212014-11-04 16:27:42 +00002921/// Analyze the specified pointer to see if it can be expressed as a base
2922/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002923Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002924 const DataLayout &DL) {
2925 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002926 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002927
2928 // We walk up the defs but use a visited set to handle unreachable code. In
2929 // that case, we stop after accumulating the cycle once (not that it
2930 // matters).
2931 SmallPtrSet<Value *, 16> Visited;
2932 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002933 if (Ptr->getType()->isVectorTy())
2934 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002935
Nuno Lopes368c4d02012-12-31 20:48:35 +00002936 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002937 // If one of the values we have visited is an addrspacecast, then
2938 // the pointer type of this GEP may be different from the type
2939 // of the Ptr parameter which was passed to this function. This
2940 // means when we construct GEPOffset, we need to use the size
2941 // of GEP's pointer type rather than the size of the original
2942 // pointer type.
2943 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002944 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2945 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002946
Tom Stellard17eb3412016-10-07 14:23:29 +00002947 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002948
Nuno Lopes368c4d02012-12-31 20:48:35 +00002949 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002950 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2951 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002952 Ptr = cast<Operator>(Ptr)->getOperand(0);
2953 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002954 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002955 break;
2956 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002957 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002958 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002959 }
2960 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002961 Offset = ByteOffset.getSExtValue();
2962 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002963}
2964
David L Kreitzer752c1442016-04-13 14:31:06 +00002965bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP) {
2966 // Make sure the GEP has exactly three arguments.
2967 if (GEP->getNumOperands() != 3)
2968 return false;
2969
2970 // Make sure the index-ee is a pointer to array of i8.
2971 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2972 if (!AT || !AT->getElementType()->isIntegerTy(8))
2973 return false;
2974
2975 // Check to make sure that the first operand of the GEP is an integer and
2976 // has value 0 so that we are sure we're indexing into the initializer.
2977 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2978 if (!FirstIdx || !FirstIdx->isZero())
2979 return false;
2980
2981 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002982}
Chris Lattnere28618d2010-11-30 22:25:26 +00002983
Sanjay Patelaee84212014-11-04 16:27:42 +00002984/// This function computes the length of a null-terminated C string pointed to
2985/// by V. If successful, it returns true and returns the string in Str.
2986/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002987bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2988 uint64_t Offset, bool TrimAtNul) {
2989 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002990
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002991 // Look through bitcast instructions and geps.
2992 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002993
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002994 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002995 // offset.
2996 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002997 // The GEP operator should be based on a pointer to string constant, and is
2998 // indexing into the string constant.
2999 if (!isGEPBasedOnPointerToString(GEP))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003000 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003001
Evan Chengda3db112008-06-30 07:31:25 +00003002 // If the second index isn't a ConstantInt, then this is a variable index
3003 // into the array. If this occurs, we can't say anything meaningful about
3004 // the string.
3005 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003006 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003007 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003008 else
3009 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003010 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
3011 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00003012 }
Nick Lewycky46209882011-10-20 00:34:35 +00003013
Evan Chengda3db112008-06-30 07:31:25 +00003014 // The GEP instruction, constant or instruction, must reference a global
3015 // variable that is a constant and is initialized. The referenced constant
3016 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003017 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003018 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003019 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003020
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003021 // Handle the all-zeros case.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003022 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00003023 // This is a degenerate case. The initializer is constant zero so the
3024 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003025 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003026 return true;
3027 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003028
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003029 // This must be a ConstantDataArray.
3030 const auto *Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00003031 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003032 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003033
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003034 // Get the number of elements in the array.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003035 uint64_t NumElts = Array->getType()->getArrayNumElements();
3036
3037 // Start out with the entire array in the StringRef.
3038 Str = Array->getAsString();
3039
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003040 if (Offset > NumElts)
3041 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003042
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003043 // Skip over 'offset' bytes.
3044 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003045
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003046 if (TrimAtNul) {
3047 // Trim off the \0 and anything after it. If the array is not nul
3048 // terminated, we just return the whole end of string. The client may know
3049 // some other way that the string is length-bound.
3050 Str = Str.substr(0, Str.find('\0'));
3051 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003052 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003053}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003054
3055// These next two are very similar to the above, but also look through PHI
3056// nodes.
3057// TODO: See if we can integrate these two together.
3058
Sanjay Patelaee84212014-11-04 16:27:42 +00003059/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003060/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003061static uint64_t GetStringLengthH(const Value *V,
3062 SmallPtrSetImpl<const PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003063 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003064 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003065
3066 // If this is a PHI node, there are two cases: either we have already seen it
3067 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003068 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003069 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003070 return ~0ULL; // already in the set.
3071
3072 // If it was new, see if all the input strings are the same length.
3073 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003074 for (Value *IncValue : PN->incoming_values()) {
3075 uint64_t Len = GetStringLengthH(IncValue, PHIs);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003076 if (Len == 0) return 0; // Unknown length -> unknown.
3077
3078 if (Len == ~0ULL) continue;
3079
3080 if (Len != LenSoFar && LenSoFar != ~0ULL)
3081 return 0; // Disagree -> unknown.
3082 LenSoFar = Len;
3083 }
3084
3085 // Success, all agree.
3086 return LenSoFar;
3087 }
3088
3089 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003090 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003091 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
3092 if (Len1 == 0) return 0;
3093 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
3094 if (Len2 == 0) return 0;
3095 if (Len1 == ~0ULL) return Len2;
3096 if (Len2 == ~0ULL) return Len1;
3097 if (Len1 != Len2) return 0;
3098 return Len1;
3099 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003100
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003101 // Otherwise, see if we can read the string.
3102 StringRef StrData;
3103 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003104 return 0;
3105
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003106 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003107}
3108
Sanjay Patelaee84212014-11-04 16:27:42 +00003109/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003110/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003111uint64_t llvm::GetStringLength(const Value *V) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003112 if (!V->getType()->isPointerTy()) return 0;
3113
Pete Cooper35b00d52016-08-13 01:05:32 +00003114 SmallPtrSet<const PHINode*, 32> PHIs;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003115 uint64_t Len = GetStringLengthH(V, PHIs);
3116 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3117 // an empty string as a length.
3118 return Len == ~0ULL ? 1 : Len;
3119}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003120
Adam Nemete2b885c2015-04-23 20:09:20 +00003121/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3122/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003123static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3124 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003125 // Find the loop-defined value.
3126 Loop *L = LI->getLoopFor(PN->getParent());
3127 if (PN->getNumIncomingValues() != 2)
3128 return true;
3129
3130 // Find the value from previous iteration.
3131 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3132 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3133 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3134 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3135 return true;
3136
3137 // If a new pointer is loaded in the loop, the pointer references a different
3138 // object in every iteration. E.g.:
3139 // for (i)
3140 // int *p = a[i];
3141 // ...
3142 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3143 if (!L->isLoopInvariant(Load->getPointerOperand()))
3144 return false;
3145 return true;
3146}
3147
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003148Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3149 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003150 if (!V->getType()->isPointerTy())
3151 return V;
3152 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3153 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3154 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003155 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3156 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003157 V = cast<Operator>(V)->getOperand(0);
3158 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003159 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003160 return V;
3161 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003162 } else if (isa<AllocaInst>(V)) {
3163 // An alloca can't be further simplified.
3164 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003165 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003166 if (auto CS = CallSite(V))
3167 if (Value *RV = CS.getReturnedArgOperand()) {
3168 V = RV;
3169 continue;
3170 }
3171
Dan Gohman05b18f12010-12-15 20:49:55 +00003172 // See if InstructionSimplify knows any relevant tricks.
3173 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003174 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003175 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003176 V = Simplified;
3177 continue;
3178 }
3179
Dan Gohmana4fcd242010-12-15 20:02:24 +00003180 return V;
3181 }
3182 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3183 }
3184 return V;
3185}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003186
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003187void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003188 const DataLayout &DL, LoopInfo *LI,
3189 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003190 SmallPtrSet<Value *, 4> Visited;
3191 SmallVector<Value *, 4> Worklist;
3192 Worklist.push_back(V);
3193 do {
3194 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003195 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003196
David Blaikie70573dc2014-11-19 07:49:26 +00003197 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003198 continue;
3199
3200 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3201 Worklist.push_back(SI->getTrueValue());
3202 Worklist.push_back(SI->getFalseValue());
3203 continue;
3204 }
3205
3206 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003207 // If this PHI changes the underlying object in every iteration of the
3208 // loop, don't look through it. Consider:
3209 // int **A;
3210 // for (i) {
3211 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3212 // Curr = A[i];
3213 // *Prev, *Curr;
3214 //
3215 // Prev is tracking Curr one iteration behind so they refer to different
3216 // underlying objects.
3217 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3218 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003219 for (Value *IncValue : PN->incoming_values())
3220 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003221 continue;
3222 }
3223
3224 Objects.push_back(P);
3225 } while (!Worklist.empty());
3226}
3227
Sanjay Patelaee84212014-11-04 16:27:42 +00003228/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003229bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003230 for (const User *U : V->users()) {
3231 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003232 if (!II) return false;
3233
3234 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3235 II->getIntrinsicID() != Intrinsic::lifetime_end)
3236 return false;
3237 }
3238 return true;
3239}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003240
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003241bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3242 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003243 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003244 const Operator *Inst = dyn_cast<Operator>(V);
3245 if (!Inst)
3246 return false;
3247
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003248 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3249 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3250 if (C->canTrap())
3251 return false;
3252
3253 switch (Inst->getOpcode()) {
3254 default:
3255 return true;
3256 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003257 case Instruction::URem: {
3258 // x / y is undefined if y == 0.
3259 const APInt *V;
3260 if (match(Inst->getOperand(1), m_APInt(V)))
3261 return *V != 0;
3262 return false;
3263 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003264 case Instruction::SDiv:
3265 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003266 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003267 const APInt *Numerator, *Denominator;
3268 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3269 return false;
3270 // We cannot hoist this division if the denominator is 0.
3271 if (*Denominator == 0)
3272 return false;
3273 // It's safe to hoist if the denominator is not 0 or -1.
3274 if (*Denominator != -1)
3275 return true;
3276 // At this point we know that the denominator is -1. It is safe to hoist as
3277 // long we know that the numerator is not INT_MIN.
3278 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3279 return !Numerator->isMinSignedValue();
3280 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003281 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003282 }
3283 case Instruction::Load: {
3284 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003285 if (!LI->isUnordered() ||
3286 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003287 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003288 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003289 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003290 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003291 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003292 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3293 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003294 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003295 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003296 auto *CI = cast<const CallInst>(Inst);
3297 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003298
Matt Arsenault6a288c12017-05-03 02:26:10 +00003299 // The called function could have undefined behavior or side-effects, even
3300 // if marked readnone nounwind.
3301 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003302 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003303 case Instruction::VAArg:
3304 case Instruction::Alloca:
3305 case Instruction::Invoke:
3306 case Instruction::PHI:
3307 case Instruction::Store:
3308 case Instruction::Ret:
3309 case Instruction::Br:
3310 case Instruction::IndirectBr:
3311 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003312 case Instruction::Unreachable:
3313 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003314 case Instruction::AtomicRMW:
3315 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003316 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003317 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003318 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003319 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003320 case Instruction::CatchRet:
3321 case Instruction::CleanupPad:
3322 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003323 return false; // Misc instructions which have effects
3324 }
3325}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003326
Quentin Colombet6443cce2015-08-06 18:44:34 +00003327bool llvm::mayBeMemoryDependent(const Instruction &I) {
3328 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3329}
3330
Sanjay Patelaee84212014-11-04 16:27:42 +00003331/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003332bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003333 assert(V->getType()->isPointerTy() && "V must be pointer type");
3334
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003335 // Alloca never returns null, malloc might.
3336 if (isa<AllocaInst>(V)) return true;
3337
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003338 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003339 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003340 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003341
Peter Collingbourne235c2752016-12-08 19:01:00 +00003342 // A global variable in address space 0 is non null unless extern weak
3343 // or an absolute symbol reference. Other address spaces may have null as a
3344 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003345 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003346 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003347 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003348
Sanjoy Das5056e192016-05-07 02:08:22 +00003349 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003350 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003351 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003352
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003353 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003354 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003355 return true;
3356
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003357 return false;
3358}
David Majnemer491331a2015-01-02 07:29:43 +00003359
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003360static bool isKnownNonNullFromDominatingCondition(const Value *V,
3361 const Instruction *CtxI,
3362 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003363 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003364 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003365 assert(CtxI && "Context instruction required for analysis");
3366 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003367
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003368 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003369 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003370 // Avoid massive lists
3371 if (NumUsesExplored >= DomConditionsMaxUses)
3372 break;
3373 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003374
3375 // If the value is used as an argument to a call or invoke, then argument
3376 // attributes may provide an answer about null-ness.
3377 if (auto CS = ImmutableCallSite(U))
3378 if (auto *CalledFunc = CS.getCalledFunction())
3379 for (const Argument &Arg : CalledFunc->args())
3380 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3381 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3382 return true;
3383
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003384 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003385 CmpInst::Predicate Pred;
3386 if (!match(const_cast<User *>(U),
3387 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3388 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003389 continue;
3390
Sanjoy Das987aaa12016-05-07 02:08:24 +00003391 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003392 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3393 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003394
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003395 BasicBlock *NonNullSuccessor =
3396 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3397 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3398 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3399 return true;
3400 } else if (Pred == ICmpInst::ICMP_NE &&
3401 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3402 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003403 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003404 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003405 }
3406 }
3407
3408 return false;
3409}
3410
3411bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003412 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003413 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3414 return false;
3415
Sean Silva45835e72016-07-02 23:47:27 +00003416 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003417 return true;
3418
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003419 if (!CtxI || !DT)
3420 return false;
3421
3422 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003423}
3424
Pete Cooper35b00d52016-08-13 01:05:32 +00003425OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3426 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003427 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003428 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003429 const Instruction *CxtI,
3430 const DominatorTree *DT) {
3431 // Multiplying n * m significant bits yields a result of n + m significant
3432 // bits. If the total number of significant bits does not exceed the
3433 // result bit width (minus 1), there is no overflow.
3434 // This means if we have enough leading zero bits in the operands
3435 // we can guarantee that the result does not overflow.
3436 // Ref: "Hacker's Delight" by Henry Warren
3437 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003438 KnownBits LHSKnown(BitWidth);
3439 KnownBits RHSKnown(BitWidth);
3440 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3441 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003442 // Note that underestimating the number of zero bits gives a more
3443 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003444 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3445 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003446 // First handle the easy case: if we have enough zero bits there's
3447 // definitely no overflow.
3448 if (ZeroBits >= BitWidth)
3449 return OverflowResult::NeverOverflows;
3450
3451 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003452 APInt LHSMax = ~LHSKnown.Zero;
3453 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003454
3455 // We know the multiply operation doesn't overflow if the maximum values for
3456 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003457 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003458 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003459 if (!MaxOverflow)
3460 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003461
David Majnemerc8a576b2015-01-02 07:29:47 +00003462 // We know it always overflows if multiplying the smallest possible values for
3463 // the operands also results in overflow.
3464 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003465 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003466 if (MinOverflow)
3467 return OverflowResult::AlwaysOverflows;
3468
3469 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003470}
David Majnemer5310c1e2015-01-07 00:39:50 +00003471
Pete Cooper35b00d52016-08-13 01:05:32 +00003472OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3473 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003474 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003475 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003476 const Instruction *CxtI,
3477 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003478 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3479 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3480 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003481
Craig Topper6e11a052017-05-08 16:22:48 +00003482 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003483 // The sign bit is set in both cases: this MUST overflow.
3484 // Create a simple add instruction, and insert it into the struct.
3485 return OverflowResult::AlwaysOverflows;
3486 }
3487
Craig Topper6e11a052017-05-08 16:22:48 +00003488 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003489 // The sign bit is clear in both cases: this CANNOT overflow.
3490 // Create a simple add instruction, and insert it into the struct.
3491 return OverflowResult::NeverOverflows;
3492 }
3493 }
3494
3495 return OverflowResult::MayOverflow;
3496}
James Molloy71b91c22015-05-11 14:42:20 +00003497
Pete Cooper35b00d52016-08-13 01:05:32 +00003498static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3499 const Value *RHS,
3500 const AddOperator *Add,
3501 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003502 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003503 const Instruction *CxtI,
3504 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003505 if (Add && Add->hasNoSignedWrap()) {
3506 return OverflowResult::NeverOverflows;
3507 }
3508
Craig Topper6e11a052017-05-08 16:22:48 +00003509 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3510 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003511
Craig Topper6e11a052017-05-08 16:22:48 +00003512 if ((LHSKnown.isNonNegative() && RHSKnown.isNegative()) ||
3513 (LHSKnown.isNegative() && RHSKnown.isNonNegative())) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003514 // The sign bits are opposite: this CANNOT overflow.
3515 return OverflowResult::NeverOverflows;
3516 }
3517
3518 // The remaining code needs Add to be available. Early returns if not so.
3519 if (!Add)
3520 return OverflowResult::MayOverflow;
3521
3522 // If the sign of Add is the same as at least one of the operands, this add
3523 // CANNOT overflow. This is particularly useful when the sum is
3524 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3525 // operands.
3526 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003527 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
3528 bool LHSOrRHSKnownNegative = (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003529 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003530 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3531 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3532 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003533 return OverflowResult::NeverOverflows;
3534 }
3535 }
3536
3537 return OverflowResult::MayOverflow;
3538}
3539
Pete Cooper35b00d52016-08-13 01:05:32 +00003540bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3541 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003542#ifndef NDEBUG
3543 auto IID = II->getIntrinsicID();
3544 assert((IID == Intrinsic::sadd_with_overflow ||
3545 IID == Intrinsic::uadd_with_overflow ||
3546 IID == Intrinsic::ssub_with_overflow ||
3547 IID == Intrinsic::usub_with_overflow ||
3548 IID == Intrinsic::smul_with_overflow ||
3549 IID == Intrinsic::umul_with_overflow) &&
3550 "Not an overflow intrinsic!");
3551#endif
3552
Pete Cooper35b00d52016-08-13 01:05:32 +00003553 SmallVector<const BranchInst *, 2> GuardingBranches;
3554 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003555
Pete Cooper35b00d52016-08-13 01:05:32 +00003556 for (const User *U : II->users()) {
3557 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003558 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3559
3560 if (EVI->getIndices()[0] == 0)
3561 Results.push_back(EVI);
3562 else {
3563 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3564
Pete Cooper35b00d52016-08-13 01:05:32 +00003565 for (const auto *U : EVI->users())
3566 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003567 assert(B->isConditional() && "How else is it using an i1?");
3568 GuardingBranches.push_back(B);
3569 }
3570 }
3571 } else {
3572 // We are using the aggregate directly in a way we don't want to analyze
3573 // here (storing it to a global, say).
3574 return false;
3575 }
3576 }
3577
Pete Cooper35b00d52016-08-13 01:05:32 +00003578 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003579 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3580 if (!NoWrapEdge.isSingleEdge())
3581 return false;
3582
3583 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003584 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003585 // If the extractvalue itself is not executed on overflow, the we don't
3586 // need to check each use separately, since domination is transitive.
3587 if (DT.dominates(NoWrapEdge, Result->getParent()))
3588 continue;
3589
3590 for (auto &RU : Result->uses())
3591 if (!DT.dominates(NoWrapEdge, RU))
3592 return false;
3593 }
3594
3595 return true;
3596 };
3597
3598 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3599}
3600
3601
Pete Cooper35b00d52016-08-13 01:05:32 +00003602OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003603 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003604 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003605 const Instruction *CxtI,
3606 const DominatorTree *DT) {
3607 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003608 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003609}
3610
Pete Cooper35b00d52016-08-13 01:05:32 +00003611OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3612 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003613 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003614 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003615 const Instruction *CxtI,
3616 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003617 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003618}
3619
Jingyue Wu42f1d672015-07-28 18:22:40 +00003620bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003621 // A memory operation returns normally if it isn't volatile. A volatile
3622 // operation is allowed to trap.
3623 //
3624 // An atomic operation isn't guaranteed to return in a reasonable amount of
3625 // time because it's possible for another thread to interfere with it for an
3626 // arbitrary length of time, but programs aren't allowed to rely on that.
3627 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3628 return !LI->isVolatile();
3629 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3630 return !SI->isVolatile();
3631 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3632 return !CXI->isVolatile();
3633 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3634 return !RMWI->isVolatile();
3635 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3636 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003637
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003638 // If there is no successor, then execution can't transfer to it.
3639 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3640 return !CRI->unwindsToCaller();
3641 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3642 return !CatchSwitch->unwindsToCaller();
3643 if (isa<ResumeInst>(I))
3644 return false;
3645 if (isa<ReturnInst>(I))
3646 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003647 if (isa<UnreachableInst>(I))
3648 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003649
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003650 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003651 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003652 // Call sites that throw have implicit non-local control flow.
3653 if (!CS.doesNotThrow())
3654 return false;
3655
3656 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3657 // etc. and thus not return. However, LLVM already assumes that
3658 //
3659 // - Thread exiting actions are modeled as writes to memory invisible to
3660 // the program.
3661 //
3662 // - Loops that don't have side effects (side effects are volatile/atomic
3663 // stores and IO) always terminate (see http://llvm.org/PR965).
3664 // Furthermore IO itself is also modeled as writes to memory invisible to
3665 // the program.
3666 //
3667 // We rely on those assumptions here, and use the memory effects of the call
3668 // target as a proxy for checking that it always returns.
3669
3670 // FIXME: This isn't aggressive enough; a call which only writes to a global
3671 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003672 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3673 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003674 }
3675
3676 // Other instructions return normally.
3677 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003678}
3679
3680bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3681 const Loop *L) {
3682 // The loop header is guaranteed to be executed for every iteration.
3683 //
3684 // FIXME: Relax this constraint to cover all basic blocks that are
3685 // guaranteed to be executed at every iteration.
3686 if (I->getParent() != L->getHeader()) return false;
3687
3688 for (const Instruction &LI : *L->getHeader()) {
3689 if (&LI == I) return true;
3690 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3691 }
3692 llvm_unreachable("Instruction not contained in its own parent basic block.");
3693}
3694
3695bool llvm::propagatesFullPoison(const Instruction *I) {
3696 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003697 case Instruction::Add:
3698 case Instruction::Sub:
3699 case Instruction::Xor:
3700 case Instruction::Trunc:
3701 case Instruction::BitCast:
3702 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003703 case Instruction::Mul:
3704 case Instruction::Shl:
3705 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003706 // These operations all propagate poison unconditionally. Note that poison
3707 // is not any particular value, so xor or subtraction of poison with
3708 // itself still yields poison, not zero.
3709 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003710
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003711 case Instruction::AShr:
3712 case Instruction::SExt:
3713 // For these operations, one bit of the input is replicated across
3714 // multiple output bits. A replicated poison bit is still poison.
3715 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003716
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003717 case Instruction::ICmp:
3718 // Comparing poison with any value yields poison. This is why, for
3719 // instance, x s< (x +nsw 1) can be folded to true.
3720 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003721
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003722 default:
3723 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003724 }
3725}
3726
3727const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3728 switch (I->getOpcode()) {
3729 case Instruction::Store:
3730 return cast<StoreInst>(I)->getPointerOperand();
3731
3732 case Instruction::Load:
3733 return cast<LoadInst>(I)->getPointerOperand();
3734
3735 case Instruction::AtomicCmpXchg:
3736 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3737
3738 case Instruction::AtomicRMW:
3739 return cast<AtomicRMWInst>(I)->getPointerOperand();
3740
3741 case Instruction::UDiv:
3742 case Instruction::SDiv:
3743 case Instruction::URem:
3744 case Instruction::SRem:
3745 return I->getOperand(1);
3746
3747 default:
3748 return nullptr;
3749 }
3750}
3751
Sanjoy Das08989c72017-04-30 19:41:19 +00003752bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003753 // We currently only look for uses of poison values within the same basic
3754 // block, as that makes it easier to guarantee that the uses will be
3755 // executed given that PoisonI is executed.
3756 //
3757 // FIXME: Expand this to consider uses beyond the same basic block. To do
3758 // this, look out for the distinction between post-dominance and strong
3759 // post-dominance.
3760 const BasicBlock *BB = PoisonI->getParent();
3761
3762 // Set of instructions that we have proved will yield poison if PoisonI
3763 // does.
3764 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003765 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003766 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003767 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003768
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003769 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003770
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003771 unsigned Iter = 0;
3772 while (Iter++ < MaxDepth) {
3773 for (auto &I : make_range(Begin, End)) {
3774 if (&I != PoisonI) {
3775 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3776 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3777 return true;
3778 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3779 return false;
3780 }
3781
3782 // Mark poison that propagates from I through uses of I.
3783 if (YieldsPoison.count(&I)) {
3784 for (const User *User : I.users()) {
3785 const Instruction *UserI = cast<Instruction>(User);
3786 if (propagatesFullPoison(UserI))
3787 YieldsPoison.insert(User);
3788 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003789 }
3790 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003791
3792 if (auto *NextBB = BB->getSingleSuccessor()) {
3793 if (Visited.insert(NextBB).second) {
3794 BB = NextBB;
3795 Begin = BB->getFirstNonPHI()->getIterator();
3796 End = BB->end();
3797 continue;
3798 }
3799 }
3800
3801 break;
3802 };
Jingyue Wu42f1d672015-07-28 18:22:40 +00003803 return false;
3804}
3805
Pete Cooper35b00d52016-08-13 01:05:32 +00003806static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003807 if (FMF.noNaNs())
3808 return true;
3809
3810 if (auto *C = dyn_cast<ConstantFP>(V))
3811 return !C->isNaN();
3812 return false;
3813}
3814
Pete Cooper35b00d52016-08-13 01:05:32 +00003815static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003816 if (auto *C = dyn_cast<ConstantFP>(V))
3817 return !C->isZero();
3818 return false;
3819}
3820
Sanjay Patel819f0962016-11-13 19:30:19 +00003821/// Match non-obvious integer minimum and maximum sequences.
3822static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
3823 Value *CmpLHS, Value *CmpRHS,
3824 Value *TrueVal, Value *FalseVal,
3825 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00003826 // Assume success. If there's no match, callers should not use these anyway.
3827 LHS = TrueVal;
3828 RHS = FalseVal;
3829
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003830 // Recognize variations of:
3831 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
3832 const APInt *C1;
3833 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
3834 const APInt *C2;
3835
3836 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
3837 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003838 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003839 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003840
3841 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
3842 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003843 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003844 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003845
3846 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
3847 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003848 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003849 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003850
3851 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
3852 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003853 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003854 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003855 }
3856
Sanjay Patel819f0962016-11-13 19:30:19 +00003857 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
3858 return {SPF_UNKNOWN, SPNB_NA, false};
3859
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003860 // Z = X -nsw Y
3861 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
3862 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
3863 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003864 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003865 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003866
3867 // Z = X -nsw Y
3868 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
3869 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
3870 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003871 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003872 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003873
Sanjay Patel819f0962016-11-13 19:30:19 +00003874 if (!match(CmpRHS, m_APInt(C1)))
3875 return {SPF_UNKNOWN, SPNB_NA, false};
3876
3877 // An unsigned min/max can be written with a signed compare.
3878 const APInt *C2;
3879 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
3880 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
3881 // Is the sign bit set?
3882 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
3883 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00003884 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003885 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003886
3887 // Is the sign bit clear?
3888 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
3889 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
3890 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003891 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003892 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003893 }
3894
3895 // Look through 'not' ops to find disguised signed min/max.
3896 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
3897 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
3898 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003899 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003900 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003901
3902 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
3903 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
3904 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003905 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003906 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003907
3908 return {SPF_UNKNOWN, SPNB_NA, false};
3909}
3910
James Molloy134bec22015-08-11 09:12:57 +00003911static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3912 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00003913 Value *CmpLHS, Value *CmpRHS,
3914 Value *TrueVal, Value *FalseVal,
3915 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003916 LHS = CmpLHS;
3917 RHS = CmpRHS;
3918
James Molloy134bec22015-08-11 09:12:57 +00003919 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
3920 // return inconsistent results between implementations.
3921 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3922 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3923 // Therefore we behave conservatively and only proceed if at least one of the
3924 // operands is known to not be zero, or if we don't care about signed zeroes.
3925 switch (Pred) {
3926 default: break;
3927 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3928 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3929 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3930 !isKnownNonZero(CmpRHS))
3931 return {SPF_UNKNOWN, SPNB_NA, false};
3932 }
3933
3934 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3935 bool Ordered = false;
3936
3937 // When given one NaN and one non-NaN input:
3938 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3939 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3940 // ordered comparison fails), which could be NaN or non-NaN.
3941 // so here we discover exactly what NaN behavior is required/accepted.
3942 if (CmpInst::isFPPredicate(Pred)) {
3943 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3944 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3945
3946 if (LHSSafe && RHSSafe) {
3947 // Both operands are known non-NaN.
3948 NaNBehavior = SPNB_RETURNS_ANY;
3949 } else if (CmpInst::isOrdered(Pred)) {
3950 // An ordered comparison will return false when given a NaN, so it
3951 // returns the RHS.
3952 Ordered = true;
3953 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00003954 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00003955 NaNBehavior = SPNB_RETURNS_NAN;
3956 else if (RHSSafe)
3957 NaNBehavior = SPNB_RETURNS_OTHER;
3958 else
3959 // Completely unsafe.
3960 return {SPF_UNKNOWN, SPNB_NA, false};
3961 } else {
3962 Ordered = false;
3963 // An unordered comparison will return true when given a NaN, so it
3964 // returns the LHS.
3965 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00003966 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00003967 NaNBehavior = SPNB_RETURNS_OTHER;
3968 else if (RHSSafe)
3969 NaNBehavior = SPNB_RETURNS_NAN;
3970 else
3971 // Completely unsafe.
3972 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003973 }
3974 }
3975
James Molloy71b91c22015-05-11 14:42:20 +00003976 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00003977 std::swap(CmpLHS, CmpRHS);
3978 Pred = CmpInst::getSwappedPredicate(Pred);
3979 if (NaNBehavior == SPNB_RETURNS_NAN)
3980 NaNBehavior = SPNB_RETURNS_OTHER;
3981 else if (NaNBehavior == SPNB_RETURNS_OTHER)
3982 NaNBehavior = SPNB_RETURNS_NAN;
3983 Ordered = !Ordered;
3984 }
3985
3986 // ([if]cmp X, Y) ? X : Y
3987 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003988 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00003989 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00003990 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00003991 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003992 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00003993 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003994 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00003995 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00003996 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00003997 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
3998 case FCmpInst::FCMP_UGT:
3999 case FCmpInst::FCMP_UGE:
4000 case FCmpInst::FCMP_OGT:
4001 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4002 case FCmpInst::FCMP_ULT:
4003 case FCmpInst::FCMP_ULE:
4004 case FCmpInst::FCMP_OLT:
4005 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004006 }
4007 }
4008
Sanjay Patele372aec2016-10-27 15:26:10 +00004009 const APInt *C1;
4010 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004011 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4012 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4013
4014 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4015 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004016 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004017 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004018 }
4019
4020 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4021 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004022 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004023 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004024 }
4025 }
James Molloy71b91c22015-05-11 14:42:20 +00004026 }
4027
Sanjay Patel819f0962016-11-13 19:30:19 +00004028 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004029}
James Molloy270ef8c2015-05-15 16:04:50 +00004030
James Molloy569cea62015-09-02 17:25:25 +00004031static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4032 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004033 auto *Cast1 = dyn_cast<CastInst>(V1);
4034 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004035 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004036
Sanjay Patel14a4b812017-01-29 16:34:57 +00004037 *CastOp = Cast1->getOpcode();
4038 Type *SrcTy = Cast1->getSrcTy();
4039 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4040 // If V1 and V2 are both the same cast from the same type, look through V1.
4041 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4042 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004043 return nullptr;
4044 }
4045
Sanjay Patel14a4b812017-01-29 16:34:57 +00004046 auto *C = dyn_cast<Constant>(V2);
4047 if (!C)
4048 return nullptr;
4049
David Majnemerd2a074b2016-04-29 18:40:34 +00004050 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004051 switch (*CastOp) {
4052 case Instruction::ZExt:
4053 if (CmpI->isUnsigned())
4054 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4055 break;
4056 case Instruction::SExt:
4057 if (CmpI->isSigned())
4058 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4059 break;
4060 case Instruction::Trunc:
4061 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4062 break;
4063 case Instruction::FPTrunc:
4064 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4065 break;
4066 case Instruction::FPExt:
4067 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4068 break;
4069 case Instruction::FPToUI:
4070 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4071 break;
4072 case Instruction::FPToSI:
4073 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4074 break;
4075 case Instruction::UIToFP:
4076 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4077 break;
4078 case Instruction::SIToFP:
4079 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4080 break;
4081 default:
4082 break;
4083 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004084
4085 if (!CastedTo)
4086 return nullptr;
4087
David Majnemerd2a074b2016-04-29 18:40:34 +00004088 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004089 Constant *CastedBack =
4090 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004091 if (CastedBack != C)
4092 return nullptr;
4093
4094 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004095}
4096
Sanjay Patele8dc0902016-05-23 17:57:54 +00004097SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004098 Instruction::CastOps *CastOp) {
4099 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004100 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004101
James Molloy134bec22015-08-11 09:12:57 +00004102 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4103 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004104
James Molloy134bec22015-08-11 09:12:57 +00004105 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004106 Value *CmpLHS = CmpI->getOperand(0);
4107 Value *CmpRHS = CmpI->getOperand(1);
4108 Value *TrueVal = SI->getTrueValue();
4109 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004110 FastMathFlags FMF;
4111 if (isa<FPMathOperator>(CmpI))
4112 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004113
4114 // Bail out early.
4115 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004116 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004117
4118 // Deal with type mismatches.
4119 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004120 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004121 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004122 cast<CastInst>(TrueVal)->getOperand(0), C,
4123 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004124 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004125 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004126 C, cast<CastInst>(FalseVal)->getOperand(0),
4127 LHS, RHS);
4128 }
James Molloy134bec22015-08-11 09:12:57 +00004129 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004130 LHS, RHS);
4131}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004132
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004133/// Return true if "icmp Pred LHS RHS" is always true.
Pete Cooper35b00d52016-08-13 01:05:32 +00004134static bool isTruePredicate(CmpInst::Predicate Pred,
4135 const Value *LHS, const Value *RHS,
Sanjoy Das55ea67c2015-11-06 19:01:08 +00004136 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004137 AssumptionCache *AC, const Instruction *CxtI,
4138 const DominatorTree *DT) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004139 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004140 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4141 return true;
4142
4143 switch (Pred) {
4144 default:
4145 return false;
4146
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004147 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004148 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004149
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004150 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004151 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004152 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004153 return false;
4154 }
4155
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004156 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004157 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004158
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004159 // LHS u<= LHS +_{nuw} C for any C
4160 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004161 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004162
4163 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004164 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4165 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004166 const APInt *&CA, const APInt *&CB) {
4167 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4168 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4169 return true;
4170
4171 // If X & C == 0 then (X | C) == X +_{nuw} C
4172 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4173 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004174 KnownBits Known(CA->getBitWidth());
4175 computeKnownBits(X, Known, DL, Depth + 1, AC, CxtI, DT);
Sanjoy Das92568102015-11-10 23:56:20 +00004176
Craig Topperb45eabc2017-04-26 16:39:58 +00004177 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004178 return true;
4179 }
4180
4181 return false;
4182 };
4183
Pete Cooper35b00d52016-08-13 01:05:32 +00004184 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004185 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004186 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4187 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004188
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004189 return false;
4190 }
4191 }
4192}
4193
4194/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004195/// ALHS ARHS" is true. Otherwise, return None.
4196static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004197isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4198 const Value *ARHS, const Value *BLHS,
4199 const Value *BRHS, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004200 unsigned Depth, AssumptionCache *AC,
4201 const Instruction *CxtI, const DominatorTree *DT) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004202 switch (Pred) {
4203 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004204 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004205
4206 case CmpInst::ICMP_SLT:
4207 case CmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004208 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004209 DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004210 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004211 return true;
4212 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004213
4214 case CmpInst::ICMP_ULT:
4215 case CmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004216 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
4217 DT) &&
4218 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004219 return true;
4220 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004221 }
4222}
4223
Chad Rosier226a7342016-05-05 17:41:19 +00004224/// Return true if the operands of the two compares match. IsSwappedOps is true
4225/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004226static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4227 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004228 bool &IsSwappedOps) {
4229
4230 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4231 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4232 return IsMatchingOps || IsSwappedOps;
4233}
4234
Chad Rosier41dd31f2016-04-20 19:15:26 +00004235/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4236/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4237/// BRHS" is false. Otherwise, return None if we can't infer anything.
4238static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004239 const Value *ALHS,
4240 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004241 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004242 const Value *BLHS,
4243 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004244 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004245 // Canonicalize the operands so they're matching.
4246 if (IsSwappedOps) {
4247 std::swap(BLHS, BRHS);
4248 BPred = ICmpInst::getSwappedPredicate(BPred);
4249 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004250 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004251 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004252 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004253 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004254
Chad Rosier41dd31f2016-04-20 19:15:26 +00004255 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004256}
4257
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004258/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4259/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4260/// C2" is false. Otherwise, return None if we can't infer anything.
4261static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004262isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4263 const ConstantInt *C1,
4264 CmpInst::Predicate BPred,
4265 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004266 assert(ALHS == BLHS && "LHS operands must match.");
4267 ConstantRange DomCR =
4268 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4269 ConstantRange CR =
4270 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4271 ConstantRange Intersection = DomCR.intersectWith(CR);
4272 ConstantRange Difference = DomCR.difference(CR);
4273 if (Intersection.isEmptySet())
4274 return false;
4275 if (Difference.isEmptySet())
4276 return true;
4277 return None;
4278}
4279
Pete Cooper35b00d52016-08-13 01:05:32 +00004280Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosiere2cbd132016-04-25 17:23:36 +00004281 const DataLayout &DL, bool InvertAPred,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004282 unsigned Depth, AssumptionCache *AC,
4283 const Instruction *CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004284 const DominatorTree *DT) {
Chad Rosiercd62bf52016-04-29 21:12:31 +00004285 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example.
4286 if (LHS->getType() != RHS->getType())
4287 return None;
4288
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004289 Type *OpTy = LHS->getType();
4290 assert(OpTy->getScalarType()->isIntegerTy(1));
4291
4292 // LHS ==> RHS by definition
Chad Rosiere2cbd132016-04-25 17:23:36 +00004293 if (!InvertAPred && LHS == RHS)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004294 return true;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004295
4296 if (OpTy->isVectorTy())
4297 // TODO: extending the code below to handle vectors
Chad Rosier41dd31f2016-04-20 19:15:26 +00004298 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004299 assert(OpTy->isIntegerTy(1) && "implied by above");
4300
4301 ICmpInst::Predicate APred, BPred;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004302 Value *ALHS, *ARHS;
4303 Value *BLHS, *BRHS;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004304
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004305 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
4306 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004307 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004308
Chad Rosiere2cbd132016-04-25 17:23:36 +00004309 if (InvertAPred)
4310 APred = CmpInst::getInversePredicate(APred);
4311
Chad Rosier226a7342016-05-05 17:41:19 +00004312 // Can we infer anything when the two compares have matching operands?
4313 bool IsSwappedOps;
4314 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4315 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4316 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004317 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004318 // No amount of additional analysis will infer the second condition, so
4319 // early exit.
4320 return None;
4321 }
4322
4323 // Can we infer anything when the LHS operands match and the RHS operands are
4324 // constants (not necessarily matching)?
4325 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4326 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4327 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4328 cast<ConstantInt>(BRHS)))
4329 return Implication;
4330 // No amount of additional analysis will infer the second condition, so
4331 // early exit.
4332 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004333 }
4334
Chad Rosier41dd31f2016-04-20 19:15:26 +00004335 if (APred == BPred)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004336 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
4337 CxtI, DT);
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004338
Chad Rosier41dd31f2016-04-20 19:15:26 +00004339 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004340}