blob: 54828e392d4aa1f11ee89e72b6e8cd580fa890b9 [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"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
James Molloy493e57d2015-10-26 14:10:46 +000020#include "llvm/ADT/Optional.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000023#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000028#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000029#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000030#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000031#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000032#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000037#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000038#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000039#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000042#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000046#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/Type.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000067#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000068#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000069#include <algorithm>
70#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000071#include <cassert>
72#include <cstdint>
73#include <iterator>
74#include <utility>
75
Chris Lattner965c7692008-06-02 01:18:21 +000076using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000077using namespace llvm::PatternMatch;
78
79const unsigned MaxDepth = 6;
80
Philip Reames1c292272015-03-10 22:43:20 +000081// Controls the number of uses of the value searched for possible
82// dominating comparisons.
83static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000084 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000085
Craig Topper6b3940a2017-05-03 22:25:19 +000086/// Returns the bitwidth of the given scalar or pointer type. For vector types,
87/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000089 if (unsigned BitWidth = Ty->getScalarSizeInBits())
90 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000091
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000092 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000093}
Chris Lattner965c7692008-06-02 01:18:21 +000094
Benjamin Kramercfd8d902014-09-12 08:56:53 +000095namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000096
Hal Finkel60db0582014-09-07 18:57:58 +000097// Simplifying using an assume can only be done in a particular control-flow
98// context (the context instruction provides that context). If an assume and
99// the context instruction are not in the same block then the DT helps in
100// figuring out if we can use it.
101struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000102 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000103 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000104 const Instruction *CxtI;
105 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000106
Sanjay Patel54656ca2017-02-06 18:26:06 +0000107 // Unlike the other analyses, this may be a nullptr because not all clients
108 // provide it currently.
109 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000110
Matthias Braun37e5d792016-01-28 06:29:33 +0000111 /// Set of assumptions that should be excluded from further queries.
112 /// This is because of the potential for mutual recursion to cause
113 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
114 /// classic case of this is assume(x = y), which will attempt to determine
115 /// bits in x from bits in y, which will attempt to determine bits in y from
116 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000117 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
118 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000119 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000120
121 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000122
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000123 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000124 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000125 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000126
127 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000128 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
129 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000130 Excluded = Q.Excluded;
131 Excluded[NumExcluded++] = NewExcl;
132 assert(NumExcluded <= Excluded.size());
133 }
134
135 bool isExcluded(const Value *Value) const {
136 if (NumExcluded == 0)
137 return false;
138 auto End = Excluded.begin() + NumExcluded;
139 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000140 }
141};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000142
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000143} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000144
Sanjay Patel547e9752014-11-04 16:09:50 +0000145// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000146// the preferred context instruction (if any).
147static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
148 // If we've been provided with a context instruction, then use that (provided
149 // it has been inserted).
150 if (CxtI && CxtI->getParent())
151 return CxtI;
152
153 // If the value is really an already-inserted instruction, then use that.
154 CxtI = dyn_cast<Instruction>(V);
155 if (CxtI && CxtI->getParent())
156 return CxtI;
157
158 return nullptr;
159}
160
Craig Topperb45eabc2017-04-26 16:39:58 +0000161static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000162 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000163
Craig Topperb45eabc2017-04-26 16:39:58 +0000164void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000165 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000166 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000167 const DominatorTree *DT,
168 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000169 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000170 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000171}
172
Craig Topper6e11a052017-05-08 16:22:48 +0000173static KnownBits computeKnownBits(const Value *V, unsigned Depth,
174 const Query &Q);
175
176KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
177 unsigned Depth, AssumptionCache *AC,
178 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000179 const DominatorTree *DT,
180 OptimizationRemarkEmitter *ORE) {
181 return ::computeKnownBits(V, Depth,
182 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000183}
184
Pete Cooper35b00d52016-08-13 01:05:32 +0000185bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
186 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000187 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000188 const DominatorTree *DT) {
189 assert(LHS->getType() == RHS->getType() &&
190 "LHS and RHS should have the same type");
191 assert(LHS->getType()->isIntOrIntVectorTy() &&
192 "LHS and RHS should be integers");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000193 // Look for an inverted mask: (X & ~M) op (Y & M).
194 Value *M;
195 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
196 match(RHS, m_c_And(m_Specific(M), m_Value())))
197 return true;
198 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
199 match(LHS, m_c_And(m_Specific(M), m_Value())))
200 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000201 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000202 KnownBits LHSKnown(IT->getBitWidth());
203 KnownBits RHSKnown(IT->getBitWidth());
204 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
205 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
206 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000207}
208
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000209bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
210 for (const User *U : CxtI->users()) {
211 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
212 if (IC->isEquality())
213 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
214 if (C->isNullValue())
215 continue;
216 return false;
217 }
218 return true;
219}
220
Pete Cooper35b00d52016-08-13 01:05:32 +0000221static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000222 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000223
Pete Cooper35b00d52016-08-13 01:05:32 +0000224bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
225 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000226 unsigned Depth, AssumptionCache *AC,
227 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000228 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000230 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231}
232
Pete Cooper35b00d52016-08-13 01:05:32 +0000233static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000234
Pete Cooper35b00d52016-08-13 01:05:32 +0000235bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000236 AssumptionCache *AC, const Instruction *CxtI,
237 const DominatorTree *DT) {
238 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239}
240
Pete Cooper35b00d52016-08-13 01:05:32 +0000241bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000242 unsigned Depth,
243 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000244 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000245 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
246 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000247}
248
Pete Cooper35b00d52016-08-13 01:05:32 +0000249bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000250 AssumptionCache *AC, const Instruction *CxtI,
251 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000252 if (auto *CI = dyn_cast<ConstantInt>(V))
253 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000254
Philip Reames8f12eba2016-03-09 21:31:47 +0000255 // TODO: We'd doing two recursive queries here. We should factor this such
256 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000257 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
258 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000259}
260
Pete Cooper35b00d52016-08-13 01:05:32 +0000261bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000262 AssumptionCache *AC, const Instruction *CxtI,
263 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000264 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
265 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000266}
267
Pete Cooper35b00d52016-08-13 01:05:32 +0000268static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000269
Pete Cooper35b00d52016-08-13 01:05:32 +0000270bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000271 const DataLayout &DL,
272 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000273 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000274 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
275 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000276 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000277}
278
Pete Cooper35b00d52016-08-13 01:05:32 +0000279static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000280 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000281
Pete Cooper35b00d52016-08-13 01:05:32 +0000282bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
283 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000284 unsigned Depth, AssumptionCache *AC,
285 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000286 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000287 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288}
289
Pete Cooper35b00d52016-08-13 01:05:32 +0000290static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
291 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000292
Pete Cooper35b00d52016-08-13 01:05:32 +0000293unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000294 unsigned Depth, AssumptionCache *AC,
295 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000297 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000298}
299
Craig Topper8fbb74b2017-03-24 22:12:10 +0000300static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
301 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000302 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000303 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000304 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000305
306 // If an initial sequence of bits in the result is not needed, the
307 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000308 KnownBits LHSKnown(BitWidth);
309 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
310 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000311
Craig Topperb498a232017-08-08 16:29:35 +0000312 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000313}
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
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000347 assert(!Known.hasConflict() && !Known2.hasConflict());
348 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000349 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
350 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000351 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000352 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000353
354 // The result of the bottom bits of an integer multiply can be
355 // inferred by looking at the bottom bits of both operands and
356 // multiplying them together.
357 // We can infer at least the minimum number of known trailing bits
358 // of both operands. Depending on number of trailing zeros, we can
359 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
360 // a and b are divisible by m and n respectively.
361 // We then calculate how many of those bits are inferrable and set
362 // the output. For example, the i8 mul:
363 // a = XXXX1100 (12)
364 // b = XXXX1110 (14)
365 // We know the bottom 3 bits are zero since the first can be divided by
366 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
367 // Applying the multiplication to the trimmed arguments gets:
368 // XX11 (3)
369 // X111 (7)
370 // -------
371 // XX11
372 // XX11
373 // XX11
374 // XX11
375 // -------
376 // XXXXX01
377 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
378 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
379 // The proof for this can be described as:
380 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
381 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
382 // umin(countTrailingZeros(C2), C6) +
383 // umin(C5 - umin(countTrailingZeros(C1), C5),
384 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
385 // %aa = shl i8 %a, C5
386 // %bb = shl i8 %b, C6
387 // %aaa = or i8 %aa, C1
388 // %bbb = or i8 %bb, C2
389 // %mul = mul i8 %aaa, %bbb
390 // %mask = and i8 %mul, C7
391 // =>
392 // %mask = i8 ((C1*C2)&C7)
393 // Where C5, C6 describe the known bits of %a, %b
394 // C1, C2 describe the known bottom bits of %a, %b.
395 // C7 describes the mask of the known bits of the result.
396 APInt Bottom0 = Known.One;
397 APInt Bottom1 = Known2.One;
398
399 // How many times we'd be able to divide each argument by 2 (shr by 1).
400 // This gives us the number of trailing zeros on the multiplication result.
401 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
402 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
403 unsigned TrailZero0 = Known.countMinTrailingZeros();
404 unsigned TrailZero1 = Known2.countMinTrailingZeros();
405 unsigned TrailZ = TrailZero0 + TrailZero1;
406
407 // Figure out the fewest known-bits operand.
408 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
409 TrailBitsKnown1 - TrailZero1);
410 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
411
412 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
413 Bottom1.getLoBits(TrailBitsKnown1);
414
Craig Topperf0aeee02017-05-05 17:36:09 +0000415 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000416 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000417 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
418 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000419
420 // Only make use of no-wrap flags if we failed to compute the sign bit
421 // directly. This matters if the multiplication always overflows, in
422 // which case we prefer to follow the result of the direct computation,
423 // though as the program is invoking undefined behaviour we can choose
424 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000425 if (isKnownNonNegative && !Known.isNegative())
426 Known.makeNonNegative();
427 else if (isKnownNegative && !Known.isNonNegative())
428 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000429}
430
Jingyue Wu37fcb592014-06-19 16:50:16 +0000431void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000432 KnownBits &Known) {
433 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000434 unsigned NumRanges = Ranges.getNumOperands() / 2;
435 assert(NumRanges >= 1);
436
Craig Topperf42b23f2017-04-28 06:28:56 +0000437 Known.Zero.setAllBits();
438 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000439
Rafael Espindola53190532012-03-30 15:52:11 +0000440 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000441 ConstantInt *Lower =
442 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
443 ConstantInt *Upper =
444 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000445 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000446
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000447 // The first CommonPrefixBits of all values in Range are equal.
448 unsigned CommonPrefixBits =
449 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
450
451 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000452 Known.One &= Range.getUnsignedMax() & Mask;
453 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000454 }
Rafael Espindola53190532012-03-30 15:52:11 +0000455}
Jay Foad5a29c362014-05-15 12:12:55 +0000456
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000457static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000458 SmallVector<const Value *, 16> WorkSet(1, I);
459 SmallPtrSet<const Value *, 32> Visited;
460 SmallPtrSet<const Value *, 16> EphValues;
461
Hal Finkelf2199b22015-10-23 20:37:08 +0000462 // The instruction defining an assumption's condition itself is always
463 // considered ephemeral to that assumption (even if it has other
464 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000465 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000466 return true;
467
Hal Finkel60db0582014-09-07 18:57:58 +0000468 while (!WorkSet.empty()) {
469 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000470 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000471 continue;
472
473 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000474 if (llvm::all_of(V->users(), [&](const User *U) {
475 return EphValues.count(U);
476 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000477 if (V == E)
478 return true;
479
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000480 if (V == I || isSafeToSpeculativelyExecute(V)) {
481 EphValues.insert(V);
482 if (const User *U = dyn_cast<User>(V))
483 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
484 J != JE; ++J)
485 WorkSet.push_back(*J);
486 }
Hal Finkel60db0582014-09-07 18:57:58 +0000487 }
488 }
489
490 return false;
491}
492
493// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000494bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000495 if (const CallInst *CI = dyn_cast<CallInst>(I))
496 if (Function *F = CI->getCalledFunction())
497 switch (F->getIntrinsicID()) {
498 default: break;
499 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
500 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000501 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000502 case Intrinsic::dbg_declare:
503 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000504 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000505 case Intrinsic::invariant_start:
506 case Intrinsic::invariant_end:
507 case Intrinsic::lifetime_start:
508 case Intrinsic::lifetime_end:
509 case Intrinsic::objectsize:
510 case Intrinsic::ptr_annotation:
511 case Intrinsic::var_annotation:
512 return true;
513 }
514
515 return false;
516}
517
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000518bool llvm::isValidAssumeForContext(const Instruction *Inv,
519 const Instruction *CxtI,
520 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000521 // There are two restrictions on the use of an assume:
522 // 1. The assume must dominate the context (or the control flow must
523 // reach the assume whenever it reaches the context).
524 // 2. The context must not be in the assume's set of ephemeral values
525 // (otherwise we will use the assume to prove that the condition
526 // feeding the assume is trivially true, thus causing the removal of
527 // the assume).
528
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000529 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000530 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000531 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000532 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
533 // We don't have a DT, but this trivially dominates.
534 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000535 }
536
Pete Cooper54a02552016-08-12 01:00:15 +0000537 // With or without a DT, the only remaining case we will check is if the
538 // instructions are in the same BB. Give up if that is not the case.
539 if (Inv->getParent() != CxtI->getParent())
540 return false;
541
Vedant Kumard3196742018-02-28 19:08:52 +0000542 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000543 // the other instruction. If we don't have a dom tree then we can check if
544 // the assume is first in the BB.
545 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000546 // Search forward from the assume until we reach the context (or the end
547 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000548 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000549 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000550 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000551 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000552 }
553
Pete Cooper54a02552016-08-12 01:00:15 +0000554 // The context comes first, but they're both in the same block. Make sure
555 // there is nothing in between that might interrupt the control flow.
556 for (BasicBlock::const_iterator I =
557 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
558 I != IE; ++I)
559 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
560 return false;
561
562 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000563}
564
Craig Topperb45eabc2017-04-26 16:39:58 +0000565static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
566 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000567 // Use of assumptions is context-sensitive. If we don't have a context, we
568 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000569 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000570 return;
571
Craig Topperb45eabc2017-04-26 16:39:58 +0000572 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000573
Hal Finkel8a9a7832017-01-11 13:24:24 +0000574 // Note that the patterns below need to be kept in sync with the code
575 // in AssumptionCache::updateAffectedValues.
576
577 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000578 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000579 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000580 CallInst *I = cast<CallInst>(AssumeVH);
581 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
582 "Got assumption for the wrong function!");
583 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000584 continue;
585
Vedant Kumard3196742018-02-28 19:08:52 +0000586 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 // We're running this loop for once for each value queried resulting in a
588 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000589
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000590 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
591 "must be an assume intrinsic");
592
593 Value *Arg = I->getArgOperand(0);
594
595 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000596 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000597 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000598 return;
599 }
Sanjay Patel96669962017-01-17 18:15:49 +0000600 if (match(Arg, m_Not(m_Specific(V))) &&
601 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
602 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000603 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000604 return;
605 }
Hal Finkel60db0582014-09-07 18:57:58 +0000606
David Majnemer9b609752014-12-12 23:59:29 +0000607 // The remaining tests are all recursive, so bail out if we hit the limit.
608 if (Depth == MaxDepth)
609 continue;
610
Hal Finkel60db0582014-09-07 18:57:58 +0000611 Value *A, *B;
612 auto m_V = m_CombineOr(m_Specific(V),
613 m_CombineOr(m_PtrToInt(m_Specific(V)),
614 m_BitCast(m_Specific(V))));
615
616 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000617 uint64_t C;
Hal Finkel60db0582014-09-07 18:57:58 +0000618 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000619 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000620 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000621 KnownBits RHSKnown(BitWidth);
622 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
623 Known.Zero |= RHSKnown.Zero;
624 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000625 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000626 } else if (match(Arg,
627 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000628 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000629 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000630 KnownBits RHSKnown(BitWidth);
631 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
632 KnownBits MaskKnown(BitWidth);
633 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000634
635 // For those bits in the mask that are known to be one, we can propagate
636 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000637 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
638 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000639 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000640 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
641 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000642 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000643 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000644 KnownBits RHSKnown(BitWidth);
645 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
646 KnownBits MaskKnown(BitWidth);
647 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000648
649 // For those bits in the mask that are known to be one, we can propagate
650 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000651 Known.Zero |= RHSKnown.One & MaskKnown.One;
652 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000653 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 } else if (match(Arg,
655 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000656 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000657 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000658 KnownBits RHSKnown(BitWidth);
659 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
660 KnownBits BKnown(BitWidth);
661 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000662
663 // For those bits in B that are known to be zero, we can propagate known
664 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000665 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
666 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000667 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000668 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
669 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000670 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000671 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000672 KnownBits RHSKnown(BitWidth);
673 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
674 KnownBits BKnown(BitWidth);
675 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000676
677 // For those bits in B that are known to be zero, we can propagate
678 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000679 Known.Zero |= RHSKnown.One & BKnown.Zero;
680 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000681 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000682 } else if (match(Arg,
683 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000684 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000685 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000686 KnownBits RHSKnown(BitWidth);
687 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
688 KnownBits BKnown(BitWidth);
689 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000690
691 // For those bits in B that are known to be zero, we can propagate known
692 // bits from the RHS to V. For those bits in B that are known to be one,
693 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000694 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
695 Known.One |= RHSKnown.One & BKnown.Zero;
696 Known.Zero |= RHSKnown.One & BKnown.One;
697 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000699 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
700 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000701 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000702 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000703 KnownBits RHSKnown(BitWidth);
704 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
705 KnownBits BKnown(BitWidth);
706 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000707
708 // For those bits in B that are known to be zero, we can propagate
709 // inverted known bits from the RHS to V. For those bits in B that are
710 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000711 Known.Zero |= RHSKnown.One & BKnown.Zero;
712 Known.One |= RHSKnown.Zero & BKnown.Zero;
713 Known.Zero |= RHSKnown.Zero & BKnown.One;
714 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000715 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000716 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
717 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000718 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000719 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
720 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000721 KnownBits RHSKnown(BitWidth);
722 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000723 // For those bits in RHS that are known, we can propagate them to known
724 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000725 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000726 Known.Zero |= RHSKnown.Zero;
Igor Laevskycec8f472017-12-05 12:18:15 +0000727 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000728 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000729 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000730 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
731 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000732 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000733 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
734 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000735 KnownBits RHSKnown(BitWidth);
736 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000737 // For those bits in RHS that are known, we can propagate them inverted
738 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000739 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000740 Known.Zero |= RHSKnown.One;
Igor Laevskycec8f472017-12-05 12:18:15 +0000741 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000742 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000743 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000744 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000745 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000746 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000747 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000748 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
749 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000750 KnownBits RHSKnown(BitWidth);
751 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000752 // For those bits in RHS that are known, we can propagate them to known
753 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000754 Known.Zero |= RHSKnown.Zero << C;
755 Known.One |= RHSKnown.One << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000756 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000757 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000758 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000759 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000760 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
761 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000762 KnownBits RHSKnown(BitWidth);
763 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000764 // For those bits in RHS that are known, we can propagate them inverted
765 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000766 Known.Zero |= RHSKnown.One << C;
767 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000768 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000769 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000770 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000771 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000772 KnownBits RHSKnown(BitWidth);
773 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000774
Craig Topperca48af32017-04-29 16:43:11 +0000775 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000776 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000777 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000778 }
779 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000780 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000781 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000782 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000783 KnownBits RHSKnown(BitWidth);
784 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000785
Craig Topperf0aeee02017-05-05 17:36:09 +0000786 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000787 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000788 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000789 }
790 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000791 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000792 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000793 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000794 KnownBits RHSKnown(BitWidth);
795 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000796
Craig Topperca48af32017-04-29 16:43:11 +0000797 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000798 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000799 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000800 }
801 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000802 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000803 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000804 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000805 KnownBits RHSKnown(BitWidth);
806 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000807
Craig Topperf0aeee02017-05-05 17:36:09 +0000808 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000809 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000810 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000811 }
812 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000813 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000814 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000815 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000816 KnownBits RHSKnown(BitWidth);
817 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000818
819 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000820 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
821 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000822 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000823 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000824 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000825 KnownBits RHSKnown(BitWidth);
826 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000827
Sanjay Patela60aec12018-02-08 14:52:40 +0000828 // If the RHS is known zero, then this assumption must be wrong (nothing
829 // is unsigned less than zero). Signal a conflict and get out of here.
830 if (RHSKnown.isZero()) {
831 Known.Zero.setAllBits();
832 Known.One.setAllBits();
833 break;
834 }
835
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000836 // Whatever high bits in c are zero are known to be zero (if c is a power
837 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000838 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000839 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000840 else
Craig Topper8df66c62017-05-12 17:20:30 +0000841 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000842 }
843 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000844
845 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000846 // have a logical fallacy. It's possible that the assumption is not reachable,
847 // so this isn't a real bug. On the other hand, the program may have undefined
848 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
849 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000850 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000851 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000852
Vivek Pandya95906582017-10-11 17:12:59 +0000853 if (Q.ORE)
854 Q.ORE->emit([&]() {
855 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
856 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
857 CxtI)
858 << "Detected conflicting code assumptions. Program may "
859 "have undefined behavior, or compiler may have "
860 "internal error.";
861 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000862 }
Hal Finkel60db0582014-09-07 18:57:58 +0000863}
864
Sanjay Patelb7d12382017-10-16 14:46:37 +0000865/// Compute known bits from a shift operator, including those with a
866/// non-constant shift amount. Known is the output of this function. Known2 is a
867/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000868/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000869/// respectively, and a shift amount, compute the implied known-zero or
870/// known-one bits of the shift operator's result respectively for that shift
871/// amount. The results from calling KZF and KOF are conservatively combined for
872/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000873static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000874 const Operator *I, KnownBits &Known, KnownBits &Known2,
875 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000876 function_ref<APInt(const APInt &, unsigned)> KZF,
877 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000878 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000879
880 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
881 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
882
Craig Topperb45eabc2017-04-26 16:39:58 +0000883 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000884 Known.Zero = KZF(Known.Zero, ShiftAmt);
885 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000886 // If the known bits conflict, this must be an overflowing left shift, so
887 // the shift result is poison. We can return anything we want. Choose 0 for
888 // the best folding opportunity.
889 if (Known.hasConflict())
890 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000891
Hal Finkelf2199b22015-10-23 20:37:08 +0000892 return;
893 }
894
Craig Topperb45eabc2017-04-26 16:39:58 +0000895 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000896
Sanjay Patele272be72017-10-12 17:31:46 +0000897 // If the shift amount could be greater than or equal to the bit-width of the
898 // LHS, the value could be poison, but bail out because the check below is
899 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000900 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000901 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000902 return;
903 }
904
Craig Topperb45eabc2017-04-26 16:39:58 +0000905 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000906 // BitWidth > 64 and any upper bits are known, we'll end up returning the
907 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
909 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000910
911 // It would be more-clearly correct to use the two temporaries for this
912 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000913 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000914
James Molloy493e57d2015-10-26 14:10:46 +0000915 // If we know the shifter operand is nonzero, we can sometimes infer more
916 // known bits. However this is expensive to compute, so be lazy about it and
917 // only compute it when absolutely necessary.
918 Optional<bool> ShifterOperandIsNonZero;
919
Hal Finkelf2199b22015-10-23 20:37:08 +0000920 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000921 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
922 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000923 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000924 if (!*ShifterOperandIsNonZero)
925 return;
926 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000927
Craig Topperb45eabc2017-04-26 16:39:58 +0000928 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000929
Craig Topperb45eabc2017-04-26 16:39:58 +0000930 Known.Zero.setAllBits();
931 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000932 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
933 // Combine the shifted known input bits only for those shift amounts
934 // compatible with its known constraints.
935 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
936 continue;
937 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
938 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000939 // If we know the shifter is nonzero, we may be able to infer more known
940 // bits. This check is sunk down as far as possible to avoid the expensive
941 // call to isKnownNonZero if the cheaper checks above fail.
942 if (ShiftAmt == 0) {
943 if (!ShifterOperandIsNonZero.hasValue())
944 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000945 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000946 if (*ShifterOperandIsNonZero)
947 continue;
948 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000949
Sam McCalld0d43e62017-12-04 12:51:49 +0000950 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
951 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000952 }
953
Sanjay Patele272be72017-10-12 17:31:46 +0000954 // If the known bits conflict, the result is poison. Return a 0 and hope the
955 // caller can further optimize that.
956 if (Known.hasConflict())
957 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000958}
959
Craig Topperb45eabc2017-04-26 16:39:58 +0000960static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
961 unsigned Depth, const Query &Q) {
962 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000963
Craig Topperb45eabc2017-04-26 16:39:58 +0000964 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000965 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000966 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000967 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000968 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000969 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000970 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000971 case Instruction::And: {
972 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000973 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
974 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000975
Chris Lattner965c7692008-06-02 01:18:21 +0000976 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000977 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000978 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000979 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000980
981 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
982 // here we handle the more general case of adding any odd number by
983 // matching the form add(x, add(x, y)) where y is odd.
984 // TODO: This could be generalized to clearing any bit set in y where the
985 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000986 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000987 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000988 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000989 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000990 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000991 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000992 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000993 }
Jay Foad5a29c362014-05-15 12:12:55 +0000994 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000995 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000996 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +0000997 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
998 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000999
Chris Lattner965c7692008-06-02 01:18:21 +00001000 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001001 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001002 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001003 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001004 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001005 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001006 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1007 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001008
Chris Lattner965c7692008-06-02 01:18:21 +00001009 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001010 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001011 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001012 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1013 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001014 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001015 }
1016 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001017 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +00001018 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1019 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001020 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001021 }
1022 case Instruction::UDiv: {
1023 // For the purposes of computing leading zeros we can conservatively
1024 // treat a udiv as a logical right shift by the power of 2 known to
1025 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001026 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001027 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001028
Craig Topperf0aeee02017-05-05 17:36:09 +00001029 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001030 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001031 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1032 if (RHSMaxLeadingZeros != BitWidth)
1033 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001034
Craig Topperb45eabc2017-04-26 16:39:58 +00001035 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001036 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001037 }
David Majnemera19d0f22016-08-06 08:16:00 +00001038 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001039 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001040 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1041 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001042 computeKnownBits(RHS, Known, Depth + 1, Q);
1043 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001044 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001045 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1046 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001047 }
1048
1049 unsigned MaxHighOnes = 0;
1050 unsigned MaxHighZeros = 0;
1051 if (SPF == SPF_SMAX) {
1052 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001053 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001054 // We can derive a lower bound on the result by taking the max of the
1055 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001056 MaxHighOnes =
1057 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001058 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001059 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001060 MaxHighZeros = 1;
1061 } else if (SPF == SPF_SMIN) {
1062 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001063 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001064 // We can derive an upper bound on the result by taking the max of the
1065 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001066 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1067 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001068 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001069 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001070 MaxHighOnes = 1;
1071 } else if (SPF == SPF_UMAX) {
1072 // We can derive a lower bound on the result by taking the max of the
1073 // leading one bits.
1074 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001075 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001076 } else if (SPF == SPF_UMIN) {
1077 // We can derive an upper bound on the result by taking the max of the
1078 // leading zero bits.
1079 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001080 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001081 } else if (SPF == SPF_ABS) {
1082 // RHS from matchSelectPattern returns the negation part of abs pattern.
1083 // If the negate has an NSW flag we can assume the sign bit of the result
1084 // will be 0 because that makes abs(INT_MIN) undefined.
1085 if (cast<Instruction>(RHS)->hasNoSignedWrap())
1086 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001087 }
1088
Chris Lattner965c7692008-06-02 01:18:21 +00001089 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001090 Known.One &= Known2.One;
1091 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001092 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001093 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001094 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001095 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001096 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001097 }
Chris Lattner965c7692008-06-02 01:18:21 +00001098 case Instruction::FPTrunc:
1099 case Instruction::FPExt:
1100 case Instruction::FPToUI:
1101 case Instruction::FPToSI:
1102 case Instruction::SIToFP:
1103 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001104 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001105 case Instruction::PtrToInt:
1106 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001107 // Fall through and handle them the same as zext/trunc.
1108 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001109 case Instruction::ZExt:
1110 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001111 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001112
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001113 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001114 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1115 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001116 Type *ScalarTy = SrcTy->getScalarType();
1117 SrcBitWidth = ScalarTy->isPointerTy() ?
1118 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1119 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001120
1121 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001122 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001123 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001124 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001125 // Any top bits are known to be zero.
1126 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001127 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001128 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001129 }
1130 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001131 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001132 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001133 // TODO: For now, not handling conversions like:
1134 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001135 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001136 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001137 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001138 }
1139 break;
1140 }
1141 case Instruction::SExt: {
1142 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001143 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001144
Craig Topperd938fd12017-05-03 22:07:25 +00001145 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001146 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001147 // If the sign bit of the input is known set or clear, then we know the
1148 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001149 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001150 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001151 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001152 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001153 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001154 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Sam McCalld0d43e62017-12-04 12:51:49 +00001155 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1156 APInt KZResult = KnownZero << ShiftAmt;
1157 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001158 // If this shift has "nsw" keyword, then the result is either a poison
1159 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001160 if (NSW && KnownZero.isSignBitSet())
1161 KZResult.setSignBit();
1162 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001163 };
1164
Sam McCalld0d43e62017-12-04 12:51:49 +00001165 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1166 APInt KOResult = KnownOne << ShiftAmt;
1167 if (NSW && KnownOne.isSignBitSet())
1168 KOResult.setSignBit();
1169 return KOResult;
1170 };
1171
1172 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001173 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001174 }
1175 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001176 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001177 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1178 APInt KZResult = KnownZero.lshr(ShiftAmt);
1179 // High bits known zero.
1180 KZResult.setHighBits(ShiftAmt);
1181 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001182 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001183
Sam McCalld0d43e62017-12-04 12:51:49 +00001184 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1185 return KnownOne.lshr(ShiftAmt);
1186 };
1187
1188 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001189 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001190 }
1191 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001192 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001193 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1194 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001195 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001196
Sam McCalld0d43e62017-12-04 12:51:49 +00001197 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1198 return KnownOne.ashr(ShiftAmt);
1199 };
1200
1201 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001202 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001203 }
Chris Lattner965c7692008-06-02 01:18:21 +00001204 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001205 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001206 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001207 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001208 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001209 }
Chris Lattner965c7692008-06-02 01:18:21 +00001210 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001211 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001212 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001213 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001214 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001215 }
1216 case Instruction::SRem:
1217 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001218 APInt RA = Rem->getValue().abs();
1219 if (RA.isPowerOf2()) {
1220 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001221 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001222
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001223 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001224 Known.Zero = Known2.Zero & LowBits;
1225 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001226
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001227 // If the first operand is non-negative or has all low bits zero, then
1228 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001229 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001230 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001231
1232 // If the first operand is negative and not all low bits are zero, then
1233 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001234 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001235 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001236
Craig Topperb45eabc2017-04-26 16:39:58 +00001237 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001238 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001239 }
1240 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001241
1242 // The sign bit is the LHS's sign bit, except when the result of the
1243 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001244 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001245 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001246 if (Known2.isNonNegative())
1247 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001248
Chris Lattner965c7692008-06-02 01:18:21 +00001249 break;
1250 case Instruction::URem: {
1251 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001252 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001253 if (RA.isPowerOf2()) {
1254 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001255 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1256 Known.Zero |= ~LowBits;
1257 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001258 break;
1259 }
1260 }
1261
1262 // Since the result is less than or equal to either operand, any leading
1263 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001264 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1265 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001266
Craig Topper8df66c62017-05-12 17:20:30 +00001267 unsigned Leaders =
1268 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001269 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001270 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001271 break;
1272 }
1273
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001274 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001275 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001276 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001277 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001278 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001279
Chris Lattner965c7692008-06-02 01:18:21 +00001280 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001281 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001282 break;
1283 }
1284 case Instruction::GetElementPtr: {
1285 // Analyze all of the subscripts of this getelementptr instruction
1286 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001287 KnownBits LocalKnown(BitWidth);
1288 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001289 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001290
1291 gep_type_iterator GTI = gep_type_begin(I);
1292 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1293 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001294 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001295 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001296
1297 // Handle case when index is vector zeroinitializer
1298 Constant *CIndex = cast<Constant>(Index);
1299 if (CIndex->isZeroValue())
1300 continue;
1301
1302 if (CIndex->getType()->isVectorTy())
1303 Index = CIndex->getSplatValue();
1304
Chris Lattner965c7692008-06-02 01:18:21 +00001305 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001306 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001307 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001308 TrailZ = std::min<unsigned>(TrailZ,
1309 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001310 } else {
1311 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001312 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001313 if (!IndexedTy->isSized()) {
1314 TrailZ = 0;
1315 break;
1316 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001317 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001318 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001319 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1320 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001321 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001322 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001323 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001324 }
1325 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001326
Craig Topperb45eabc2017-04-26 16:39:58 +00001327 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001328 break;
1329 }
1330 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001331 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001332 // Handle the case of a simple two-predecessor recurrence PHI.
1333 // There's a lot more that could theoretically be done here, but
1334 // this is sufficient to catch some interesting cases.
1335 if (P->getNumIncomingValues() == 2) {
1336 for (unsigned i = 0; i != 2; ++i) {
1337 Value *L = P->getIncomingValue(i);
1338 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001339 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001340 if (!LU)
1341 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001342 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001343 // Check for operations that have the property that if
1344 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001345 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001346 if (Opcode == Instruction::Add ||
1347 Opcode == Instruction::Sub ||
1348 Opcode == Instruction::And ||
1349 Opcode == Instruction::Or ||
1350 Opcode == Instruction::Mul) {
1351 Value *LL = LU->getOperand(0);
1352 Value *LR = LU->getOperand(1);
1353 // Find a recurrence.
1354 if (LL == I)
1355 L = LR;
1356 else if (LR == I)
1357 L = LL;
1358 else
1359 break;
1360 // Ok, we have a PHI of the form L op= R. Check for low
1361 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001362 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001363
1364 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001365 KnownBits Known3(Known);
1366 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001367
Craig Topper8df66c62017-05-12 17:20:30 +00001368 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1369 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001370
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001371 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1372 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1373 // If initial value of recurrence is nonnegative, and we are adding
1374 // a nonnegative number with nsw, the result can only be nonnegative
1375 // or poison value regardless of the number of times we execute the
1376 // add in phi recurrence. If initial value is negative and we are
1377 // adding a negative number with nsw, the result can only be
1378 // negative or poison value. Similar arguments apply to sub and mul.
1379 //
1380 // (add non-negative, non-negative) --> non-negative
1381 // (add negative, negative) --> negative
1382 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001383 if (Known2.isNonNegative() && Known3.isNonNegative())
1384 Known.makeNonNegative();
1385 else if (Known2.isNegative() && Known3.isNegative())
1386 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001387 }
1388
1389 // (sub nsw non-negative, negative) --> non-negative
1390 // (sub nsw negative, non-negative) --> negative
1391 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001392 if (Known2.isNonNegative() && Known3.isNegative())
1393 Known.makeNonNegative();
1394 else if (Known2.isNegative() && Known3.isNonNegative())
1395 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001396 }
1397
1398 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001399 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1400 Known3.isNonNegative())
1401 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001402 }
1403
Chris Lattner965c7692008-06-02 01:18:21 +00001404 break;
1405 }
1406 }
1407 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001408
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001409 // Unreachable blocks may have zero-operand PHI nodes.
1410 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001411 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001412
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001413 // Otherwise take the unions of the known bit sets of the operands,
1414 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001415 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001416 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001417 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001418 break;
1419
Craig Topperb45eabc2017-04-26 16:39:58 +00001420 Known.Zero.setAllBits();
1421 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001422 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001423 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001424 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001425
Craig Topperb45eabc2017-04-26 16:39:58 +00001426 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001427 // Recurse, but cap the recursion to one level, because we don't
1428 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001429 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1430 Known.Zero &= Known2.Zero;
1431 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001432 // If all bits have been ruled out, there's no need to check
1433 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001434 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001435 break;
1436 }
1437 }
Chris Lattner965c7692008-06-02 01:18:21 +00001438 break;
1439 }
1440 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001441 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001442 // If range metadata is attached to this call, set known bits from that,
1443 // and then intersect with known bits based on other properties of the
1444 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001445 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001446 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001447 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001448 computeKnownBits(RV, Known2, Depth + 1, Q);
1449 Known.Zero |= Known2.Zero;
1450 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001451 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001452 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001453 switch (II->getIntrinsicID()) {
1454 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001455 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001456 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1457 Known.Zero |= Known2.Zero.reverseBits();
1458 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001459 break;
Philip Reames675418e2015-10-06 20:20:45 +00001460 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001461 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1462 Known.Zero |= Known2.Zero.byteSwap();
1463 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001464 break;
Craig Topper868813f2017-05-08 17:22:34 +00001465 case Intrinsic::ctlz: {
1466 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1467 // If we have a known 1, its position is our upper bound.
1468 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001469 // If this call is undefined for 0, the result will be less than 2^n.
1470 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001471 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1472 unsigned LowBits = Log2_32(PossibleLZ)+1;
1473 Known.Zero.setBitsFrom(LowBits);
1474 break;
1475 }
1476 case Intrinsic::cttz: {
1477 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1478 // If we have a known 1, its position is our upper bound.
1479 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1480 // If this call is undefined for 0, the result will be less than 2^n.
1481 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1482 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1483 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001484 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001485 break;
1486 }
1487 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001488 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001489 // We can bound the space the count needs. Also, bits known to be zero
1490 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001491 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001492 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001493 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001494 // TODO: we could bound KnownOne using the lower bound on the number
1495 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001496 break;
1497 }
Chad Rosierb3628842011-05-26 23:13:19 +00001498 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001499 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001500 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001501 }
1502 }
1503 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001504 case Instruction::ExtractElement:
1505 // Look through extract element. At the moment we keep this simple and skip
1506 // tracking the specific element. But at least we might find information
1507 // valid for all elements of the vector (for example if vector is sign
1508 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001509 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001510 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001511 case Instruction::ExtractValue:
1512 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001513 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001514 if (EVI->getNumIndices() != 1) break;
1515 if (EVI->getIndices()[0] == 0) {
1516 switch (II->getIntrinsicID()) {
1517 default: break;
1518 case Intrinsic::uadd_with_overflow:
1519 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001520 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001521 II->getArgOperand(1), false, Known, Known2,
1522 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001523 break;
1524 case Intrinsic::usub_with_overflow:
1525 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001526 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001527 II->getArgOperand(1), false, Known, Known2,
1528 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001529 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001530 case Intrinsic::umul_with_overflow:
1531 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001532 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001533 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001534 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001535 }
1536 }
1537 }
Chris Lattner965c7692008-06-02 01:18:21 +00001538 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001539}
1540
1541/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001542/// them.
1543KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1544 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1545 computeKnownBits(V, Known, Depth, Q);
1546 return Known;
1547}
1548
1549/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001550/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001551///
1552/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1553/// we cannot optimize based on the assumption that it is zero without changing
1554/// it to be an explicit zero. If we don't change it to zero, other code could
1555/// optimized based on the contradictory assumption that it is non-zero.
1556/// Because instcombine aggressively folds operations with undef args anyway,
1557/// this won't lose us code quality.
1558///
1559/// This function is defined on values with integer type, values with pointer
1560/// type, and vectors of integers. In the case
1561/// where V is a vector, known zero, and known one values are the
1562/// same width as the vector element, and the bit is set only if it is true
1563/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001564void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1565 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001566 assert(V && "No Value?");
1567 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001568 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001569
Craig Topperfde47232017-07-09 07:04:03 +00001570 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001571 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001572 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001573
1574 Type *ScalarTy = V->getType()->getScalarType();
1575 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1576 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1577 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001578 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001579 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001580
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001581 const APInt *C;
1582 if (match(V, m_APInt(C))) {
1583 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001584 Known.One = *C;
1585 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001586 return;
1587 }
1588 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001589 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001590 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001591 return;
1592 }
1593 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001594 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001595 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001596 // We know that CDS must be a vector of integers. Take the intersection of
1597 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001598 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001599 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001600 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001601 Known.Zero &= ~Elt;
1602 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001603 }
1604 return;
1605 }
1606
Pete Cooper35b00d52016-08-13 01:05:32 +00001607 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001608 // We know that CV must be a vector of integers. Take the intersection of
1609 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001610 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001611 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1612 Constant *Element = CV->getAggregateElement(i);
1613 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1614 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001615 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001616 return;
1617 }
Craig Topperb98ee582017-10-21 16:35:39 +00001618 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001619 Known.Zero &= ~Elt;
1620 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001621 }
1622 return;
1623 }
1624
Jingyue Wu12b0c282015-06-15 05:46:29 +00001625 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001626 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001627
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001628 // We can't imply anything about undefs.
1629 if (isa<UndefValue>(V))
1630 return;
1631
1632 // There's no point in looking through other users of ConstantData for
1633 // assumptions. Confirm that we've handled them all.
1634 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1635
Jingyue Wu12b0c282015-06-15 05:46:29 +00001636 // Limit search depth.
1637 // All recursive calls that increase depth must come after this.
1638 if (Depth == MaxDepth)
1639 return;
1640
1641 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1642 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001643 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001644 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001645 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001646 return;
1647 }
1648
Pete Cooper35b00d52016-08-13 01:05:32 +00001649 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001650 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001651
Craig Topperb45eabc2017-04-26 16:39:58 +00001652 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001653 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001654 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001655 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001656 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001657 }
1658
Craig Topperb45eabc2017-04-26 16:39:58 +00001659 // computeKnownBitsFromAssume strictly refines Known.
1660 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001661
1662 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001663 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001664
Craig Topperb45eabc2017-04-26 16:39:58 +00001665 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001666}
1667
Sanjay Patelaee84212014-11-04 16:27:42 +00001668/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001669/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001670/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001671/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001672bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001673 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001674 assert(Depth <= MaxDepth && "Limit Search Depth");
1675
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001676 // Attempt to match against constants.
1677 if (OrZero && match(V, m_Power2OrZero()))
1678 return true;
1679 if (match(V, m_Power2()))
1680 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001681
1682 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1683 // it is shifted off the end then the result is undefined.
1684 if (match(V, m_Shl(m_One(), m_Value())))
1685 return true;
1686
Craig Topperbcfd2d12017-04-20 16:56:25 +00001687 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1688 // the bottom. If it is shifted off the bottom then the result is undefined.
1689 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001690 return true;
1691
1692 // The remaining tests are all recursive, so bail out if we hit the limit.
1693 if (Depth++ == MaxDepth)
1694 return false;
1695
Craig Topper9f008862014-04-15 04:59:12 +00001696 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001697 // A shift left or a logical shift right of a power of two is a power of two
1698 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001699 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001700 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001701 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001702
Pete Cooper35b00d52016-08-13 01:05:32 +00001703 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001704 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001705
Pete Cooper35b00d52016-08-13 01:05:32 +00001706 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001707 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1708 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001709
Duncan Sandsba286d72011-10-26 20:55:21 +00001710 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1711 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001712 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1713 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001714 return true;
1715 // X & (-X) is always a power of two or zero.
1716 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1717 return true;
1718 return false;
1719 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001720
David Majnemerb7d54092013-07-30 21:01:36 +00001721 // Adding a power-of-two or zero to the same power-of-two or zero yields
1722 // either the original power-of-two, a larger power-of-two or zero.
1723 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001724 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001725 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1726 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1727 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001728 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001729 return true;
1730 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1731 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001732 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001733 return true;
1734
1735 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001736 KnownBits LHSBits(BitWidth);
1737 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001738
Craig Topperb45eabc2017-04-26 16:39:58 +00001739 KnownBits RHSBits(BitWidth);
1740 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001741 // If i8 V is a power of two or zero:
1742 // ZeroBits: 1 1 1 0 1 1 1 1
1743 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001744 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001745 // If OrZero isn't set, we cannot give back a zero result.
1746 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001747 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001748 return true;
1749 }
1750 }
David Majnemerbeab5672013-05-18 19:30:37 +00001751
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001752 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001753 // is a power of two only if the first operand is a power of two and not
1754 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001755 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1756 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001757 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001758 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001759 }
1760
Duncan Sandsd3951082011-01-25 09:38:29 +00001761 return false;
1762}
1763
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001764/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001765///
1766/// Uses properties inherent in a GEP to try to determine whether it is known
1767/// to be non-null.
1768///
1769/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001770static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001771 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001772 const Function *F = nullptr;
1773 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1774 F = I->getFunction();
1775
1776 if (!GEP->isInBounds() ||
1777 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001778 return false;
1779
1780 // FIXME: Support vector-GEPs.
1781 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1782
1783 // If the base pointer is non-null, we cannot walk to a null address with an
1784 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001785 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001786 return true;
1787
Chandler Carruth80d3e562012-12-07 02:08:58 +00001788 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1789 // If so, then the GEP cannot produce a null pointer, as doing so would
1790 // inherently violate the inbounds contract within address space zero.
1791 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1792 GTI != GTE; ++GTI) {
1793 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001794 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001795 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1796 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001797 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001798 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1799 if (ElementOffset > 0)
1800 return true;
1801 continue;
1802 }
1803
1804 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001805 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001806 continue;
1807
1808 // Fast path the constant operand case both for efficiency and so we don't
1809 // increment Depth when just zipping down an all-constant GEP.
1810 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1811 if (!OpC->isZero())
1812 return true;
1813 continue;
1814 }
1815
1816 // We post-increment Depth here because while isKnownNonZero increments it
1817 // as well, when we pop back up that increment won't persist. We don't want
1818 // to recurse 10k times just because we have 10k GEP operands. We don't
1819 // bail completely out because we want to handle constant GEPs regardless
1820 // of depth.
1821 if (Depth++ >= MaxDepth)
1822 continue;
1823
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001824 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001825 return true;
1826 }
1827
1828 return false;
1829}
1830
Nuno Lopes404f1062017-09-09 18:23:11 +00001831static bool isKnownNonNullFromDominatingCondition(const Value *V,
1832 const Instruction *CtxI,
1833 const DominatorTree *DT) {
1834 assert(V->getType()->isPointerTy() && "V must be pointer type");
1835 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1836
1837 if (!CtxI || !DT)
1838 return false;
1839
1840 unsigned NumUsesExplored = 0;
1841 for (auto *U : V->users()) {
1842 // Avoid massive lists
1843 if (NumUsesExplored >= DomConditionsMaxUses)
1844 break;
1845 NumUsesExplored++;
1846
1847 // If the value is used as an argument to a call or invoke, then argument
1848 // attributes may provide an answer about null-ness.
1849 if (auto CS = ImmutableCallSite(U))
1850 if (auto *CalledFunc = CS.getCalledFunction())
1851 for (const Argument &Arg : CalledFunc->args())
1852 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1853 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1854 return true;
1855
1856 // Consider only compare instructions uniquely controlling a branch
1857 CmpInst::Predicate Pred;
1858 if (!match(const_cast<User *>(U),
1859 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1860 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1861 continue;
1862
1863 for (auto *CmpU : U->users()) {
1864 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
1865 assert(BI->isConditional() && "uses a comparison!");
1866
1867 BasicBlock *NonNullSuccessor =
1868 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1869 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1870 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1871 return true;
1872 } else if (Pred == ICmpInst::ICMP_NE &&
1873 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
1874 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
1875 return true;
1876 }
1877 }
1878 }
1879
1880 return false;
1881}
1882
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001883/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1884/// ensure that the value it's attached to is never Value? 'RangeType' is
1885/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001886static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001887 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1888 assert(NumRanges >= 1);
1889 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001890 ConstantInt *Lower =
1891 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1892 ConstantInt *Upper =
1893 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001894 ConstantRange Range(Lower->getValue(), Upper->getValue());
1895 if (Range.contains(Value))
1896 return false;
1897 }
1898 return true;
1899}
1900
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001901/// Return true if the given value is known to be non-zero when defined. For
1902/// vectors, return true if every element is known to be non-zero when
1903/// defined. For pointers, if the context instruction and dominator tree are
1904/// specified, perform context-sensitive analysis and return true if the
1905/// pointer couldn't possibly be null at the specified instruction.
1906/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001907bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001908 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001909 if (C->isNullValue())
1910 return false;
1911 if (isa<ConstantInt>(C))
1912 // Must be non-zero due to null test above.
1913 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001914
1915 // For constant vectors, check that all elements are undefined or known
1916 // non-zero to determine that the whole vector is known non-zero.
1917 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1918 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1919 Constant *Elt = C->getAggregateElement(i);
1920 if (!Elt || Elt->isNullValue())
1921 return false;
1922 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1923 return false;
1924 }
1925 return true;
1926 }
1927
Nuno Lopes404f1062017-09-09 18:23:11 +00001928 // A global variable in address space 0 is non null unless extern weak
1929 // or an absolute symbol reference. Other address spaces may have null as a
1930 // valid address for a global, so we can't assume anything.
1931 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1932 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1933 GV->getType()->getAddressSpace() == 0)
1934 return true;
1935 } else
1936 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00001937 }
1938
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001939 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001940 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001941 // If the possible ranges don't contain zero, then the value is
1942 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001943 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001944 const APInt ZeroValue(Ty->getBitWidth(), 0);
1945 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1946 return true;
1947 }
1948 }
1949 }
1950
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00001951 // Some of the tests below are recursive, so bail out if we hit the limit.
1952 if (Depth++ >= MaxDepth)
1953 return false;
1954
Nuno Lopes404f1062017-09-09 18:23:11 +00001955 // Check for pointer simplifications.
1956 if (V->getType()->isPointerTy()) {
1957 // Alloca never returns null, malloc might.
1958 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1959 return true;
1960
1961 // A byval, inalloca, or nonnull argument is never null.
1962 if (const Argument *A = dyn_cast<Argument>(V))
1963 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1964 return true;
1965
1966 // A Load tagged with nonnull metadata is never null.
1967 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
1968 if (LI->getMetadata(LLVMContext::MD_nonnull))
1969 return true;
1970
Piotr Padlewski5642a422018-05-18 23:54:33 +00001971 if (auto CS = ImmutableCallSite(V)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001972 if (CS.isReturnNonNull())
1973 return true;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00001974 if (const auto *RP = getArgumentAliasingToReturnedPointer(CS))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00001975 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00001976 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001977 }
1978
Duncan Sandsd3951082011-01-25 09:38:29 +00001979
Nuno Lopes404f1062017-09-09 18:23:11 +00001980 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001981 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001982 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001983 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001984
Pete Cooper35b00d52016-08-13 01:05:32 +00001985 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001986 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001987 return true;
1988 }
1989
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001990 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001991
1992 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001993 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001994 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001995 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001996
1997 // ext X != 0 if X != 0.
1998 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001999 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002000
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002001 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002002 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002003 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002004 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002005 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002006 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002007 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002008
Craig Topperb45eabc2017-04-26 16:39:58 +00002009 KnownBits Known(BitWidth);
2010 computeKnownBits(X, Known, Depth, Q);
2011 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002012 return true;
2013 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002014 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002015 // defined if the sign bit is shifted off the end.
2016 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002017 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002018 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002019 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002020 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002021
Craig Topper6e11a052017-05-08 16:22:48 +00002022 KnownBits Known = computeKnownBits(X, Depth, Q);
2023 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002024 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002025
2026 // If the shifter operand is a constant, and all of the bits shifted
2027 // out are known to be zero, and X is known non-zero then at least one
2028 // non-zero bit must remain.
2029 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002030 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2031 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002032 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002033 return true;
2034 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002035 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002036 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002037 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002038 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002039 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002040 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002041 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002042 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002043 // X + Y.
2044 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002045 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2046 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002047
2048 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002049 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002050 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002051 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002052 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002053
2054 // If X and Y are both negative (as signed values) then their sum is not
2055 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002056 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002057 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2058 // The sign bit of X is set. If some other bit is set then X is not equal
2059 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002060 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002061 return true;
2062 // The sign bit of Y is set. If some other bit is set then Y is not equal
2063 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002064 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002065 return true;
2066 }
2067
2068 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002069 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002070 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002071 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002072 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002073 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002074 return true;
2075 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002076 // X * Y.
2077 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002078 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002079 // If X and Y are non-zero then so is X * Y as long as the multiplication
2080 // does not overflow.
2081 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002082 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002083 return true;
2084 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002085 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002086 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002087 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2088 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002089 return true;
2090 }
James Molloy897048b2015-09-29 14:08:45 +00002091 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002092 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002093 // Try and detect a recurrence that monotonically increases from a
2094 // starting value, as these are common as induction variables.
2095 if (PN->getNumIncomingValues() == 2) {
2096 Value *Start = PN->getIncomingValue(0);
2097 Value *Induction = PN->getIncomingValue(1);
2098 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2099 std::swap(Start, Induction);
2100 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2101 if (!C->isZero() && !C->isNegative()) {
2102 ConstantInt *X;
2103 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2104 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2105 !X->isNegative())
2106 return true;
2107 }
2108 }
2109 }
Jun Bum Limca832662016-02-01 17:03:07 +00002110 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002111 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002112 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002113 });
2114 if (AllNonZeroConstants)
2115 return true;
James Molloy897048b2015-09-29 14:08:45 +00002116 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002117
Craig Topperb45eabc2017-04-26 16:39:58 +00002118 KnownBits Known(BitWidth);
2119 computeKnownBits(V, Known, Depth, Q);
2120 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002121}
2122
James Molloy1d88d6f2015-10-22 13:18:42 +00002123/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002124static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2125 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002126 if (!BO || BO->getOpcode() != Instruction::Add)
2127 return false;
2128 Value *Op = nullptr;
2129 if (V2 == BO->getOperand(0))
2130 Op = BO->getOperand(1);
2131 else if (V2 == BO->getOperand(1))
2132 Op = BO->getOperand(0);
2133 else
2134 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002135 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002136}
2137
2138/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002139static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002140 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002141 return false;
2142 if (V1->getType() != V2->getType())
2143 // We can't look through casts yet.
2144 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002145 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002146 return true;
2147
Craig Topper3002d5b2017-06-06 07:13:15 +00002148 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002149 // Are any known bits in V1 contradictory to known bits in V2? If V1
2150 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002151 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2152 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002153
Craig Topper8365df82017-06-06 07:13:09 +00002154 if (Known1.Zero.intersects(Known2.One) ||
2155 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002156 return true;
2157 }
2158 return false;
2159}
2160
Sanjay Patelaee84212014-11-04 16:27:42 +00002161/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2162/// simplify operations downstream. Mask is known to be zero for bits that V
2163/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002164///
2165/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002166/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002167/// where V is a vector, the mask, known zero, and known one values are the
2168/// same width as the vector element, and the bit is set only if it is true
2169/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002170bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002171 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002172 KnownBits Known(Mask.getBitWidth());
2173 computeKnownBits(V, Known, Depth, Q);
2174 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002175}
2176
Sanjay Patela06d9892016-06-22 19:20:59 +00002177/// For vector constants, loop over the elements and find the constant with the
2178/// minimum number of sign bits. Return 0 if the value is not a vector constant
2179/// or if any element was not analyzed; otherwise, return the count for the
2180/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002181static unsigned computeNumSignBitsVectorConstant(const Value *V,
2182 unsigned TyBits) {
2183 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002184 if (!CV || !CV->getType()->isVectorTy())
2185 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002186
Sanjay Patela06d9892016-06-22 19:20:59 +00002187 unsigned MinSignBits = TyBits;
2188 unsigned NumElts = CV->getType()->getVectorNumElements();
2189 for (unsigned i = 0; i != NumElts; ++i) {
2190 // If we find a non-ConstantInt, bail out.
2191 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2192 if (!Elt)
2193 return 0;
2194
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002195 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002196 }
2197
2198 return MinSignBits;
2199}
Chris Lattner965c7692008-06-02 01:18:21 +00002200
Sanjoy Das39a684d2017-02-25 20:30:45 +00002201static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2202 const Query &Q);
2203
2204static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2205 const Query &Q) {
2206 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2207 assert(Result > 0 && "At least one sign bit needs to be present!");
2208 return Result;
2209}
2210
Sanjay Patelaee84212014-11-04 16:27:42 +00002211/// Return the number of times the sign bit of the register is replicated into
2212/// the other bits. We know that at least 1 bit is always equal to the sign bit
2213/// (itself), but other cases can give us information. For example, immediately
2214/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002215/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002216/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002217static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2218 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002219 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002220
2221 // We return the minimum number of sign bits that are guaranteed to be present
2222 // in V, so for undef we have to conservatively return 1. We don't have the
2223 // same behavior for poison though -- that's a FIXME today.
2224
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002225 Type *ScalarTy = V->getType()->getScalarType();
2226 unsigned TyBits = ScalarTy->isPointerTy() ?
2227 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2228 Q.DL.getTypeSizeInBits(ScalarTy);
2229
Chris Lattner965c7692008-06-02 01:18:21 +00002230 unsigned Tmp, Tmp2;
2231 unsigned FirstAnswer = 1;
2232
Jay Foada0653a32014-05-14 21:14:37 +00002233 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002234 // below.
2235
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002236 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002237 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002238
Pete Cooper35b00d52016-08-13 01:05:32 +00002239 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002240 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002241 default: break;
2242 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002243 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002244 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002245
Nadav Rotemc99a3872015-03-06 00:23:58 +00002246 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002247 const APInt *Denominator;
2248 // sdiv X, C -> adds log(C) sign bits.
2249 if (match(U->getOperand(1), m_APInt(Denominator))) {
2250
2251 // Ignore non-positive denominator.
2252 if (!Denominator->isStrictlyPositive())
2253 break;
2254
2255 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002256 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002257
2258 // Add floor(log(C)) bits to the numerator bits.
2259 return std::min(TyBits, NumBits + Denominator->logBase2());
2260 }
2261 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002262 }
2263
2264 case Instruction::SRem: {
2265 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002266 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2267 // positive constant. This let us put a lower bound on the number of sign
2268 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002269 if (match(U->getOperand(1), m_APInt(Denominator))) {
2270
2271 // Ignore non-positive denominator.
2272 if (!Denominator->isStrictlyPositive())
2273 break;
2274
2275 // Calculate the incoming numerator bits. SRem by a positive constant
2276 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002277 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002278 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002279
2280 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002281 // denominator. Given that the denominator is positive, there are two
2282 // cases:
2283 //
2284 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2285 // (1 << ceilLogBase2(C)).
2286 //
2287 // 2. the numerator is negative. Then the result range is (-C,0] and
2288 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2289 //
2290 // Thus a lower bound on the number of sign bits is `TyBits -
2291 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002292
Sanjoy Dase561fee2015-03-25 22:33:53 +00002293 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002294 return std::max(NumrBits, ResBits);
2295 }
2296 break;
2297 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002298
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002299 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002300 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002301 // ashr X, C -> adds C sign bits. Vectors too.
2302 const APInt *ShAmt;
2303 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002304 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002305 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002306 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002307 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002308 if (Tmp > TyBits) Tmp = TyBits;
2309 }
2310 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002311 }
2312 case Instruction::Shl: {
2313 const APInt *ShAmt;
2314 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002315 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002316 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002317 if (ShAmt->uge(TyBits) || // Bad shift.
2318 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002319 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002320 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002321 }
2322 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002323 }
Chris Lattner965c7692008-06-02 01:18:21 +00002324 case Instruction::And:
2325 case Instruction::Or:
2326 case Instruction::Xor: // NOT is handled here.
2327 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002328 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002329 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002330 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002331 FirstAnswer = std::min(Tmp, Tmp2);
2332 // We computed what we know about the sign bits as our first
2333 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002334 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002335 }
2336 break;
2337
2338 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002339 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002340 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002341 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002342 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002343
Chris Lattner965c7692008-06-02 01:18:21 +00002344 case Instruction::Add:
2345 // Add can have at most one carry bit. Thus we know that the output
2346 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002347 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002348 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002349
Chris Lattner965c7692008-06-02 01:18:21 +00002350 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002351 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002352 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002353 KnownBits Known(TyBits);
2354 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002355
Chris Lattner965c7692008-06-02 01:18:21 +00002356 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2357 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002358 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002359 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002360
Chris Lattner965c7692008-06-02 01:18:21 +00002361 // If we are subtracting one from a positive number, there is no carry
2362 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002363 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002364 return Tmp;
2365 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002366
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002367 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002368 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002369 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002370
Chris Lattner965c7692008-06-02 01:18:21 +00002371 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002372 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002373 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002374
Chris Lattner965c7692008-06-02 01:18:21 +00002375 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002376 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002377 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002378 KnownBits Known(TyBits);
2379 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002380 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2381 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002382 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002383 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002384
Chris Lattner965c7692008-06-02 01:18:21 +00002385 // If the input is known to be positive (the sign bit is known clear),
2386 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002387 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002388 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002389
Chris Lattner965c7692008-06-02 01:18:21 +00002390 // Otherwise, we treat this like a SUB.
2391 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002392
Chris Lattner965c7692008-06-02 01:18:21 +00002393 // Sub can have at most one carry bit. Thus we know that the output
2394 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002395 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002396 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002397 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002398
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002399 case Instruction::Mul: {
2400 // The output of the Mul can be at most twice the valid bits in the inputs.
2401 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2402 if (SignBitsOp0 == 1) return 1; // Early out.
2403 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2404 if (SignBitsOp1 == 1) return 1;
2405 unsigned OutValidBits =
2406 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2407 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2408 }
2409
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002410 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002411 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002412 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002413 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002414 if (NumIncomingValues > 4) break;
2415 // Unreachable blocks may have zero-operand PHI nodes.
2416 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002417
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002418 // Take the minimum of all incoming values. This can't infinitely loop
2419 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002420 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002421 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002422 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002423 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002424 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002425 }
2426 return Tmp;
2427 }
2428
Chris Lattner965c7692008-06-02 01:18:21 +00002429 case Instruction::Trunc:
2430 // FIXME: it's tricky to do anything useful for this, but it is an important
2431 // case for targets like X86.
2432 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002433
2434 case Instruction::ExtractElement:
2435 // Look through extract element. At the moment we keep this simple and skip
2436 // tracking the specific element. But at least we might find information
2437 // valid for all elements of the vector (for example if vector is sign
2438 // extended, shifted, etc).
2439 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002440 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002441
Chris Lattner965c7692008-06-02 01:18:21 +00002442 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2443 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002444
2445 // If we can examine all elements of a vector constant successfully, we're
2446 // done (we can't do any better than that). If not, keep trying.
2447 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2448 return VecSignBits;
2449
Craig Topperb45eabc2017-04-26 16:39:58 +00002450 KnownBits Known(TyBits);
2451 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002452
Sanjay Patele0536212016-06-23 17:41:59 +00002453 // If we know that the sign bit is either zero or one, determine the number of
2454 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002455 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002456}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002457
Sanjay Patelaee84212014-11-04 16:27:42 +00002458/// This function computes the integer multiple of Base that equals V.
2459/// If successful, it returns true and returns the multiple in
2460/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002461/// through SExt instructions only if LookThroughSExt is true.
2462bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002463 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002464 const unsigned MaxDepth = 6;
2465
Dan Gohman6a976bb2009-11-18 00:58:27 +00002466 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002467 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002468 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002469
Chris Lattner229907c2011-07-18 04:54:35 +00002470 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002471
Dan Gohman6a976bb2009-11-18 00:58:27 +00002472 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002473
2474 if (Base == 0)
2475 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002476
Victor Hernandez47444882009-11-10 08:28:35 +00002477 if (Base == 1) {
2478 Multiple = V;
2479 return true;
2480 }
2481
2482 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2483 Constant *BaseVal = ConstantInt::get(T, Base);
2484 if (CO && CO == BaseVal) {
2485 // Multiple is 1.
2486 Multiple = ConstantInt::get(T, 1);
2487 return true;
2488 }
2489
2490 if (CI && CI->getZExtValue() % Base == 0) {
2491 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002492 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002493 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002494
Victor Hernandez47444882009-11-10 08:28:35 +00002495 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002496
Victor Hernandez47444882009-11-10 08:28:35 +00002497 Operator *I = dyn_cast<Operator>(V);
2498 if (!I) return false;
2499
2500 switch (I->getOpcode()) {
2501 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002502 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002503 if (!LookThroughSExt) return false;
2504 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002505 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002506 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002507 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2508 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002509 case Instruction::Shl:
2510 case Instruction::Mul: {
2511 Value *Op0 = I->getOperand(0);
2512 Value *Op1 = I->getOperand(1);
2513
2514 if (I->getOpcode() == Instruction::Shl) {
2515 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2516 if (!Op1CI) return false;
2517 // Turn Op0 << Op1 into Op0 * 2^Op1
2518 APInt Op1Int = Op1CI->getValue();
2519 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002520 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002521 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002522 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002523 }
2524
Craig Topper9f008862014-04-15 04:59:12 +00002525 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002526 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2527 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2528 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002529 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002530 MulC->getType()->getPrimitiveSizeInBits())
2531 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002532 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002533 MulC->getType()->getPrimitiveSizeInBits())
2534 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002535
Chris Lattner72d283c2010-09-05 17:20:46 +00002536 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2537 Multiple = ConstantExpr::getMul(MulC, Op1C);
2538 return true;
2539 }
Victor Hernandez47444882009-11-10 08:28:35 +00002540
2541 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2542 if (Mul0CI->getValue() == 1) {
2543 // V == Base * Op1, so return Op1
2544 Multiple = Op1;
2545 return true;
2546 }
2547 }
2548
Craig Topper9f008862014-04-15 04:59:12 +00002549 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002550 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2551 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2552 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002553 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002554 MulC->getType()->getPrimitiveSizeInBits())
2555 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002556 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002557 MulC->getType()->getPrimitiveSizeInBits())
2558 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002559
Chris Lattner72d283c2010-09-05 17:20:46 +00002560 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2561 Multiple = ConstantExpr::getMul(MulC, Op0C);
2562 return true;
2563 }
Victor Hernandez47444882009-11-10 08:28:35 +00002564
2565 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2566 if (Mul1CI->getValue() == 1) {
2567 // V == Base * Op0, so return Op0
2568 Multiple = Op0;
2569 return true;
2570 }
2571 }
Victor Hernandez47444882009-11-10 08:28:35 +00002572 }
2573 }
2574
2575 // We could not determine if V is a multiple of Base.
2576 return false;
2577}
2578
David Majnemerb4b27232016-04-19 19:10:21 +00002579Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2580 const TargetLibraryInfo *TLI) {
2581 const Function *F = ICS.getCalledFunction();
2582 if (!F)
2583 return Intrinsic::not_intrinsic;
2584
2585 if (F->isIntrinsic())
2586 return F->getIntrinsicID();
2587
2588 if (!TLI)
2589 return Intrinsic::not_intrinsic;
2590
David L. Jonesd21529f2017-01-23 23:16:46 +00002591 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002592 // We're going to make assumptions on the semantics of the functions, check
2593 // that the target knows that it's available in this environment and it does
2594 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002595 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2596 return Intrinsic::not_intrinsic;
2597
2598 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002599 return Intrinsic::not_intrinsic;
2600
2601 // Otherwise check if we have a call to a function that can be turned into a
2602 // vector intrinsic.
2603 switch (Func) {
2604 default:
2605 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002606 case LibFunc_sin:
2607 case LibFunc_sinf:
2608 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002609 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002610 case LibFunc_cos:
2611 case LibFunc_cosf:
2612 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002613 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002614 case LibFunc_exp:
2615 case LibFunc_expf:
2616 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002617 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002618 case LibFunc_exp2:
2619 case LibFunc_exp2f:
2620 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002621 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002622 case LibFunc_log:
2623 case LibFunc_logf:
2624 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002625 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002626 case LibFunc_log10:
2627 case LibFunc_log10f:
2628 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002629 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002630 case LibFunc_log2:
2631 case LibFunc_log2f:
2632 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002633 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002634 case LibFunc_fabs:
2635 case LibFunc_fabsf:
2636 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002637 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002638 case LibFunc_fmin:
2639 case LibFunc_fminf:
2640 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002641 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002642 case LibFunc_fmax:
2643 case LibFunc_fmaxf:
2644 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002645 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002646 case LibFunc_copysign:
2647 case LibFunc_copysignf:
2648 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002649 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002650 case LibFunc_floor:
2651 case LibFunc_floorf:
2652 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002653 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002654 case LibFunc_ceil:
2655 case LibFunc_ceilf:
2656 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002657 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002658 case LibFunc_trunc:
2659 case LibFunc_truncf:
2660 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002661 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002662 case LibFunc_rint:
2663 case LibFunc_rintf:
2664 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002665 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002666 case LibFunc_nearbyint:
2667 case LibFunc_nearbyintf:
2668 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002669 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002670 case LibFunc_round:
2671 case LibFunc_roundf:
2672 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002673 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002674 case LibFunc_pow:
2675 case LibFunc_powf:
2676 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002677 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002678 case LibFunc_sqrt:
2679 case LibFunc_sqrtf:
2680 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002681 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002682 }
2683
2684 return Intrinsic::not_intrinsic;
2685}
2686
Sanjay Patelaee84212014-11-04 16:27:42 +00002687/// Return true if we can prove that the specified FP value is never equal to
2688/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002689///
2690/// NOTE: this function will need to be revisited when we support non-default
2691/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002692bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2693 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002694 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002695 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002696
Sanjay Patel20df88a2017-11-13 17:56:23 +00002697 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002698 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002699 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002700
Sanjay Patel20df88a2017-11-13 17:56:23 +00002701 auto *Op = dyn_cast<Operator>(V);
2702 if (!Op)
2703 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002704
Sanjay Patel20df88a2017-11-13 17:56:23 +00002705 // Check if the nsz fast-math flag is set.
2706 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002707 if (FPO->hasNoSignedZeros())
2708 return true;
2709
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002710 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002711 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002712 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002713
Chris Lattnera12a6de2008-06-02 01:29:46 +00002714 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002715 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002716 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002717
Sanjay Patel20df88a2017-11-13 17:56:23 +00002718 if (auto *Call = dyn_cast<CallInst>(Op)) {
2719 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002720 switch (IID) {
2721 default:
2722 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002723 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002724 case Intrinsic::sqrt:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002725 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002726 // fabs(x) != -0.0
2727 case Intrinsic::fabs:
2728 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002729 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002730 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002731
Chris Lattnera12a6de2008-06-02 01:29:46 +00002732 return false;
2733}
2734
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002735/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2736/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2737/// bit despite comparing equal.
2738static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2739 const TargetLibraryInfo *TLI,
2740 bool SignBitOnly,
2741 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002742 // TODO: This function does not do the right thing when SignBitOnly is true
2743 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2744 // which flips the sign bits of NaNs. See
2745 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2746
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002747 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2748 return !CFP->getValueAPF().isNegative() ||
2749 (!SignBitOnly && CFP->getValueAPF().isZero());
2750 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002751
Craig Topper69c89722018-02-26 22:33:17 +00002752 // Handle vector of constants.
2753 if (auto *CV = dyn_cast<Constant>(V)) {
2754 if (CV->getType()->isVectorTy()) {
2755 unsigned NumElts = CV->getType()->getVectorNumElements();
2756 for (unsigned i = 0; i != NumElts; ++i) {
2757 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2758 if (!CFP)
2759 return false;
2760 if (CFP->getValueAPF().isNegative() &&
2761 (SignBitOnly || !CFP->getValueAPF().isZero()))
2762 return false;
2763 }
2764
2765 // All non-negative ConstantFPs.
2766 return true;
2767 }
2768 }
2769
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002770 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002771 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002772
2773 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002774 if (!I)
2775 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002776
2777 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002778 default:
2779 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002780 // Unsigned integers are always nonnegative.
2781 case Instruction::UIToFP:
2782 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002783 case Instruction::FMul:
2784 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002785 if (I->getOperand(0) == I->getOperand(1) &&
2786 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002787 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002788
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002789 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002790 case Instruction::FAdd:
2791 case Instruction::FDiv:
2792 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002793 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2794 Depth + 1) &&
2795 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2796 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002797 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002798 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2799 Depth + 1) &&
2800 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2801 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002802 case Instruction::FPExt:
2803 case Instruction::FPTrunc:
2804 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002805 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2806 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002807 case Instruction::ExtractElement:
2808 // Look through extract element. At the moment we keep this simple and skip
2809 // tracking the specific element. But at least we might find information
2810 // valid for all elements of the vector.
2811 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2812 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002813 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002814 const auto *CI = cast<CallInst>(I);
2815 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002816 switch (IID) {
2817 default:
2818 break;
2819 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002820 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2821 Depth + 1) ||
2822 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2823 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002824 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002825 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2826 Depth + 1) &&
2827 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2828 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002829 case Intrinsic::exp:
2830 case Intrinsic::exp2:
2831 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002832 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002833
2834 case Intrinsic::sqrt:
2835 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2836 if (!SignBitOnly)
2837 return true;
2838 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2839 CannotBeNegativeZero(CI->getOperand(0), TLI));
2840
David Majnemer3ee5f342016-04-13 06:55:52 +00002841 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002842 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002843 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002844 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002845 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002846 }
Justin Lebar322c1272017-01-27 00:58:34 +00002847 // TODO: This is not correct. Given that exp is an integer, here are the
2848 // ways that pow can return a negative value:
2849 //
2850 // pow(x, exp) --> negative if exp is odd and x is negative.
2851 // pow(-0, exp) --> -inf if exp is negative odd.
2852 // pow(-0, exp) --> -0 if exp is positive odd.
2853 // pow(-inf, exp) --> -0 if exp is negative odd.
2854 // pow(-inf, exp) --> -inf if exp is positive odd.
2855 //
2856 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2857 // but we must return false if x == -0. Unfortunately we do not currently
2858 // have a way of expressing this constraint. See details in
2859 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002860 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2861 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002862
David Majnemer3ee5f342016-04-13 06:55:52 +00002863 case Intrinsic::fma:
2864 case Intrinsic::fmuladd:
2865 // x*x+y is non-negative if y is non-negative.
2866 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002867 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2868 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2869 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002870 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002871 break;
2872 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002873 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002874}
2875
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002876bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2877 const TargetLibraryInfo *TLI) {
2878 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2879}
2880
2881bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2882 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2883}
2884
Sanjay Patel6840c5f2017-09-05 23:13:13 +00002885bool llvm::isKnownNeverNaN(const Value *V) {
2886 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
2887
2888 // If we're told that NaNs won't happen, assume they won't.
2889 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
2890 if (FPMathOp->hasNoNaNs())
2891 return true;
2892
2893 // TODO: Handle instructions and potentially recurse like other 'isKnown'
2894 // functions. For example, the result of sitofp is never NaN.
2895
2896 // Handle scalar constants.
2897 if (auto *CFP = dyn_cast<ConstantFP>(V))
2898 return !CFP->isNaN();
2899
2900 // Bail out for constant expressions, but try to handle vector constants.
2901 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
2902 return false;
2903
2904 // For vectors, verify that each element is not NaN.
2905 unsigned NumElts = V->getType()->getVectorNumElements();
2906 for (unsigned i = 0; i != NumElts; ++i) {
2907 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
2908 if (!Elt)
2909 return false;
2910 if (isa<UndefValue>(Elt))
2911 continue;
2912 auto *CElt = dyn_cast<ConstantFP>(Elt);
2913 if (!CElt || CElt->isNaN())
2914 return false;
2915 }
2916 // All elements were confirmed not-NaN or undefined.
2917 return true;
2918}
2919
Sanjay Patelaee84212014-11-04 16:27:42 +00002920/// If the specified value can be set by repeating the same byte in memory,
2921/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002922/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2923/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2924/// byte store (e.g. i16 0x1234), return null.
2925Value *llvm::isBytewiseValue(Value *V) {
2926 // All byte-wide stores are splatable, even of arbitrary variables.
2927 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002928
2929 // Handle 'null' ConstantArrayZero etc.
2930 if (Constant *C = dyn_cast<Constant>(V))
2931 if (C->isNullValue())
2932 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002933
Chris Lattner9cb10352010-12-26 20:15:01 +00002934 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002935 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002936 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2937 if (CFP->getType()->isFloatTy())
2938 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2939 if (CFP->getType()->isDoubleTy())
2940 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2941 // Don't handle long double formats, which have strange constraints.
2942 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002943
Benjamin Kramer17d90152015-02-07 19:29:02 +00002944 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002945 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002946 if (CI->getBitWidth() % 8 == 0) {
2947 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002948
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002949 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002950 return nullptr;
2951 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002952 }
2953 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002954
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002955 // A ConstantDataArray/Vector is splatable if all its members are equal and
2956 // also splatable.
2957 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2958 Value *Elt = CA->getElementAsConstant(0);
2959 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002960 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002961 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002962
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002963 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2964 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002965 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002966
Chris Lattner9cb10352010-12-26 20:15:01 +00002967 return Val;
2968 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002969
Chris Lattner9cb10352010-12-26 20:15:01 +00002970 // Conceptually, we could handle things like:
2971 // %a = zext i8 %X to i16
2972 // %b = shl i16 %a, 8
2973 // %c = or i16 %a, %b
2974 // but until there is an example that actually needs this, it doesn't seem
2975 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002976 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002977}
2978
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002979// This is the recursive version of BuildSubAggregate. It takes a few different
2980// arguments. Idxs is the index within the nested struct From that we are
2981// looking at now (which is of type IndexedType). IdxSkip is the number of
2982// indices from Idxs that should be left out when inserting into the resulting
2983// struct. To is the result struct built so far, new insertvalue instructions
2984// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002985static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002986 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002987 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002988 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002989 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002990 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002991 // Save the original To argument so we can modify it
2992 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002993 // General case, the type indexed by Idxs is a struct
2994 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2995 // Process each struct element recursively
2996 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002997 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002998 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002999 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003000 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003001 if (!To) {
3002 // Couldn't find any inserted value for this index? Cleanup
3003 while (PrevTo != OrigTo) {
3004 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3005 PrevTo = Del->getAggregateOperand();
3006 Del->eraseFromParent();
3007 }
3008 // Stop processing elements
3009 break;
3010 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003011 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003012 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003013 if (To)
3014 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003015 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003016 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3017 // the struct's elements had a value that was inserted directly. In the latter
3018 // case, perhaps we can't determine each of the subelements individually, but
3019 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003020
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003021 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003022 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003023
3024 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003025 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003026
Vedant Kumard3196742018-02-28 19:08:52 +00003027 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003028 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3029 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003030}
3031
3032// This helper takes a nested struct and extracts a part of it (which is again a
3033// struct) into a new value. For example, given the struct:
3034// { a, { b, { c, d }, e } }
3035// and the indices "1, 1" this returns
3036// { c, d }.
3037//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003038// It does this by inserting an insertvalue for each element in the resulting
3039// struct, as opposed to just inserting a single struct. This will only work if
3040// each of the elements of the substruct are known (ie, inserted into From by an
3041// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003042//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003043// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003044static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003045 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003046 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003047 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003048 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003049 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003050 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003051 unsigned IdxSkip = Idxs.size();
3052
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003053 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003054}
3055
Vedant Kumard3196742018-02-28 19:08:52 +00003056/// Given an aggregate and a sequence of indices, see if the scalar value
3057/// indexed is already around as a register, for example if it was inserted
3058/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003059///
3060/// If InsertBefore is not null, this function will duplicate (modified)
3061/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003062Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3063 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003064 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003065 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003066 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003067 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003068 // We have indices, so V should have an indexable type.
3069 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3070 "Not looking at a struct or array?");
3071 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3072 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003073
Chris Lattner67058832012-01-25 06:48:06 +00003074 if (Constant *C = dyn_cast<Constant>(V)) {
3075 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003076 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003077 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3078 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003079
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003080 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003081 // Loop the indices for the insertvalue instruction in parallel with the
3082 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003083 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003084 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3085 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003086 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003087 // We can't handle this without inserting insertvalues
3088 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003089 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003090
3091 // The requested index identifies a part of a nested aggregate. Handle
3092 // this specially. For example,
3093 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3094 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3095 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3096 // This can be changed into
3097 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3098 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3099 // which allows the unused 0,0 element from the nested struct to be
3100 // removed.
3101 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3102 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003103 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003104
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003105 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003106 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003107 // looking for, then.
3108 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003109 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003110 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003111 }
3112 // If we end up here, the indices of the insertvalue match with those
3113 // requested (though possibly only partially). Now we recursively look at
3114 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003115 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003116 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003117 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003118 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003119
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003120 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003121 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003122 // something else, we can extract from that something else directly instead.
3123 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003124
3125 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003126 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003127 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003128 SmallVector<unsigned, 5> Idxs;
3129 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003130 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003131 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003132
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003133 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003134 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003135
Craig Topper1bef2c82012-12-22 19:15:35 +00003136 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003137 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003138
Jay Foad57aa6362011-07-13 10:26:04 +00003139 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003140 }
3141 // Otherwise, we don't know (such as, extracting from a function return value
3142 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003143 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003144}
Evan Chengda3db112008-06-30 07:31:25 +00003145
Sanjay Patelaee84212014-11-04 16:27:42 +00003146/// Analyze the specified pointer to see if it can be expressed as a base
3147/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003148Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003149 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003150 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003151 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003152
3153 // We walk up the defs but use a visited set to handle unreachable code. In
3154 // that case, we stop after accumulating the cycle once (not that it
3155 // matters).
3156 SmallPtrSet<Value *, 16> Visited;
3157 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003158 if (Ptr->getType()->isVectorTy())
3159 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003160
Nuno Lopes368c4d02012-12-31 20:48:35 +00003161 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003162 // If one of the values we have visited is an addrspacecast, then
3163 // the pointer type of this GEP may be different from the type
3164 // of the Ptr parameter which was passed to this function. This
3165 // means when we construct GEPOffset, we need to use the size
3166 // of GEP's pointer type rather than the size of the original
3167 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003168 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003169 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3170 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003171
Tom Stellard17eb3412016-10-07 14:23:29 +00003172 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003173
Nuno Lopes368c4d02012-12-31 20:48:35 +00003174 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003175 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3176 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003177 Ptr = cast<Operator>(Ptr)->getOperand(0);
3178 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003179 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003180 break;
3181 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003182 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003183 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003184 }
3185 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003186 Offset = ByteOffset.getSExtValue();
3187 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003188}
3189
Matthias Braun50ec0b52017-05-19 22:37:09 +00003190bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3191 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003192 // Make sure the GEP has exactly three arguments.
3193 if (GEP->getNumOperands() != 3)
3194 return false;
3195
Matthias Braun50ec0b52017-05-19 22:37:09 +00003196 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3197 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003198 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003199 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003200 return false;
3201
3202 // Check to make sure that the first operand of the GEP is an integer and
3203 // has value 0 so that we are sure we're indexing into the initializer.
3204 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3205 if (!FirstIdx || !FirstIdx->isZero())
3206 return false;
3207
3208 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003209}
Chris Lattnere28618d2010-11-30 22:25:26 +00003210
Matthias Braun50ec0b52017-05-19 22:37:09 +00003211bool llvm::getConstantDataArrayInfo(const Value *V,
3212 ConstantDataArraySlice &Slice,
3213 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003214 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003215
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003216 // Look through bitcast instructions and geps.
3217 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003218
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003219 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003220 // offset.
3221 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003222 // The GEP operator should be based on a pointer to string constant, and is
3223 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003224 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003225 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003226
Evan Chengda3db112008-06-30 07:31:25 +00003227 // If the second index isn't a ConstantInt, then this is a variable index
3228 // into the array. If this occurs, we can't say anything meaningful about
3229 // the string.
3230 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003231 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003232 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003233 else
3234 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003235 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3236 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003237 }
Nick Lewycky46209882011-10-20 00:34:35 +00003238
Evan Chengda3db112008-06-30 07:31:25 +00003239 // The GEP instruction, constant or instruction, must reference a global
3240 // variable that is a constant and is initialized. The referenced constant
3241 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003242 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003243 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003244 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003245
Matthias Braun50ec0b52017-05-19 22:37:09 +00003246 const ConstantDataArray *Array;
3247 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003248 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003249 Type *GVTy = GV->getValueType();
3250 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003251 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003252 Array = nullptr;
3253 } else {
3254 const DataLayout &DL = GV->getParent()->getDataLayout();
3255 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3256 uint64_t Length = SizeInBytes / (ElementSize / 8);
3257 if (Length <= Offset)
3258 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003259
Matthias Braun50ec0b52017-05-19 22:37:09 +00003260 Slice.Array = nullptr;
3261 Slice.Offset = 0;
3262 Slice.Length = Length - Offset;
3263 return true;
3264 }
3265 } else {
3266 // This must be a ConstantDataArray.
3267 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3268 if (!Array)
3269 return false;
3270 ArrayTy = Array->getType();
3271 }
3272 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003273 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003274
Matthias Braun50ec0b52017-05-19 22:37:09 +00003275 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003276 if (Offset > NumElts)
3277 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003278
Matthias Braun50ec0b52017-05-19 22:37:09 +00003279 Slice.Array = Array;
3280 Slice.Offset = Offset;
3281 Slice.Length = NumElts - Offset;
3282 return true;
3283}
3284
3285/// This function computes the length of a null-terminated C string pointed to
3286/// by V. If successful, it returns true and returns the string in Str.
3287/// If unsuccessful, it returns false.
3288bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3289 uint64_t Offset, bool TrimAtNul) {
3290 ConstantDataArraySlice Slice;
3291 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3292 return false;
3293
3294 if (Slice.Array == nullptr) {
3295 if (TrimAtNul) {
3296 Str = StringRef();
3297 return true;
3298 }
3299 if (Slice.Length == 1) {
3300 Str = StringRef("", 1);
3301 return true;
3302 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003303 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003304 // of 0s at hand.
3305 return false;
3306 }
3307
3308 // Start out with the entire array in the StringRef.
3309 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003310 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003311 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003312
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003313 if (TrimAtNul) {
3314 // Trim off the \0 and anything after it. If the array is not nul
3315 // terminated, we just return the whole end of string. The client may know
3316 // some other way that the string is length-bound.
3317 Str = Str.substr(0, Str.find('\0'));
3318 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003319 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003320}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003321
3322// These next two are very similar to the above, but also look through PHI
3323// nodes.
3324// TODO: See if we can integrate these two together.
3325
Sanjay Patelaee84212014-11-04 16:27:42 +00003326/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003327/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003328static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003329 SmallPtrSetImpl<const PHINode*> &PHIs,
3330 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003331 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003332 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003333
3334 // If this is a PHI node, there are two cases: either we have already seen it
3335 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003336 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003337 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003338 return ~0ULL; // already in the set.
3339
3340 // If it was new, see if all the input strings are the same length.
3341 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003342 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003343 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003344 if (Len == 0) return 0; // Unknown length -> unknown.
3345
3346 if (Len == ~0ULL) continue;
3347
3348 if (Len != LenSoFar && LenSoFar != ~0ULL)
3349 return 0; // Disagree -> unknown.
3350 LenSoFar = Len;
3351 }
3352
3353 // Success, all agree.
3354 return LenSoFar;
3355 }
3356
3357 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003358 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003359 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003360 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003361 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003362 if (Len2 == 0) return 0;
3363 if (Len1 == ~0ULL) return Len2;
3364 if (Len2 == ~0ULL) return Len1;
3365 if (Len1 != Len2) return 0;
3366 return Len1;
3367 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003368
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003369 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003370 ConstantDataArraySlice Slice;
3371 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003372 return 0;
3373
Matthias Braun50ec0b52017-05-19 22:37:09 +00003374 if (Slice.Array == nullptr)
3375 return 1;
3376
3377 // Search for nul characters
3378 unsigned NullIndex = 0;
3379 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3380 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3381 break;
3382 }
3383
3384 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003385}
3386
Sanjay Patelaee84212014-11-04 16:27:42 +00003387/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003388/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003389uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003390 if (!V->getType()->isPointerTy())
3391 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003392
Pete Cooper35b00d52016-08-13 01:05:32 +00003393 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003394 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003395 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3396 // an empty string as a length.
3397 return Len == ~0ULL ? 1 : Len;
3398}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003399
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003400const Value *llvm::getArgumentAliasingToReturnedPointer(ImmutableCallSite CS) {
3401 assert(CS &&
3402 "getArgumentAliasingToReturnedPointer only works on nonnull CallSite");
3403 if (const Value *RV = CS.getReturnedArgOperand())
3404 return RV;
3405 // This can be used only as a aliasing property.
3406 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CS))
3407 return CS.getArgOperand(0);
3408 return nullptr;
3409}
3410
3411bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003412 ImmutableCallSite CS) {
3413 return CS.getIntrinsicID() == Intrinsic::launder_invariant_group ||
3414 CS.getIntrinsicID() == Intrinsic::strip_invariant_group;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003415}
3416
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003417/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003418/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003419static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3420 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003421 // Find the loop-defined value.
3422 Loop *L = LI->getLoopFor(PN->getParent());
3423 if (PN->getNumIncomingValues() != 2)
3424 return true;
3425
3426 // Find the value from previous iteration.
3427 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3428 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3429 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3430 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3431 return true;
3432
3433 // If a new pointer is loaded in the loop, the pointer references a different
3434 // object in every iteration. E.g.:
3435 // for (i)
3436 // int *p = a[i];
3437 // ...
3438 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3439 if (!L->isLoopInvariant(Load->getPointerOperand()))
3440 return false;
3441 return true;
3442}
3443
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003444Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3445 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003446 if (!V->getType()->isPointerTy())
3447 return V;
3448 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3449 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3450 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003451 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3452 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003453 V = cast<Operator>(V)->getOperand(0);
3454 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003455 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003456 return V;
3457 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003458 } else if (isa<AllocaInst>(V)) {
3459 // An alloca can't be further simplified.
3460 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003461 } else {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003462 if (auto CS = CallSite(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003463 // CaptureTracking can know about special capturing properties of some
3464 // intrinsics like launder.invariant.group, that can't be expressed with
3465 // the attributes, but have properties like returning aliasing pointer.
3466 // Because some analysis may assume that nocaptured pointer is not
3467 // returned from some special intrinsic (because function would have to
3468 // be marked with returns attribute), it is crucial to use this function
3469 // because it should be in sync with CaptureTracking. Not using it may
3470 // cause weird miscompilations where 2 aliasing pointers are assumed to
3471 // noalias.
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003472 if (auto *RP = getArgumentAliasingToReturnedPointer(CS)) {
3473 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003474 continue;
3475 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003476 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003477
Dan Gohman05b18f12010-12-15 20:49:55 +00003478 // See if InstructionSimplify knows any relevant tricks.
3479 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003480 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003481 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003482 V = Simplified;
3483 continue;
3484 }
3485
Dan Gohmana4fcd242010-12-15 20:02:24 +00003486 return V;
3487 }
3488 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3489 }
3490 return V;
3491}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003492
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003493void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003494 const DataLayout &DL, LoopInfo *LI,
3495 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003496 SmallPtrSet<Value *, 4> Visited;
3497 SmallVector<Value *, 4> Worklist;
3498 Worklist.push_back(V);
3499 do {
3500 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003501 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003502
David Blaikie70573dc2014-11-19 07:49:26 +00003503 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003504 continue;
3505
3506 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3507 Worklist.push_back(SI->getTrueValue());
3508 Worklist.push_back(SI->getFalseValue());
3509 continue;
3510 }
3511
3512 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003513 // If this PHI changes the underlying object in every iteration of the
3514 // loop, don't look through it. Consider:
3515 // int **A;
3516 // for (i) {
3517 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3518 // Curr = A[i];
3519 // *Prev, *Curr;
3520 //
3521 // Prev is tracking Curr one iteration behind so they refer to different
3522 // underlying objects.
3523 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3524 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003525 for (Value *IncValue : PN->incoming_values())
3526 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003527 continue;
3528 }
3529
3530 Objects.push_back(P);
3531 } while (!Worklist.empty());
3532}
3533
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003534/// This is the function that does the work of looking through basic
3535/// ptrtoint+arithmetic+inttoptr sequences.
3536static const Value *getUnderlyingObjectFromInt(const Value *V) {
3537 do {
3538 if (const Operator *U = dyn_cast<Operator>(V)) {
3539 // If we find a ptrtoint, we can transfer control back to the
3540 // regular getUnderlyingObjectFromInt.
3541 if (U->getOpcode() == Instruction::PtrToInt)
3542 return U->getOperand(0);
3543 // If we find an add of a constant, a multiplied value, or a phi, it's
3544 // likely that the other operand will lead us to the base
3545 // object. We don't have to worry about the case where the
3546 // object address is somehow being computed by the multiply,
3547 // because our callers only care when the result is an
3548 // identifiable object.
3549 if (U->getOpcode() != Instruction::Add ||
3550 (!isa<ConstantInt>(U->getOperand(1)) &&
3551 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3552 !isa<PHINode>(U->getOperand(1))))
3553 return V;
3554 V = U->getOperand(0);
3555 } else {
3556 return V;
3557 }
3558 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3559 } while (true);
3560}
3561
3562/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3563/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003564/// It returns false if unidentified object is found in GetUnderlyingObjects.
3565bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003566 SmallVectorImpl<Value *> &Objects,
3567 const DataLayout &DL) {
3568 SmallPtrSet<const Value *, 16> Visited;
3569 SmallVector<const Value *, 4> Working(1, V);
3570 do {
3571 V = Working.pop_back_val();
3572
3573 SmallVector<Value *, 4> Objs;
3574 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3575
3576 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003577 if (!Visited.insert(V).second)
3578 continue;
3579 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3580 const Value *O =
3581 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3582 if (O->getType()->isPointerTy()) {
3583 Working.push_back(O);
3584 continue;
3585 }
3586 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003587 // If GetUnderlyingObjects fails to find an identifiable object,
3588 // getUnderlyingObjectsForCodeGen also fails for safety.
3589 if (!isIdentifiedObject(V)) {
3590 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003591 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003592 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003593 Objects.push_back(const_cast<Value *>(V));
3594 }
3595 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003596 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003597}
3598
Sanjay Patelaee84212014-11-04 16:27:42 +00003599/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003600bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003601 for (const User *U : V->users()) {
3602 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003603 if (!II) return false;
3604
3605 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3606 II->getIntrinsicID() != Intrinsic::lifetime_end)
3607 return false;
3608 }
3609 return true;
3610}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003611
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003612bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3613 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003614 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003615 const Operator *Inst = dyn_cast<Operator>(V);
3616 if (!Inst)
3617 return false;
3618
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003619 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3620 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3621 if (C->canTrap())
3622 return false;
3623
3624 switch (Inst->getOpcode()) {
3625 default:
3626 return true;
3627 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003628 case Instruction::URem: {
3629 // x / y is undefined if y == 0.
3630 const APInt *V;
3631 if (match(Inst->getOperand(1), m_APInt(V)))
3632 return *V != 0;
3633 return false;
3634 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003635 case Instruction::SDiv:
3636 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003637 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003638 const APInt *Numerator, *Denominator;
3639 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3640 return false;
3641 // We cannot hoist this division if the denominator is 0.
3642 if (*Denominator == 0)
3643 return false;
3644 // It's safe to hoist if the denominator is not 0 or -1.
3645 if (*Denominator != -1)
3646 return true;
3647 // At this point we know that the denominator is -1. It is safe to hoist as
3648 // long we know that the numerator is not INT_MIN.
3649 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3650 return !Numerator->isMinSignedValue();
3651 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003652 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003653 }
3654 case Instruction::Load: {
3655 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003656 if (!LI->isUnordered() ||
3657 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003658 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003659 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003660 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3661 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003662 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003663 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003664 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3665 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003666 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003667 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003668 auto *CI = cast<const CallInst>(Inst);
3669 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003670
Matt Arsenault6a288c12017-05-03 02:26:10 +00003671 // The called function could have undefined behavior or side-effects, even
3672 // if marked readnone nounwind.
3673 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003674 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003675 case Instruction::VAArg:
3676 case Instruction::Alloca:
3677 case Instruction::Invoke:
3678 case Instruction::PHI:
3679 case Instruction::Store:
3680 case Instruction::Ret:
3681 case Instruction::Br:
3682 case Instruction::IndirectBr:
3683 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003684 case Instruction::Unreachable:
3685 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003686 case Instruction::AtomicRMW:
3687 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003688 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003689 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003690 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003691 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003692 case Instruction::CatchRet:
3693 case Instruction::CleanupPad:
3694 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003695 return false; // Misc instructions which have effects
3696 }
3697}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003698
Quentin Colombet6443cce2015-08-06 18:44:34 +00003699bool llvm::mayBeMemoryDependent(const Instruction &I) {
3700 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3701}
3702
Pete Cooper35b00d52016-08-13 01:05:32 +00003703OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3704 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003705 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003706 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003707 const Instruction *CxtI,
3708 const DominatorTree *DT) {
3709 // Multiplying n * m significant bits yields a result of n + m significant
3710 // bits. If the total number of significant bits does not exceed the
3711 // result bit width (minus 1), there is no overflow.
3712 // This means if we have enough leading zero bits in the operands
3713 // we can guarantee that the result does not overflow.
3714 // Ref: "Hacker's Delight" by Henry Warren
3715 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003716 KnownBits LHSKnown(BitWidth);
3717 KnownBits RHSKnown(BitWidth);
3718 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3719 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003720 // Note that underestimating the number of zero bits gives a more
3721 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003722 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3723 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003724 // First handle the easy case: if we have enough zero bits there's
3725 // definitely no overflow.
3726 if (ZeroBits >= BitWidth)
3727 return OverflowResult::NeverOverflows;
3728
3729 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003730 APInt LHSMax = ~LHSKnown.Zero;
3731 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003732
3733 // We know the multiply operation doesn't overflow if the maximum values for
3734 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003735 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003736 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003737 if (!MaxOverflow)
3738 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003739
David Majnemerc8a576b2015-01-02 07:29:47 +00003740 // We know it always overflows if multiplying the smallest possible values for
3741 // the operands also results in overflow.
3742 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003743 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003744 if (MinOverflow)
3745 return OverflowResult::AlwaysOverflows;
3746
3747 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003748}
David Majnemer5310c1e2015-01-07 00:39:50 +00003749
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00003750OverflowResult llvm::computeOverflowForSignedMul(const Value *LHS,
3751 const Value *RHS,
3752 const DataLayout &DL,
3753 AssumptionCache *AC,
3754 const Instruction *CxtI,
3755 const DominatorTree *DT) {
3756 // Multiplying n * m significant bits yields a result of n + m significant
3757 // bits. If the total number of significant bits does not exceed the
3758 // result bit width (minus 1), there is no overflow.
3759 // This means if we have enough leading sign bits in the operands
3760 // we can guarantee that the result does not overflow.
3761 // Ref: "Hacker's Delight" by Henry Warren
3762 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3763
3764 // Note that underestimating the number of sign bits gives a more
3765 // conservative answer.
3766 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
3767 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
3768
3769 // First handle the easy case: if we have enough sign bits there's
3770 // definitely no overflow.
3771 if (SignBits > BitWidth + 1)
3772 return OverflowResult::NeverOverflows;
3773
3774 // There are two ambiguous cases where there can be no overflow:
3775 // SignBits == BitWidth + 1 and
3776 // SignBits == BitWidth
3777 // The second case is difficult to check, therefore we only handle the
3778 // first case.
3779 if (SignBits == BitWidth + 1) {
3780 // It overflows only when both arguments are negative and the true
3781 // product is exactly the minimum negative number.
3782 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
3783 // For simplicity we just check if at least one side is not negative.
3784 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3785 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
3786 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
3787 return OverflowResult::NeverOverflows;
3788 }
3789 return OverflowResult::MayOverflow;
3790}
3791
Pete Cooper35b00d52016-08-13 01:05:32 +00003792OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3793 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003794 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003795 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003796 const Instruction *CxtI,
3797 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003798 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3799 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3800 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003801
Craig Topper6e11a052017-05-08 16:22:48 +00003802 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003803 // The sign bit is set in both cases: this MUST overflow.
3804 // Create a simple add instruction, and insert it into the struct.
3805 return OverflowResult::AlwaysOverflows;
3806 }
3807
Craig Topper6e11a052017-05-08 16:22:48 +00003808 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003809 // The sign bit is clear in both cases: this CANNOT overflow.
3810 // Create a simple add instruction, and insert it into the struct.
3811 return OverflowResult::NeverOverflows;
3812 }
3813 }
3814
3815 return OverflowResult::MayOverflow;
3816}
James Molloy71b91c22015-05-11 14:42:20 +00003817
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003818/// Return true if we can prove that adding the two values of the
Craig Topperbb973722017-05-15 02:44:08 +00003819/// knownbits will not overflow.
3820/// Otherwise return false.
3821static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3822 const KnownBits &RHSKnown) {
3823 // Addition of two 2's complement numbers having opposite signs will never
3824 // overflow.
3825 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3826 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3827 return true;
3828
3829 // If either of the values is known to be non-negative, adding them can only
3830 // overflow if the second is also non-negative, so we can assume that.
3831 // Two non-negative numbers will only overflow if there is a carry to the
3832 // sign bit, so we can check if even when the values are as big as possible
3833 // there is no overflow to the sign bit.
3834 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3835 APInt MaxLHS = ~LHSKnown.Zero;
3836 MaxLHS.clearSignBit();
3837 APInt MaxRHS = ~RHSKnown.Zero;
3838 MaxRHS.clearSignBit();
3839 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3840 return Result.isSignBitClear();
3841 }
3842
3843 // If either of the values is known to be negative, adding them can only
3844 // overflow if the second is also negative, so we can assume that.
3845 // Two negative number will only overflow if there is no carry to the sign
3846 // bit, so we can check if even when the values are as small as possible
3847 // there is overflow to the sign bit.
3848 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3849 APInt MinLHS = LHSKnown.One;
3850 MinLHS.clearSignBit();
3851 APInt MinRHS = RHSKnown.One;
3852 MinRHS.clearSignBit();
3853 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3854 return Result.isSignBitSet();
3855 }
3856
3857 // If we reached here it means that we know nothing about the sign bits.
3858 // In this case we can't know if there will be an overflow, since by
3859 // changing the sign bits any two values can be made to overflow.
3860 return false;
3861}
3862
Pete Cooper35b00d52016-08-13 01:05:32 +00003863static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3864 const Value *RHS,
3865 const AddOperator *Add,
3866 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003867 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003868 const Instruction *CxtI,
3869 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003870 if (Add && Add->hasNoSignedWrap()) {
3871 return OverflowResult::NeverOverflows;
3872 }
3873
Craig Topperbb973722017-05-15 02:44:08 +00003874 // If LHS and RHS each have at least two sign bits, the addition will look
3875 // like
3876 //
3877 // XX..... +
3878 // YY.....
3879 //
3880 // If the carry into the most significant position is 0, X and Y can't both
3881 // be 1 and therefore the carry out of the addition is also 0.
3882 //
3883 // If the carry into the most significant position is 1, X and Y can't both
3884 // be 0 and therefore the carry out of the addition is also 1.
3885 //
3886 // Since the carry into the most significant position is always equal to
3887 // the carry out of the addition, there is no signed overflow.
3888 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3889 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3890 return OverflowResult::NeverOverflows;
3891
Craig Topper6e11a052017-05-08 16:22:48 +00003892 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3893 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003894
Craig Topperbb973722017-05-15 02:44:08 +00003895 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003896 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003897
3898 // The remaining code needs Add to be available. Early returns if not so.
3899 if (!Add)
3900 return OverflowResult::MayOverflow;
3901
3902 // If the sign of Add is the same as at least one of the operands, this add
3903 // CANNOT overflow. This is particularly useful when the sum is
3904 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3905 // operands.
3906 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003907 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003908 bool LHSOrRHSKnownNegative =
3909 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003910 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003911 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3912 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3913 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003914 return OverflowResult::NeverOverflows;
3915 }
3916 }
3917
3918 return OverflowResult::MayOverflow;
3919}
3920
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00003921OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
3922 const Value *RHS,
3923 const DataLayout &DL,
3924 AssumptionCache *AC,
3925 const Instruction *CxtI,
3926 const DominatorTree *DT) {
3927 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
3928 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3929 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
3930 if (LHSKnown.isNegative() && RHSKnown.isNonNegative())
3931 return OverflowResult::NeverOverflows;
3932
3933 return OverflowResult::MayOverflow;
3934}
3935
3936OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
3937 const Value *RHS,
3938 const DataLayout &DL,
3939 AssumptionCache *AC,
3940 const Instruction *CxtI,
3941 const DominatorTree *DT) {
3942 // If LHS and RHS each have at least two sign bits, the subtraction
3943 // cannot overflow.
3944 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3945 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3946 return OverflowResult::NeverOverflows;
3947
3948 KnownBits LHSKnown = computeKnownBits(LHS, DL, 0, AC, CxtI, DT);
3949
3950 KnownBits RHSKnown = computeKnownBits(RHS, DL, 0, AC, CxtI, DT);
3951
3952 // Subtraction of two 2's complement numbers having identical signs will
3953 // never overflow.
3954 if ((LHSKnown.isNegative() && RHSKnown.isNegative()) ||
3955 (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()))
3956 return OverflowResult::NeverOverflows;
3957
3958 // TODO: implement logic similar to checkRippleForAdd
3959 return OverflowResult::MayOverflow;
3960}
3961
Pete Cooper35b00d52016-08-13 01:05:32 +00003962bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3963 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003964#ifndef NDEBUG
3965 auto IID = II->getIntrinsicID();
3966 assert((IID == Intrinsic::sadd_with_overflow ||
3967 IID == Intrinsic::uadd_with_overflow ||
3968 IID == Intrinsic::ssub_with_overflow ||
3969 IID == Intrinsic::usub_with_overflow ||
3970 IID == Intrinsic::smul_with_overflow ||
3971 IID == Intrinsic::umul_with_overflow) &&
3972 "Not an overflow intrinsic!");
3973#endif
3974
Pete Cooper35b00d52016-08-13 01:05:32 +00003975 SmallVector<const BranchInst *, 2> GuardingBranches;
3976 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003977
Pete Cooper35b00d52016-08-13 01:05:32 +00003978 for (const User *U : II->users()) {
3979 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003980 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3981
3982 if (EVI->getIndices()[0] == 0)
3983 Results.push_back(EVI);
3984 else {
3985 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3986
Pete Cooper35b00d52016-08-13 01:05:32 +00003987 for (const auto *U : EVI->users())
3988 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003989 assert(B->isConditional() && "How else is it using an i1?");
3990 GuardingBranches.push_back(B);
3991 }
3992 }
3993 } else {
3994 // We are using the aggregate directly in a way we don't want to analyze
3995 // here (storing it to a global, say).
3996 return false;
3997 }
3998 }
3999
Pete Cooper35b00d52016-08-13 01:05:32 +00004000 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004001 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4002 if (!NoWrapEdge.isSingleEdge())
4003 return false;
4004
4005 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004006 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004007 // If the extractvalue itself is not executed on overflow, the we don't
4008 // need to check each use separately, since domination is transitive.
4009 if (DT.dominates(NoWrapEdge, Result->getParent()))
4010 continue;
4011
4012 for (auto &RU : Result->uses())
4013 if (!DT.dominates(NoWrapEdge, RU))
4014 return false;
4015 }
4016
4017 return true;
4018 };
4019
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004020 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004021}
4022
4023
Pete Cooper35b00d52016-08-13 01:05:32 +00004024OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004025 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004026 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004027 const Instruction *CxtI,
4028 const DominatorTree *DT) {
4029 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004030 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004031}
4032
Pete Cooper35b00d52016-08-13 01:05:32 +00004033OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4034 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004035 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004036 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004037 const Instruction *CxtI,
4038 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004039 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004040}
4041
Jingyue Wu42f1d672015-07-28 18:22:40 +00004042bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004043 // A memory operation returns normally if it isn't volatile. A volatile
4044 // operation is allowed to trap.
4045 //
4046 // An atomic operation isn't guaranteed to return in a reasonable amount of
4047 // time because it's possible for another thread to interfere with it for an
4048 // arbitrary length of time, but programs aren't allowed to rely on that.
4049 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4050 return !LI->isVolatile();
4051 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4052 return !SI->isVolatile();
4053 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4054 return !CXI->isVolatile();
4055 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4056 return !RMWI->isVolatile();
4057 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4058 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004059
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004060 // If there is no successor, then execution can't transfer to it.
4061 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4062 return !CRI->unwindsToCaller();
4063 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4064 return !CatchSwitch->unwindsToCaller();
4065 if (isa<ResumeInst>(I))
4066 return false;
4067 if (isa<ReturnInst>(I))
4068 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004069 if (isa<UnreachableInst>(I))
4070 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004071
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004072 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004073 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004074 // Call sites that throw have implicit non-local control flow.
4075 if (!CS.doesNotThrow())
4076 return false;
4077
4078 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4079 // etc. and thus not return. However, LLVM already assumes that
4080 //
4081 // - Thread exiting actions are modeled as writes to memory invisible to
4082 // the program.
4083 //
4084 // - Loops that don't have side effects (side effects are volatile/atomic
4085 // stores and IO) always terminate (see http://llvm.org/PR965).
4086 // Furthermore IO itself is also modeled as writes to memory invisible to
4087 // the program.
4088 //
4089 // We rely on those assumptions here, and use the memory effects of the call
4090 // target as a proxy for checking that it always returns.
4091
4092 // FIXME: This isn't aggressive enough; a call which only writes to a global
4093 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00004094 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00004095 match(I, m_Intrinsic<Intrinsic::assume>()) ||
4096 match(I, m_Intrinsic<Intrinsic::sideeffect>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004097 }
4098
4099 // Other instructions return normally.
4100 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004101}
4102
Philip Reamesfbffd122018-03-08 21:25:30 +00004103bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
4104 // TODO: This is slightly consdervative for invoke instruction since exiting
4105 // via an exception *is* normal control for them.
4106 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4107 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4108 return false;
4109 return true;
4110}
4111
Jingyue Wu42f1d672015-07-28 18:22:40 +00004112bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4113 const Loop *L) {
4114 // The loop header is guaranteed to be executed for every iteration.
4115 //
4116 // FIXME: Relax this constraint to cover all basic blocks that are
4117 // guaranteed to be executed at every iteration.
4118 if (I->getParent() != L->getHeader()) return false;
4119
4120 for (const Instruction &LI : *L->getHeader()) {
4121 if (&LI == I) return true;
4122 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4123 }
4124 llvm_unreachable("Instruction not contained in its own parent basic block.");
4125}
4126
4127bool llvm::propagatesFullPoison(const Instruction *I) {
4128 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004129 case Instruction::Add:
4130 case Instruction::Sub:
4131 case Instruction::Xor:
4132 case Instruction::Trunc:
4133 case Instruction::BitCast:
4134 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004135 case Instruction::Mul:
4136 case Instruction::Shl:
4137 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004138 // These operations all propagate poison unconditionally. Note that poison
4139 // is not any particular value, so xor or subtraction of poison with
4140 // itself still yields poison, not zero.
4141 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004142
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004143 case Instruction::AShr:
4144 case Instruction::SExt:
4145 // For these operations, one bit of the input is replicated across
4146 // multiple output bits. A replicated poison bit is still poison.
4147 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004148
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004149 case Instruction::ICmp:
4150 // Comparing poison with any value yields poison. This is why, for
4151 // instance, x s< (x +nsw 1) can be folded to true.
4152 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004153
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004154 default:
4155 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004156 }
4157}
4158
4159const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4160 switch (I->getOpcode()) {
4161 case Instruction::Store:
4162 return cast<StoreInst>(I)->getPointerOperand();
4163
4164 case Instruction::Load:
4165 return cast<LoadInst>(I)->getPointerOperand();
4166
4167 case Instruction::AtomicCmpXchg:
4168 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4169
4170 case Instruction::AtomicRMW:
4171 return cast<AtomicRMWInst>(I)->getPointerOperand();
4172
4173 case Instruction::UDiv:
4174 case Instruction::SDiv:
4175 case Instruction::URem:
4176 case Instruction::SRem:
4177 return I->getOperand(1);
4178
4179 default:
4180 return nullptr;
4181 }
4182}
4183
Sanjoy Das08989c72017-04-30 19:41:19 +00004184bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004185 // We currently only look for uses of poison values within the same basic
4186 // block, as that makes it easier to guarantee that the uses will be
4187 // executed given that PoisonI is executed.
4188 //
4189 // FIXME: Expand this to consider uses beyond the same basic block. To do
4190 // this, look out for the distinction between post-dominance and strong
4191 // post-dominance.
4192 const BasicBlock *BB = PoisonI->getParent();
4193
4194 // Set of instructions that we have proved will yield poison if PoisonI
4195 // does.
4196 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004197 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004198 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004199 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004200
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004201 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004202
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004203 unsigned Iter = 0;
4204 while (Iter++ < MaxDepth) {
4205 for (auto &I : make_range(Begin, End)) {
4206 if (&I != PoisonI) {
4207 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4208 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4209 return true;
4210 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4211 return false;
4212 }
4213
4214 // Mark poison that propagates from I through uses of I.
4215 if (YieldsPoison.count(&I)) {
4216 for (const User *User : I.users()) {
4217 const Instruction *UserI = cast<Instruction>(User);
4218 if (propagatesFullPoison(UserI))
4219 YieldsPoison.insert(User);
4220 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004221 }
4222 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004223
4224 if (auto *NextBB = BB->getSingleSuccessor()) {
4225 if (Visited.insert(NextBB).second) {
4226 BB = NextBB;
4227 Begin = BB->getFirstNonPHI()->getIterator();
4228 End = BB->end();
4229 continue;
4230 }
4231 }
4232
4233 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004234 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004235 return false;
4236}
4237
Pete Cooper35b00d52016-08-13 01:05:32 +00004238static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004239 if (FMF.noNaNs())
4240 return true;
4241
4242 if (auto *C = dyn_cast<ConstantFP>(V))
4243 return !C->isNaN();
4244 return false;
4245}
4246
Pete Cooper35b00d52016-08-13 01:05:32 +00004247static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004248 if (auto *C = dyn_cast<ConstantFP>(V))
4249 return !C->isZero();
4250 return false;
4251}
4252
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004253/// Match clamp pattern for float types without care about NaNs or signed zeros.
4254/// Given non-min/max outer cmp/select from the clamp pattern this
4255/// function recognizes if it can be substitued by a "canonical" min/max
4256/// pattern.
4257static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4258 Value *CmpLHS, Value *CmpRHS,
4259 Value *TrueVal, Value *FalseVal,
4260 Value *&LHS, Value *&RHS) {
4261 // Try to match
4262 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4263 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4264 // and return description of the outer Max/Min.
4265
4266 // First, check if select has inverse order:
4267 if (CmpRHS == FalseVal) {
4268 std::swap(TrueVal, FalseVal);
4269 Pred = CmpInst::getInversePredicate(Pred);
4270 }
4271
4272 // Assume success now. If there's no match, callers should not use these anyway.
4273 LHS = TrueVal;
4274 RHS = FalseVal;
4275
4276 const APFloat *FC1;
4277 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4278 return {SPF_UNKNOWN, SPNB_NA, false};
4279
4280 const APFloat *FC2;
4281 switch (Pred) {
4282 case CmpInst::FCMP_OLT:
4283 case CmpInst::FCMP_OLE:
4284 case CmpInst::FCMP_ULT:
4285 case CmpInst::FCMP_ULE:
4286 if (match(FalseVal,
4287 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4288 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4289 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4290 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4291 break;
4292 case CmpInst::FCMP_OGT:
4293 case CmpInst::FCMP_OGE:
4294 case CmpInst::FCMP_UGT:
4295 case CmpInst::FCMP_UGE:
4296 if (match(FalseVal,
4297 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4298 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4299 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4300 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4301 break;
4302 default:
4303 break;
4304 }
4305
4306 return {SPF_UNKNOWN, SPNB_NA, false};
4307}
4308
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004309/// Recognize variations of:
4310/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4311static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4312 Value *CmpLHS, Value *CmpRHS,
4313 Value *TrueVal, Value *FalseVal) {
4314 // Swap the select operands and predicate to match the patterns below.
4315 if (CmpRHS != TrueVal) {
4316 Pred = ICmpInst::getSwappedPredicate(Pred);
4317 std::swap(TrueVal, FalseVal);
4318 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004319 const APInt *C1;
4320 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4321 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004322 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4323 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004324 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004325 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004326
4327 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4328 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004329 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004330 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004331
4332 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4333 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004334 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004335 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004336
4337 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4338 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004339 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004340 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004341 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004342 return {SPF_UNKNOWN, SPNB_NA, false};
4343}
4344
Sanjay Patel78114302018-01-02 20:56:45 +00004345/// Recognize variations of:
4346/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4347static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4348 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004349 Value *TVal, Value *FVal,
4350 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004351 // TODO: Allow FP min/max with nnan/nsz.
4352 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4353
4354 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004355 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004356 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4357 return {SPF_UNKNOWN, SPNB_NA, false};
4358
4359 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004360 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004361 if (L.Flavor != R.Flavor)
4362 return {SPF_UNKNOWN, SPNB_NA, false};
4363
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004364 // We have something like: x Pred y ? min(a, b) : min(c, d).
4365 // Try to match the compare to the min/max operations of the select operands.
4366 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004367 switch (L.Flavor) {
4368 case SPF_SMIN:
4369 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4370 Pred = ICmpInst::getSwappedPredicate(Pred);
4371 std::swap(CmpLHS, CmpRHS);
4372 }
4373 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4374 break;
4375 return {SPF_UNKNOWN, SPNB_NA, false};
4376 case SPF_SMAX:
4377 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4378 Pred = ICmpInst::getSwappedPredicate(Pred);
4379 std::swap(CmpLHS, CmpRHS);
4380 }
4381 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4382 break;
4383 return {SPF_UNKNOWN, SPNB_NA, false};
4384 case SPF_UMIN:
4385 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4386 Pred = ICmpInst::getSwappedPredicate(Pred);
4387 std::swap(CmpLHS, CmpRHS);
4388 }
4389 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4390 break;
4391 return {SPF_UNKNOWN, SPNB_NA, false};
4392 case SPF_UMAX:
4393 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4394 Pred = ICmpInst::getSwappedPredicate(Pred);
4395 std::swap(CmpLHS, CmpRHS);
4396 }
4397 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4398 break;
4399 return {SPF_UNKNOWN, SPNB_NA, false};
4400 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004401 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004402 }
4403
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004404 // If there is a common operand in the already matched min/max and the other
4405 // min/max operands match the compare operands (either directly or inverted),
4406 // then this is min/max of the same flavor.
4407
Sanjay Patel78114302018-01-02 20:56:45 +00004408 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004409 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4410 if (D == B) {
4411 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4412 match(A, m_Not(m_Specific(CmpRHS)))))
4413 return {L.Flavor, SPNB_NA, false};
4414 }
Sanjay Patel78114302018-01-02 20:56:45 +00004415 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004416 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4417 if (C == B) {
4418 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4419 match(A, m_Not(m_Specific(CmpRHS)))))
4420 return {L.Flavor, SPNB_NA, false};
4421 }
Sanjay Patel78114302018-01-02 20:56:45 +00004422 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004423 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4424 if (D == A) {
4425 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4426 match(B, m_Not(m_Specific(CmpRHS)))))
4427 return {L.Flavor, SPNB_NA, false};
4428 }
Sanjay Patel78114302018-01-02 20:56:45 +00004429 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004430 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4431 if (C == A) {
4432 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4433 match(B, m_Not(m_Specific(CmpRHS)))))
4434 return {L.Flavor, SPNB_NA, false};
4435 }
Sanjay Patel78114302018-01-02 20:56:45 +00004436
4437 return {SPF_UNKNOWN, SPNB_NA, false};
4438}
4439
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004440/// Match non-obvious integer minimum and maximum sequences.
4441static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4442 Value *CmpLHS, Value *CmpRHS,
4443 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004444 Value *&LHS, Value *&RHS,
4445 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004446 // Assume success. If there's no match, callers should not use these anyway.
4447 LHS = TrueVal;
4448 RHS = FalseVal;
4449
4450 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4451 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4452 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004453
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004454 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004455 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4456 return SPR;
4457
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004458 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004459 return {SPF_UNKNOWN, SPNB_NA, false};
4460
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004461 // Z = X -nsw Y
4462 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4463 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4464 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004465 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004466 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004467
4468 // Z = X -nsw Y
4469 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4470 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4471 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004472 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004473 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004474
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004475 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004476 if (!match(CmpRHS, m_APInt(C1)))
4477 return {SPF_UNKNOWN, SPNB_NA, false};
4478
4479 // An unsigned min/max can be written with a signed compare.
4480 const APInt *C2;
4481 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4482 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4483 // Is the sign bit set?
4484 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4485 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004486 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4487 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004488 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004489
4490 // Is the sign bit clear?
4491 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4492 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004493 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4494 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004495 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004496 }
4497
4498 // Look through 'not' ops to find disguised signed min/max.
4499 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4500 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4501 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004502 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004503 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004504
4505 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4506 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4507 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004508 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004509 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004510
4511 return {SPF_UNKNOWN, SPNB_NA, false};
4512}
4513
Chen Zheng69bb0642018-07-21 12:27:54 +00004514bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004515 assert(X && Y && "Invalid operand");
4516
Chen Zheng69bb0642018-07-21 12:27:54 +00004517 // X = sub (0, Y) || X = sub nsw (0, Y)
4518 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4519 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004520 return true;
4521
Chen Zheng69bb0642018-07-21 12:27:54 +00004522 // Y = sub (0, X) || Y = sub nsw (0, X)
4523 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4524 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004525 return true;
4526
Chen Zheng69bb0642018-07-21 12:27:54 +00004527 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004528 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004529 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4530 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4531 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4532 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004533}
4534
James Molloy134bec22015-08-11 09:12:57 +00004535static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4536 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004537 Value *CmpLHS, Value *CmpRHS,
4538 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004539 Value *&LHS, Value *&RHS,
4540 unsigned Depth) {
James Molloy71b91c22015-05-11 14:42:20 +00004541 LHS = CmpLHS;
4542 RHS = CmpRHS;
4543
Sanjay Patel9a399792017-12-26 15:09:19 +00004544 // Signed zero may return inconsistent results between implementations.
4545 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4546 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4547 // Therefore, we behave conservatively and only proceed if at least one of the
4548 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004549 switch (Pred) {
4550 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004551 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004552 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4553 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4554 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4555 !isKnownNonZero(CmpRHS))
4556 return {SPF_UNKNOWN, SPNB_NA, false};
4557 }
4558
4559 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4560 bool Ordered = false;
4561
4562 // When given one NaN and one non-NaN input:
4563 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4564 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4565 // ordered comparison fails), which could be NaN or non-NaN.
4566 // so here we discover exactly what NaN behavior is required/accepted.
4567 if (CmpInst::isFPPredicate(Pred)) {
4568 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4569 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4570
4571 if (LHSSafe && RHSSafe) {
4572 // Both operands are known non-NaN.
4573 NaNBehavior = SPNB_RETURNS_ANY;
4574 } else if (CmpInst::isOrdered(Pred)) {
4575 // An ordered comparison will return false when given a NaN, so it
4576 // returns the RHS.
4577 Ordered = true;
4578 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004579 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004580 NaNBehavior = SPNB_RETURNS_NAN;
4581 else if (RHSSafe)
4582 NaNBehavior = SPNB_RETURNS_OTHER;
4583 else
4584 // Completely unsafe.
4585 return {SPF_UNKNOWN, SPNB_NA, false};
4586 } else {
4587 Ordered = false;
4588 // An unordered comparison will return true when given a NaN, so it
4589 // returns the LHS.
4590 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004591 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004592 NaNBehavior = SPNB_RETURNS_OTHER;
4593 else if (RHSSafe)
4594 NaNBehavior = SPNB_RETURNS_NAN;
4595 else
4596 // Completely unsafe.
4597 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004598 }
4599 }
4600
James Molloy71b91c22015-05-11 14:42:20 +00004601 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004602 std::swap(CmpLHS, CmpRHS);
4603 Pred = CmpInst::getSwappedPredicate(Pred);
4604 if (NaNBehavior == SPNB_RETURNS_NAN)
4605 NaNBehavior = SPNB_RETURNS_OTHER;
4606 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4607 NaNBehavior = SPNB_RETURNS_NAN;
4608 Ordered = !Ordered;
4609 }
4610
4611 // ([if]cmp X, Y) ? X : Y
4612 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004613 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004614 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004615 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004616 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004617 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004618 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004619 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004620 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004621 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004622 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4623 case FCmpInst::FCMP_UGT:
4624 case FCmpInst::FCMP_UGE:
4625 case FCmpInst::FCMP_OGT:
4626 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4627 case FCmpInst::FCMP_ULT:
4628 case FCmpInst::FCMP_ULE:
4629 case FCmpInst::FCMP_OLT:
4630 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004631 }
4632 }
Chen Zhengccc84222018-07-16 02:23:00 +00004633
4634 if (isKnownNegation(TrueVal, FalseVal)) {
4635 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4636 // match against either LHS or sext(LHS).
4637 auto MaybeSExtCmpLHS =
4638 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4639 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4640 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4641 if (match(TrueVal, MaybeSExtCmpLHS)) {
4642 // Set the return values. If the compare uses the negated value (-X >s 0),
4643 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004644 LHS = TrueVal;
4645 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004646 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4647 std::swap(LHS, RHS);
4648
4649 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4650 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4651 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4652 return {SPF_ABS, SPNB_NA, false};
4653
4654 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4655 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4656 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4657 return {SPF_NABS, SPNB_NA, false};
4658 }
4659 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4660 // Set the return values. If the compare uses the negated value (-X >s 0),
4661 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004662 LHS = FalseVal;
4663 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004664 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4665 std::swap(LHS, RHS);
4666
4667 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4668 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4669 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4670 return {SPF_NABS, SPNB_NA, false};
4671
4672 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4673 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4674 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4675 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004676 }
James Molloy71b91c22015-05-11 14:42:20 +00004677 }
4678
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004679 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004680 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004681
4682 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4683 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4684 // semantics than minNum. Be conservative in such case.
4685 if (NaNBehavior != SPNB_RETURNS_ANY ||
4686 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4687 !isKnownNonZero(CmpRHS)))
4688 return {SPF_UNKNOWN, SPNB_NA, false};
4689
4690 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004691}
James Molloy270ef8c2015-05-15 16:04:50 +00004692
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004693/// Helps to match a select pattern in case of a type mismatch.
4694///
4695/// The function processes the case when type of true and false values of a
4696/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004697/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004698/// operation after "select". If yes, it returns the new second value of
4699/// "select" (with the assumption that cast is moved):
4700/// 1. As operand of cast instruction when both values of "select" are same cast
4701/// instructions.
4702/// 2. As restored constant (by applying reverse cast operation) when the first
4703/// value of the "select" is a cast operation and the second value is a
4704/// constant.
4705/// NOTE: We return only the new second value because the first value could be
4706/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004707static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4708 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004709 auto *Cast1 = dyn_cast<CastInst>(V1);
4710 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004711 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004712
Sanjay Patel14a4b812017-01-29 16:34:57 +00004713 *CastOp = Cast1->getOpcode();
4714 Type *SrcTy = Cast1->getSrcTy();
4715 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4716 // If V1 and V2 are both the same cast from the same type, look through V1.
4717 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4718 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004719 return nullptr;
4720 }
4721
Sanjay Patel14a4b812017-01-29 16:34:57 +00004722 auto *C = dyn_cast<Constant>(V2);
4723 if (!C)
4724 return nullptr;
4725
David Majnemerd2a074b2016-04-29 18:40:34 +00004726 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004727 switch (*CastOp) {
4728 case Instruction::ZExt:
4729 if (CmpI->isUnsigned())
4730 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4731 break;
4732 case Instruction::SExt:
4733 if (CmpI->isSigned())
4734 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4735 break;
4736 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004737 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004738 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4739 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004740 // Here we have the following case:
4741 //
4742 // %cond = cmp iN %x, CmpConst
4743 // %tr = trunc iN %x to iK
4744 // %narrowsel = select i1 %cond, iK %t, iK C
4745 //
4746 // We can always move trunc after select operation:
4747 //
4748 // %cond = cmp iN %x, CmpConst
4749 // %widesel = select i1 %cond, iN %x, iN CmpConst
4750 // %tr = trunc iN %widesel to iK
4751 //
4752 // Note that C could be extended in any way because we don't care about
4753 // upper bits after truncation. It can't be abs pattern, because it would
4754 // look like:
4755 //
4756 // select i1 %cond, x, -x.
4757 //
4758 // So only min/max pattern could be matched. Such match requires widened C
4759 // == CmpConst. That is why set widened C = CmpConst, condition trunc
4760 // CmpConst == C is checked below.
4761 CastedTo = CmpConst;
4762 } else {
4763 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4764 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00004765 break;
4766 case Instruction::FPTrunc:
4767 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4768 break;
4769 case Instruction::FPExt:
4770 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4771 break;
4772 case Instruction::FPToUI:
4773 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4774 break;
4775 case Instruction::FPToSI:
4776 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4777 break;
4778 case Instruction::UIToFP:
4779 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4780 break;
4781 case Instruction::SIToFP:
4782 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4783 break;
4784 default:
4785 break;
4786 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004787
4788 if (!CastedTo)
4789 return nullptr;
4790
David Majnemerd2a074b2016-04-29 18:40:34 +00004791 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004792 Constant *CastedBack =
4793 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004794 if (CastedBack != C)
4795 return nullptr;
4796
4797 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004798}
4799
Sanjay Patele8dc0902016-05-23 17:57:54 +00004800SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004801 Instruction::CastOps *CastOp,
4802 unsigned Depth) {
4803 if (Depth >= MaxDepth)
4804 return {SPF_UNKNOWN, SPNB_NA, false};
4805
James Molloy270ef8c2015-05-15 16:04:50 +00004806 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004807 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004808
James Molloy134bec22015-08-11 09:12:57 +00004809 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4810 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004811
James Molloy134bec22015-08-11 09:12:57 +00004812 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004813 Value *CmpLHS = CmpI->getOperand(0);
4814 Value *CmpRHS = CmpI->getOperand(1);
4815 Value *TrueVal = SI->getTrueValue();
4816 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004817 FastMathFlags FMF;
4818 if (isa<FPMathOperator>(CmpI))
4819 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004820
4821 // Bail out early.
4822 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004823 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004824
4825 // Deal with type mismatches.
4826 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00004827 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
4828 // If this is a potential fmin/fmax with a cast to integer, then ignore
4829 // -0.0 because there is no corresponding integer value.
4830 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4831 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004832 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004833 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004834 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004835 }
4836 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
4837 // If this is a potential fmin/fmax with a cast to integer, then ignore
4838 // -0.0 because there is no corresponding integer value.
4839 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4840 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004841 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004842 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004843 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004844 }
James Molloy270ef8c2015-05-15 16:04:50 +00004845 }
James Molloy134bec22015-08-11 09:12:57 +00004846 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004847 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00004848}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004849
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00004850CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
4851 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
4852 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
4853 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
4854 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
4855 if (SPF == SPF_FMINNUM)
4856 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
4857 if (SPF == SPF_FMAXNUM)
4858 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
4859 llvm_unreachable("unhandled!");
4860}
4861
4862SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
4863 if (SPF == SPF_SMIN) return SPF_SMAX;
4864 if (SPF == SPF_UMIN) return SPF_UMAX;
4865 if (SPF == SPF_SMAX) return SPF_SMIN;
4866 if (SPF == SPF_UMAX) return SPF_UMIN;
4867 llvm_unreachable("unhandled!");
4868}
4869
4870CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
4871 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
4872}
4873
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004874/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004875static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4876 const Value *RHS, const DataLayout &DL,
4877 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004878 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004879 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4880 return true;
4881
4882 switch (Pred) {
4883 default:
4884 return false;
4885
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004886 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004887 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004888
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004889 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004890 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004891 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004892 return false;
4893 }
4894
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004895 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004896 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004897
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004898 // LHS u<= LHS +_{nuw} C for any C
4899 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004900 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004901
4902 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004903 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4904 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004905 const APInt *&CA, const APInt *&CB) {
4906 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4907 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4908 return true;
4909
4910 // If X & C == 0 then (X | C) == X +_{nuw} C
4911 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4912 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004913 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004914 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4915 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004916 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004917 return true;
4918 }
4919
4920 return false;
4921 };
4922
Pete Cooper35b00d52016-08-13 01:05:32 +00004923 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004924 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004925 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4926 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004927
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004928 return false;
4929 }
4930 }
4931}
4932
4933/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004934/// ALHS ARHS" is true. Otherwise, return None.
4935static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004936isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004937 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4938 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004939 switch (Pred) {
4940 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004941 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004942
4943 case CmpInst::ICMP_SLT:
4944 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004945 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4946 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004947 return true;
4948 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004949
4950 case CmpInst::ICMP_ULT:
4951 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004952 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4953 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004954 return true;
4955 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004956 }
4957}
4958
Chad Rosier226a7342016-05-05 17:41:19 +00004959/// Return true if the operands of the two compares match. IsSwappedOps is true
4960/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004961static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4962 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004963 bool &IsSwappedOps) {
4964
4965 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4966 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4967 return IsMatchingOps || IsSwappedOps;
4968}
4969
Chad Rosier41dd31f2016-04-20 19:15:26 +00004970/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4971/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4972/// BRHS" is false. Otherwise, return None if we can't infer anything.
4973static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004974 const Value *ALHS,
4975 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004976 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004977 const Value *BLHS,
4978 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004979 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004980 // Canonicalize the operands so they're matching.
4981 if (IsSwappedOps) {
4982 std::swap(BLHS, BRHS);
4983 BPred = ICmpInst::getSwappedPredicate(BPred);
4984 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004985 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004986 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004987 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004988 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004989
Chad Rosier41dd31f2016-04-20 19:15:26 +00004990 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004991}
4992
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004993/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4994/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4995/// C2" is false. Otherwise, return None if we can't infer anything.
4996static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004997isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4998 const ConstantInt *C1,
4999 CmpInst::Predicate BPred,
5000 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005001 assert(ALHS == BLHS && "LHS operands must match.");
5002 ConstantRange DomCR =
5003 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5004 ConstantRange CR =
5005 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5006 ConstantRange Intersection = DomCR.intersectWith(CR);
5007 ConstantRange Difference = DomCR.difference(CR);
5008 if (Intersection.isEmptySet())
5009 return false;
5010 if (Difference.isEmptySet())
5011 return true;
5012 return None;
5013}
5014
Chad Rosier2f498032017-07-28 18:47:43 +00005015/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5016/// false. Otherwise, return None if we can't infer anything.
5017static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5018 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005019 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005020 unsigned Depth) {
5021 Value *ALHS = LHS->getOperand(0);
5022 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005023 // The rest of the logic assumes the LHS condition is true. If that's not the
5024 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005025 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005026 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005027
5028 Value *BLHS = RHS->getOperand(0);
5029 Value *BRHS = RHS->getOperand(1);
5030 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005031
Chad Rosier226a7342016-05-05 17:41:19 +00005032 // Can we infer anything when the two compares have matching operands?
5033 bool IsSwappedOps;
5034 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
5035 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
5036 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005037 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005038 // No amount of additional analysis will infer the second condition, so
5039 // early exit.
5040 return None;
5041 }
5042
5043 // Can we infer anything when the LHS operands match and the RHS operands are
5044 // constants (not necessarily matching)?
5045 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5046 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
5047 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
5048 cast<ConstantInt>(BRHS)))
5049 return Implication;
5050 // No amount of additional analysis will infer the second condition, so
5051 // early exit.
5052 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005053 }
5054
Chad Rosier41dd31f2016-04-20 19:15:26 +00005055 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005056 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005057 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005058}
Chad Rosier2f498032017-07-28 18:47:43 +00005059
Chad Rosierf73a10d2017-08-01 19:22:36 +00005060/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5061/// false. Otherwise, return None if we can't infer anything. We expect the
5062/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5063static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5064 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005065 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005066 unsigned Depth) {
5067 // The LHS must be an 'or' or an 'and' instruction.
5068 assert((LHS->getOpcode() == Instruction::And ||
5069 LHS->getOpcode() == Instruction::Or) &&
5070 "Expected LHS to be 'and' or 'or'.");
5071
Davide Italiano1a943a92017-08-09 16:06:54 +00005072 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005073
5074 // If the result of an 'or' is false, then we know both legs of the 'or' are
5075 // false. Similarly, if the result of an 'and' is true, then we know both
5076 // legs of the 'and' are true.
5077 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005078 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5079 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005080 // FIXME: Make this non-recursion.
5081 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005082 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005083 return Implication;
5084 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005085 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005086 return Implication;
5087 return None;
5088 }
5089 return None;
5090}
5091
Chad Rosier2f498032017-07-28 18:47:43 +00005092Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005093 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005094 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005095 // Bail out when we hit the limit.
5096 if (Depth == MaxDepth)
5097 return None;
5098
Chad Rosierf73a10d2017-08-01 19:22:36 +00005099 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5100 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005101 if (LHS->getType() != RHS->getType())
5102 return None;
5103
5104 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005105 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005106
5107 // LHS ==> RHS by definition
5108 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005109 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005110
Chad Rosierf73a10d2017-08-01 19:22:36 +00005111 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005112 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005113 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005114
Chad Rosier2f498032017-07-28 18:47:43 +00005115 assert(OpTy->isIntegerTy(1) && "implied by above");
5116
Chad Rosier2f498032017-07-28 18:47:43 +00005117 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005118 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5119 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5120 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005121 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005122
Chad Rosierf73a10d2017-08-01 19:22:36 +00005123 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5124 // an icmp. FIXME: Add support for and/or on the RHS.
5125 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5126 if (LHSBO && RHSCmp) {
5127 if ((LHSBO->getOpcode() == Instruction::And ||
5128 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005129 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005130 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005131 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005132}