blob: ac29cde01fa08300751131d4acecf2dc9194d436 [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:
504 case Intrinsic::invariant_start:
505 case Intrinsic::invariant_end:
506 case Intrinsic::lifetime_start:
507 case Intrinsic::lifetime_end:
508 case Intrinsic::objectsize:
509 case Intrinsic::ptr_annotation:
510 case Intrinsic::var_annotation:
511 return true;
512 }
513
514 return false;
515}
516
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000517bool llvm::isValidAssumeForContext(const Instruction *Inv,
518 const Instruction *CxtI,
519 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000520 // There are two restrictions on the use of an assume:
521 // 1. The assume must dominate the context (or the control flow must
522 // reach the assume whenever it reaches the context).
523 // 2. The context must not be in the assume's set of ephemeral values
524 // (otherwise we will use the assume to prove that the condition
525 // feeding the assume is trivially true, thus causing the removal of
526 // the assume).
527
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000528 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000529 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000530 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000531 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
532 // We don't have a DT, but this trivially dominates.
533 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000534 }
535
Pete Cooper54a02552016-08-12 01:00:15 +0000536 // With or without a DT, the only remaining case we will check is if the
537 // instructions are in the same BB. Give up if that is not the case.
538 if (Inv->getParent() != CxtI->getParent())
539 return false;
540
Vedant Kumard3196742018-02-28 19:08:52 +0000541 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000542 // the other instruction. If we don't have a dom tree then we can check if
543 // the assume is first in the BB.
544 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000545 // Search forward from the assume until we reach the context (or the end
546 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000547 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000548 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000549 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000550 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000551 }
552
Pete Cooper54a02552016-08-12 01:00:15 +0000553 // The context comes first, but they're both in the same block. Make sure
554 // there is nothing in between that might interrupt the control flow.
555 for (BasicBlock::const_iterator I =
556 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
557 I != IE; ++I)
558 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
559 return false;
560
561 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000562}
563
Craig Topperb45eabc2017-04-26 16:39:58 +0000564static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
565 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000566 // Use of assumptions is context-sensitive. If we don't have a context, we
567 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000568 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000569 return;
570
Craig Topperb45eabc2017-04-26 16:39:58 +0000571 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000572
Hal Finkel8a9a7832017-01-11 13:24:24 +0000573 // Note that the patterns below need to be kept in sync with the code
574 // in AssumptionCache::updateAffectedValues.
575
576 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000578 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000579 CallInst *I = cast<CallInst>(AssumeVH);
580 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
581 "Got assumption for the wrong function!");
582 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000583 continue;
584
Vedant Kumard3196742018-02-28 19:08:52 +0000585 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000586 // We're running this loop for once for each value queried resulting in a
587 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000588
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000589 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
590 "must be an assume intrinsic");
591
592 Value *Arg = I->getArgOperand(0);
593
594 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000595 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000596 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000597 return;
598 }
Sanjay Patel96669962017-01-17 18:15:49 +0000599 if (match(Arg, m_Not(m_Specific(V))) &&
600 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
601 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000602 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000603 return;
604 }
Hal Finkel60db0582014-09-07 18:57:58 +0000605
David Majnemer9b609752014-12-12 23:59:29 +0000606 // The remaining tests are all recursive, so bail out if we hit the limit.
607 if (Depth == MaxDepth)
608 continue;
609
Hal Finkel60db0582014-09-07 18:57:58 +0000610 Value *A, *B;
611 auto m_V = m_CombineOr(m_Specific(V),
612 m_CombineOr(m_PtrToInt(m_Specific(V)),
613 m_BitCast(m_Specific(V))));
614
615 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000616 uint64_t C;
Hal Finkel60db0582014-09-07 18:57:58 +0000617 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000618 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000619 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000620 KnownBits RHSKnown(BitWidth);
621 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
622 Known.Zero |= RHSKnown.Zero;
623 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000624 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 } else if (match(Arg,
626 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000627 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000628 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000629 KnownBits RHSKnown(BitWidth);
630 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
631 KnownBits MaskKnown(BitWidth);
632 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000633
634 // For those bits in the mask that are known to be one, we can propagate
635 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000636 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
637 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000638 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000639 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
640 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000641 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000642 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000643 KnownBits RHSKnown(BitWidth);
644 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
645 KnownBits MaskKnown(BitWidth);
646 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000647
648 // For those bits in the mask that are known to be one, we can propagate
649 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000650 Known.Zero |= RHSKnown.One & MaskKnown.One;
651 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000652 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000653 } else if (match(Arg,
654 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000655 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000656 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000657 KnownBits RHSKnown(BitWidth);
658 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
659 KnownBits BKnown(BitWidth);
660 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000661
662 // For those bits in B that are known to be zero, we can propagate known
663 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000664 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
665 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000666 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000667 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
668 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000669 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000670 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000671 KnownBits RHSKnown(BitWidth);
672 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
673 KnownBits BKnown(BitWidth);
674 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000675
676 // For those bits in B that are known to be zero, we can propagate
677 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000678 Known.Zero |= RHSKnown.One & BKnown.Zero;
679 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000680 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 } else if (match(Arg,
682 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000683 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000684 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 KnownBits RHSKnown(BitWidth);
686 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
687 KnownBits BKnown(BitWidth);
688 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000689
690 // For those bits in B that are known to be zero, we can propagate known
691 // bits from the RHS to V. For those bits in B that are known to be one,
692 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000693 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
694 Known.One |= RHSKnown.One & BKnown.Zero;
695 Known.Zero |= RHSKnown.One & BKnown.One;
696 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000697 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000698 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
699 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000700 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000701 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 KnownBits RHSKnown(BitWidth);
703 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
704 KnownBits BKnown(BitWidth);
705 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000706
707 // For those bits in B that are known to be zero, we can propagate
708 // inverted known bits from the RHS to V. For those bits in B that are
709 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000710 Known.Zero |= RHSKnown.One & BKnown.Zero;
711 Known.One |= RHSKnown.Zero & BKnown.Zero;
712 Known.Zero |= RHSKnown.Zero & BKnown.One;
713 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000714 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000715 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
716 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000717 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000718 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
719 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000720 KnownBits RHSKnown(BitWidth);
721 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000722 // For those bits in RHS that are known, we can propagate them to known
723 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000724 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000725 Known.Zero |= RHSKnown.Zero;
Igor Laevskycec8f472017-12-05 12:18:15 +0000726 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000727 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000728 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000729 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
730 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000731 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000732 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
733 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000734 KnownBits RHSKnown(BitWidth);
735 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000736 // For those bits in RHS that are known, we can propagate them inverted
737 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000738 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000739 Known.Zero |= RHSKnown.One;
Igor Laevskycec8f472017-12-05 12:18:15 +0000740 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000741 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000742 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000743 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000744 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000745 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000746 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000747 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
748 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000749 KnownBits RHSKnown(BitWidth);
750 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000751 // For those bits in RHS that are known, we can propagate them to known
752 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000753 Known.Zero |= RHSKnown.Zero << C;
754 Known.One |= RHSKnown.One << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000755 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000756 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000757 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000758 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000759 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
760 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000761 KnownBits RHSKnown(BitWidth);
762 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000763 // For those bits in RHS that are known, we can propagate them inverted
764 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000765 Known.Zero |= RHSKnown.One << C;
766 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000767 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000768 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000769 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000770 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000771 KnownBits RHSKnown(BitWidth);
772 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000773
Craig Topperca48af32017-04-29 16:43:11 +0000774 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000775 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000776 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000777 }
778 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000779 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000780 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000781 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000782 KnownBits RHSKnown(BitWidth);
783 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000784
Craig Topperf0aeee02017-05-05 17:36:09 +0000785 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000786 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000787 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000788 }
789 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000790 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000791 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000792 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000793 KnownBits RHSKnown(BitWidth);
794 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000795
Craig Topperca48af32017-04-29 16:43:11 +0000796 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000797 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000798 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000799 }
800 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000801 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000802 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000803 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000804 KnownBits RHSKnown(BitWidth);
805 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000806
Craig Topperf0aeee02017-05-05 17:36:09 +0000807 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000808 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000809 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000810 }
811 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000812 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000813 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000814 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000815 KnownBits RHSKnown(BitWidth);
816 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000817
818 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000819 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
820 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000821 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000822 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000823 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000824 KnownBits RHSKnown(BitWidth);
825 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000826
Sanjay Patela60aec12018-02-08 14:52:40 +0000827 // If the RHS is known zero, then this assumption must be wrong (nothing
828 // is unsigned less than zero). Signal a conflict and get out of here.
829 if (RHSKnown.isZero()) {
830 Known.Zero.setAllBits();
831 Known.One.setAllBits();
832 break;
833 }
834
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000835 // Whatever high bits in c are zero are known to be zero (if c is a power
836 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000837 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000838 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000839 else
Craig Topper8df66c62017-05-12 17:20:30 +0000840 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000841 }
842 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000843
844 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000845 // have a logical fallacy. It's possible that the assumption is not reachable,
846 // so this isn't a real bug. On the other hand, the program may have undefined
847 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
848 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000849 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000850 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000851
Vivek Pandya95906582017-10-11 17:12:59 +0000852 if (Q.ORE)
853 Q.ORE->emit([&]() {
854 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
855 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
856 CxtI)
857 << "Detected conflicting code assumptions. Program may "
858 "have undefined behavior, or compiler may have "
859 "internal error.";
860 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000861 }
Hal Finkel60db0582014-09-07 18:57:58 +0000862}
863
Sanjay Patelb7d12382017-10-16 14:46:37 +0000864/// Compute known bits from a shift operator, including those with a
865/// non-constant shift amount. Known is the output of this function. Known2 is a
866/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000867/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000868/// respectively, and a shift amount, compute the implied known-zero or
869/// known-one bits of the shift operator's result respectively for that shift
870/// amount. The results from calling KZF and KOF are conservatively combined for
871/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000872static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000873 const Operator *I, KnownBits &Known, KnownBits &Known2,
874 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000875 function_ref<APInt(const APInt &, unsigned)> KZF,
876 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000877 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000878
879 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
880 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
881
Craig Topperb45eabc2017-04-26 16:39:58 +0000882 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000883 Known.Zero = KZF(Known.Zero, ShiftAmt);
884 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000885 // If the known bits conflict, this must be an overflowing left shift, so
886 // the shift result is poison. We can return anything we want. Choose 0 for
887 // the best folding opportunity.
888 if (Known.hasConflict())
889 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000890
Hal Finkelf2199b22015-10-23 20:37:08 +0000891 return;
892 }
893
Craig Topperb45eabc2017-04-26 16:39:58 +0000894 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000895
Sanjay Patele272be72017-10-12 17:31:46 +0000896 // If the shift amount could be greater than or equal to the bit-width of the
897 // LHS, the value could be poison, but bail out because the check below is
898 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000900 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000901 return;
902 }
903
Craig Topperb45eabc2017-04-26 16:39:58 +0000904 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000905 // BitWidth > 64 and any upper bits are known, we'll end up returning the
906 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000907 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
908 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000909
910 // It would be more-clearly correct to use the two temporaries for this
911 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000912 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000913
James Molloy493e57d2015-10-26 14:10:46 +0000914 // If we know the shifter operand is nonzero, we can sometimes infer more
915 // known bits. However this is expensive to compute, so be lazy about it and
916 // only compute it when absolutely necessary.
917 Optional<bool> ShifterOperandIsNonZero;
918
Hal Finkelf2199b22015-10-23 20:37:08 +0000919 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000920 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
921 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000922 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000923 if (!*ShifterOperandIsNonZero)
924 return;
925 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000926
Craig Topperb45eabc2017-04-26 16:39:58 +0000927 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000928
Craig Topperb45eabc2017-04-26 16:39:58 +0000929 Known.Zero.setAllBits();
930 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000931 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
932 // Combine the shifted known input bits only for those shift amounts
933 // compatible with its known constraints.
934 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
935 continue;
936 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
937 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000938 // If we know the shifter is nonzero, we may be able to infer more known
939 // bits. This check is sunk down as far as possible to avoid the expensive
940 // call to isKnownNonZero if the cheaper checks above fail.
941 if (ShiftAmt == 0) {
942 if (!ShifterOperandIsNonZero.hasValue())
943 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000944 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000945 if (*ShifterOperandIsNonZero)
946 continue;
947 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000948
Sam McCalld0d43e62017-12-04 12:51:49 +0000949 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
950 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000951 }
952
Sanjay Patele272be72017-10-12 17:31:46 +0000953 // If the known bits conflict, the result is poison. Return a 0 and hope the
954 // caller can further optimize that.
955 if (Known.hasConflict())
956 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000957}
958
Craig Topperb45eabc2017-04-26 16:39:58 +0000959static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
960 unsigned Depth, const Query &Q) {
961 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000962
Craig Topperb45eabc2017-04-26 16:39:58 +0000963 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000964 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000965 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000966 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000967 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000968 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000969 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000970 case Instruction::And: {
971 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000972 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
973 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000974
Chris Lattner965c7692008-06-02 01:18:21 +0000975 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000976 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000977 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000978 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000979
980 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
981 // here we handle the more general case of adding any odd number by
982 // matching the form add(x, add(x, y)) where y is odd.
983 // TODO: This could be generalized to clearing any bit set in y where the
984 // following bit is known to be unset in y.
985 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000987 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
988 m_Value(Y))) ||
989 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
990 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000991 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000992 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000993 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000994 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000995 }
Jay Foad5a29c362014-05-15 12:12:55 +0000996 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000997 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000998 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +0000999 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1000 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001001
Chris Lattner965c7692008-06-02 01:18:21 +00001002 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001003 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001004 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001005 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001006 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001007 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001008 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1009 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001010
Chris Lattner965c7692008-06-02 01:18:21 +00001011 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001012 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001013 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001014 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1015 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001016 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001017 }
1018 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001019 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1021 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001022 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001023 }
1024 case Instruction::UDiv: {
1025 // For the purposes of computing leading zeros we can conservatively
1026 // treat a udiv as a logical right shift by the power of 2 known to
1027 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001028 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001029 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001030
Craig Topperf0aeee02017-05-05 17:36:09 +00001031 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001032 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001033 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1034 if (RHSMaxLeadingZeros != BitWidth)
1035 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001036
Craig Topperb45eabc2017-04-26 16:39:58 +00001037 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001038 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001039 }
David Majnemera19d0f22016-08-06 08:16:00 +00001040 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001041 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001042 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1043 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001044 computeKnownBits(RHS, Known, Depth + 1, Q);
1045 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001046 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001047 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1048 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001049 }
1050
1051 unsigned MaxHighOnes = 0;
1052 unsigned MaxHighZeros = 0;
1053 if (SPF == SPF_SMAX) {
1054 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001055 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001056 // We can derive a lower bound on the result by taking the max of the
1057 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001058 MaxHighOnes =
1059 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001060 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001061 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001062 MaxHighZeros = 1;
1063 } else if (SPF == SPF_SMIN) {
1064 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001065 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001066 // We can derive an upper bound on the result by taking the max of the
1067 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001068 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1069 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001070 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001071 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001072 MaxHighOnes = 1;
1073 } else if (SPF == SPF_UMAX) {
1074 // We can derive a lower bound on the result by taking the max of the
1075 // leading one bits.
1076 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001077 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001078 } else if (SPF == SPF_UMIN) {
1079 // We can derive an upper bound on the result by taking the max of the
1080 // leading zero bits.
1081 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001082 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001083 }
1084
Chris Lattner965c7692008-06-02 01:18:21 +00001085 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001086 Known.One &= Known2.One;
1087 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001088 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001089 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001090 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001091 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001092 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001093 }
Chris Lattner965c7692008-06-02 01:18:21 +00001094 case Instruction::FPTrunc:
1095 case Instruction::FPExt:
1096 case Instruction::FPToUI:
1097 case Instruction::FPToSI:
1098 case Instruction::SIToFP:
1099 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001100 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001101 case Instruction::PtrToInt:
1102 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001103 // Fall through and handle them the same as zext/trunc.
1104 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001105 case Instruction::ZExt:
1106 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001107 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001108
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001109 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001110 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1111 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001112 Type *ScalarTy = SrcTy->getScalarType();
1113 SrcBitWidth = ScalarTy->isPointerTy() ?
1114 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1115 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001116
1117 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001118 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001119 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001120 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001121 // Any top bits are known to be zero.
1122 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001123 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001124 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001125 }
1126 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001127 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001128 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001129 // TODO: For now, not handling conversions like:
1130 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001131 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001132 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001133 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001134 }
1135 break;
1136 }
1137 case Instruction::SExt: {
1138 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001139 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001140
Craig Topperd938fd12017-05-03 22:07:25 +00001141 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001142 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001143 // If the sign bit of the input is known set or clear, then we know the
1144 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001145 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001146 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001147 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001148 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001149 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001150 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Sam McCalld0d43e62017-12-04 12:51:49 +00001151 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1152 APInt KZResult = KnownZero << ShiftAmt;
1153 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001154 // If this shift has "nsw" keyword, then the result is either a poison
1155 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001156 if (NSW && KnownZero.isSignBitSet())
1157 KZResult.setSignBit();
1158 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001159 };
1160
Sam McCalld0d43e62017-12-04 12:51:49 +00001161 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1162 APInt KOResult = KnownOne << ShiftAmt;
1163 if (NSW && KnownOne.isSignBitSet())
1164 KOResult.setSignBit();
1165 return KOResult;
1166 };
1167
1168 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001169 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001170 }
1171 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001172 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001173 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1174 APInt KZResult = KnownZero.lshr(ShiftAmt);
1175 // High bits known zero.
1176 KZResult.setHighBits(ShiftAmt);
1177 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001178 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001179
Sam McCalld0d43e62017-12-04 12:51:49 +00001180 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1181 return KnownOne.lshr(ShiftAmt);
1182 };
1183
1184 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001185 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001186 }
1187 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001188 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001189 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1190 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001191 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001192
Sam McCalld0d43e62017-12-04 12:51:49 +00001193 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1194 return KnownOne.ashr(ShiftAmt);
1195 };
1196
1197 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001198 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001199 }
Chris Lattner965c7692008-06-02 01:18:21 +00001200 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001201 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001202 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001203 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001204 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001205 }
Chris Lattner965c7692008-06-02 01:18:21 +00001206 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001207 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001208 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001209 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001210 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001211 }
1212 case Instruction::SRem:
1213 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001214 APInt RA = Rem->getValue().abs();
1215 if (RA.isPowerOf2()) {
1216 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001218
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001219 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001220 Known.Zero = Known2.Zero & LowBits;
1221 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001222
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001223 // If the first operand is non-negative or has all low bits zero, then
1224 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001225 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001226 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001227
1228 // If the first operand is negative and not all low bits are zero, then
1229 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001230 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001231 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001232
Craig Topperb45eabc2017-04-26 16:39:58 +00001233 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001234 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001235 }
1236 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001237
1238 // The sign bit is the LHS's sign bit, except when the result of the
1239 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001240 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001241 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001242 if (Known2.isNonNegative())
1243 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001244
Chris Lattner965c7692008-06-02 01:18:21 +00001245 break;
1246 case Instruction::URem: {
1247 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001248 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001249 if (RA.isPowerOf2()) {
1250 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001251 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1252 Known.Zero |= ~LowBits;
1253 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001254 break;
1255 }
1256 }
1257
1258 // Since the result is less than or equal to either operand, any leading
1259 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001260 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1261 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001262
Craig Topper8df66c62017-05-12 17:20:30 +00001263 unsigned Leaders =
1264 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001265 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001266 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001267 break;
1268 }
1269
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001270 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001271 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001272 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001274 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001275
Chris Lattner965c7692008-06-02 01:18:21 +00001276 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001277 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001278 break;
1279 }
1280 case Instruction::GetElementPtr: {
1281 // Analyze all of the subscripts of this getelementptr instruction
1282 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001283 KnownBits LocalKnown(BitWidth);
1284 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001285 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001286
1287 gep_type_iterator GTI = gep_type_begin(I);
1288 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1289 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001290 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001291 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001292
1293 // Handle case when index is vector zeroinitializer
1294 Constant *CIndex = cast<Constant>(Index);
1295 if (CIndex->isZeroValue())
1296 continue;
1297
1298 if (CIndex->getType()->isVectorTy())
1299 Index = CIndex->getSplatValue();
1300
Chris Lattner965c7692008-06-02 01:18:21 +00001301 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001302 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001303 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001304 TrailZ = std::min<unsigned>(TrailZ,
1305 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001306 } else {
1307 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001308 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001309 if (!IndexedTy->isSized()) {
1310 TrailZ = 0;
1311 break;
1312 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001313 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001314 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001315 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1316 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001317 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001318 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001319 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001320 }
1321 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001322
Craig Topperb45eabc2017-04-26 16:39:58 +00001323 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001324 break;
1325 }
1326 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001327 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001328 // Handle the case of a simple two-predecessor recurrence PHI.
1329 // There's a lot more that could theoretically be done here, but
1330 // this is sufficient to catch some interesting cases.
1331 if (P->getNumIncomingValues() == 2) {
1332 for (unsigned i = 0; i != 2; ++i) {
1333 Value *L = P->getIncomingValue(i);
1334 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001335 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001336 if (!LU)
1337 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001338 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001339 // Check for operations that have the property that if
1340 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001341 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001342 if (Opcode == Instruction::Add ||
1343 Opcode == Instruction::Sub ||
1344 Opcode == Instruction::And ||
1345 Opcode == Instruction::Or ||
1346 Opcode == Instruction::Mul) {
1347 Value *LL = LU->getOperand(0);
1348 Value *LR = LU->getOperand(1);
1349 // Find a recurrence.
1350 if (LL == I)
1351 L = LR;
1352 else if (LR == I)
1353 L = LL;
1354 else
1355 break;
1356 // Ok, we have a PHI of the form L op= R. Check for low
1357 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001358 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001359
1360 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001361 KnownBits Known3(Known);
1362 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001363
Craig Topper8df66c62017-05-12 17:20:30 +00001364 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1365 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001366
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001367 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1368 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1369 // If initial value of recurrence is nonnegative, and we are adding
1370 // a nonnegative number with nsw, the result can only be nonnegative
1371 // or poison value regardless of the number of times we execute the
1372 // add in phi recurrence. If initial value is negative and we are
1373 // adding a negative number with nsw, the result can only be
1374 // negative or poison value. Similar arguments apply to sub and mul.
1375 //
1376 // (add non-negative, non-negative) --> non-negative
1377 // (add negative, negative) --> negative
1378 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001379 if (Known2.isNonNegative() && Known3.isNonNegative())
1380 Known.makeNonNegative();
1381 else if (Known2.isNegative() && Known3.isNegative())
1382 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001383 }
1384
1385 // (sub nsw non-negative, negative) --> non-negative
1386 // (sub nsw negative, non-negative) --> negative
1387 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001388 if (Known2.isNonNegative() && Known3.isNegative())
1389 Known.makeNonNegative();
1390 else if (Known2.isNegative() && Known3.isNonNegative())
1391 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001392 }
1393
1394 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001395 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1396 Known3.isNonNegative())
1397 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001398 }
1399
Chris Lattner965c7692008-06-02 01:18:21 +00001400 break;
1401 }
1402 }
1403 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001404
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001405 // Unreachable blocks may have zero-operand PHI nodes.
1406 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001407 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001408
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001409 // Otherwise take the unions of the known bit sets of the operands,
1410 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001411 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001412 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001413 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001414 break;
1415
Craig Topperb45eabc2017-04-26 16:39:58 +00001416 Known.Zero.setAllBits();
1417 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001418 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001419 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001420 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001421
Craig Topperb45eabc2017-04-26 16:39:58 +00001422 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001423 // Recurse, but cap the recursion to one level, because we don't
1424 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001425 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1426 Known.Zero &= Known2.Zero;
1427 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001428 // If all bits have been ruled out, there's no need to check
1429 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001430 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001431 break;
1432 }
1433 }
Chris Lattner965c7692008-06-02 01:18:21 +00001434 break;
1435 }
1436 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001437 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001438 // If range metadata is attached to this call, set known bits from that,
1439 // and then intersect with known bits based on other properties of the
1440 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001441 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001442 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001443 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001444 computeKnownBits(RV, Known2, Depth + 1, Q);
1445 Known.Zero |= Known2.Zero;
1446 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001447 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001448 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001449 switch (II->getIntrinsicID()) {
1450 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001451 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001452 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1453 Known.Zero |= Known2.Zero.reverseBits();
1454 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001455 break;
Philip Reames675418e2015-10-06 20:20:45 +00001456 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001457 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1458 Known.Zero |= Known2.Zero.byteSwap();
1459 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001460 break;
Craig Topper868813f2017-05-08 17:22:34 +00001461 case Intrinsic::ctlz: {
1462 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1463 // If we have a known 1, its position is our upper bound.
1464 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001465 // If this call is undefined for 0, the result will be less than 2^n.
1466 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001467 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1468 unsigned LowBits = Log2_32(PossibleLZ)+1;
1469 Known.Zero.setBitsFrom(LowBits);
1470 break;
1471 }
1472 case Intrinsic::cttz: {
1473 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1474 // If we have a known 1, its position is our upper bound.
1475 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1476 // If this call is undefined for 0, the result will be less than 2^n.
1477 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1478 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1479 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001480 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001481 break;
1482 }
1483 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001484 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001485 // We can bound the space the count needs. Also, bits known to be zero
1486 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001487 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001488 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001489 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001490 // TODO: we could bound KnownOne using the lower bound on the number
1491 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001492 break;
1493 }
Chad Rosierb3628842011-05-26 23:13:19 +00001494 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001495 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001496 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001497 }
1498 }
1499 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001500 case Instruction::ExtractElement:
1501 // Look through extract element. At the moment we keep this simple and skip
1502 // tracking the specific element. But at least we might find information
1503 // valid for all elements of the vector (for example if vector is sign
1504 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001505 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001506 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001507 case Instruction::ExtractValue:
1508 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001509 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001510 if (EVI->getNumIndices() != 1) break;
1511 if (EVI->getIndices()[0] == 0) {
1512 switch (II->getIntrinsicID()) {
1513 default: break;
1514 case Intrinsic::uadd_with_overflow:
1515 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001516 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001517 II->getArgOperand(1), false, Known, Known2,
1518 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001519 break;
1520 case Intrinsic::usub_with_overflow:
1521 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001522 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001523 II->getArgOperand(1), false, Known, Known2,
1524 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001525 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001526 case Intrinsic::umul_with_overflow:
1527 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001528 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001529 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001530 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001531 }
1532 }
1533 }
Chris Lattner965c7692008-06-02 01:18:21 +00001534 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001535}
1536
1537/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001538/// them.
1539KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1540 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1541 computeKnownBits(V, Known, Depth, Q);
1542 return Known;
1543}
1544
1545/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001546/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001547///
1548/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1549/// we cannot optimize based on the assumption that it is zero without changing
1550/// it to be an explicit zero. If we don't change it to zero, other code could
1551/// optimized based on the contradictory assumption that it is non-zero.
1552/// Because instcombine aggressively folds operations with undef args anyway,
1553/// this won't lose us code quality.
1554///
1555/// This function is defined on values with integer type, values with pointer
1556/// type, and vectors of integers. In the case
1557/// where V is a vector, known zero, and known one values are the
1558/// same width as the vector element, and the bit is set only if it is true
1559/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001560void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1561 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001562 assert(V && "No Value?");
1563 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001564 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001565
Craig Topperfde47232017-07-09 07:04:03 +00001566 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001567 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001568 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001569
1570 Type *ScalarTy = V->getType()->getScalarType();
1571 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1572 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1573 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001574 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001575 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001576
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001577 const APInt *C;
1578 if (match(V, m_APInt(C))) {
1579 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001580 Known.One = *C;
1581 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001582 return;
1583 }
1584 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001585 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001586 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001587 return;
1588 }
1589 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001590 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001591 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001592 // We know that CDS must be a vector of integers. Take the intersection of
1593 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001594 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001595 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001596 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001597 Known.Zero &= ~Elt;
1598 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001599 }
1600 return;
1601 }
1602
Pete Cooper35b00d52016-08-13 01:05:32 +00001603 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001604 // We know that CV must be a vector of integers. Take the intersection of
1605 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001606 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001607 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1608 Constant *Element = CV->getAggregateElement(i);
1609 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1610 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001611 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001612 return;
1613 }
Craig Topperb98ee582017-10-21 16:35:39 +00001614 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001615 Known.Zero &= ~Elt;
1616 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001617 }
1618 return;
1619 }
1620
Jingyue Wu12b0c282015-06-15 05:46:29 +00001621 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001622 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001623
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001624 // We can't imply anything about undefs.
1625 if (isa<UndefValue>(V))
1626 return;
1627
1628 // There's no point in looking through other users of ConstantData for
1629 // assumptions. Confirm that we've handled them all.
1630 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1631
Jingyue Wu12b0c282015-06-15 05:46:29 +00001632 // Limit search depth.
1633 // All recursive calls that increase depth must come after this.
1634 if (Depth == MaxDepth)
1635 return;
1636
1637 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1638 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001639 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001640 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001641 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001642 return;
1643 }
1644
Pete Cooper35b00d52016-08-13 01:05:32 +00001645 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001646 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001647
Craig Topperb45eabc2017-04-26 16:39:58 +00001648 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001649 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001650 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001651 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001652 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001653 }
1654
Craig Topperb45eabc2017-04-26 16:39:58 +00001655 // computeKnownBitsFromAssume strictly refines Known.
1656 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001657
1658 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001659 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001660
Craig Topperb45eabc2017-04-26 16:39:58 +00001661 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001662}
1663
Sanjay Patelaee84212014-11-04 16:27:42 +00001664/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001665/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001666/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001667/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001668bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001669 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001670 assert(Depth <= MaxDepth && "Limit Search Depth");
1671
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001672 // Attempt to match against constants.
1673 if (OrZero && match(V, m_Power2OrZero()))
1674 return true;
1675 if (match(V, m_Power2()))
1676 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001677
1678 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1679 // it is shifted off the end then the result is undefined.
1680 if (match(V, m_Shl(m_One(), m_Value())))
1681 return true;
1682
Craig Topperbcfd2d12017-04-20 16:56:25 +00001683 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1684 // the bottom. If it is shifted off the bottom then the result is undefined.
1685 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001686 return true;
1687
1688 // The remaining tests are all recursive, so bail out if we hit the limit.
1689 if (Depth++ == MaxDepth)
1690 return false;
1691
Craig Topper9f008862014-04-15 04:59:12 +00001692 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001693 // A shift left or a logical shift right of a power of two is a power of two
1694 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001695 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001696 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001697 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001698
Pete Cooper35b00d52016-08-13 01:05:32 +00001699 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001700 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001701
Pete Cooper35b00d52016-08-13 01:05:32 +00001702 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001703 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1704 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001705
Duncan Sandsba286d72011-10-26 20:55:21 +00001706 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1707 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001708 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1709 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001710 return true;
1711 // X & (-X) is always a power of two or zero.
1712 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1713 return true;
1714 return false;
1715 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001716
David Majnemerb7d54092013-07-30 21:01:36 +00001717 // Adding a power-of-two or zero to the same power-of-two or zero yields
1718 // either the original power-of-two, a larger power-of-two or zero.
1719 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001720 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001721 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1722 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1723 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001724 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001725 return true;
1726 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1727 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001728 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001729 return true;
1730
1731 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001732 KnownBits LHSBits(BitWidth);
1733 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001734
Craig Topperb45eabc2017-04-26 16:39:58 +00001735 KnownBits RHSBits(BitWidth);
1736 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001737 // If i8 V is a power of two or zero:
1738 // ZeroBits: 1 1 1 0 1 1 1 1
1739 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001740 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001741 // If OrZero isn't set, we cannot give back a zero result.
1742 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001743 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001744 return true;
1745 }
1746 }
David Majnemerbeab5672013-05-18 19:30:37 +00001747
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001748 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001749 // is a power of two only if the first operand is a power of two and not
1750 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001751 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1752 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001753 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001754 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001755 }
1756
Duncan Sandsd3951082011-01-25 09:38:29 +00001757 return false;
1758}
1759
Chandler Carruth80d3e562012-12-07 02:08:58 +00001760/// \brief Test whether a GEP's result is known to be non-null.
1761///
1762/// Uses properties inherent in a GEP to try to determine whether it is known
1763/// to be non-null.
1764///
1765/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001766static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001767 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001768 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1769 return false;
1770
1771 // FIXME: Support vector-GEPs.
1772 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1773
1774 // If the base pointer is non-null, we cannot walk to a null address with an
1775 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001776 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001777 return true;
1778
Chandler Carruth80d3e562012-12-07 02:08:58 +00001779 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1780 // If so, then the GEP cannot produce a null pointer, as doing so would
1781 // inherently violate the inbounds contract within address space zero.
1782 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1783 GTI != GTE; ++GTI) {
1784 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001785 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001786 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1787 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001788 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001789 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1790 if (ElementOffset > 0)
1791 return true;
1792 continue;
1793 }
1794
1795 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001796 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001797 continue;
1798
1799 // Fast path the constant operand case both for efficiency and so we don't
1800 // increment Depth when just zipping down an all-constant GEP.
1801 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1802 if (!OpC->isZero())
1803 return true;
1804 continue;
1805 }
1806
1807 // We post-increment Depth here because while isKnownNonZero increments it
1808 // as well, when we pop back up that increment won't persist. We don't want
1809 // to recurse 10k times just because we have 10k GEP operands. We don't
1810 // bail completely out because we want to handle constant GEPs regardless
1811 // of depth.
1812 if (Depth++ >= MaxDepth)
1813 continue;
1814
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001815 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001816 return true;
1817 }
1818
1819 return false;
1820}
1821
Nuno Lopes404f1062017-09-09 18:23:11 +00001822static bool isKnownNonNullFromDominatingCondition(const Value *V,
1823 const Instruction *CtxI,
1824 const DominatorTree *DT) {
1825 assert(V->getType()->isPointerTy() && "V must be pointer type");
1826 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1827
1828 if (!CtxI || !DT)
1829 return false;
1830
1831 unsigned NumUsesExplored = 0;
1832 for (auto *U : V->users()) {
1833 // Avoid massive lists
1834 if (NumUsesExplored >= DomConditionsMaxUses)
1835 break;
1836 NumUsesExplored++;
1837
1838 // If the value is used as an argument to a call or invoke, then argument
1839 // attributes may provide an answer about null-ness.
1840 if (auto CS = ImmutableCallSite(U))
1841 if (auto *CalledFunc = CS.getCalledFunction())
1842 for (const Argument &Arg : CalledFunc->args())
1843 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1844 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1845 return true;
1846
1847 // Consider only compare instructions uniquely controlling a branch
1848 CmpInst::Predicate Pred;
1849 if (!match(const_cast<User *>(U),
1850 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1851 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1852 continue;
1853
1854 for (auto *CmpU : U->users()) {
1855 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
1856 assert(BI->isConditional() && "uses a comparison!");
1857
1858 BasicBlock *NonNullSuccessor =
1859 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1860 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1861 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1862 return true;
1863 } else if (Pred == ICmpInst::ICMP_NE &&
1864 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
1865 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
1866 return true;
1867 }
1868 }
1869 }
1870
1871 return false;
1872}
1873
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001874/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1875/// ensure that the value it's attached to is never Value? 'RangeType' is
1876/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001877static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001878 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1879 assert(NumRanges >= 1);
1880 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001881 ConstantInt *Lower =
1882 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1883 ConstantInt *Upper =
1884 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001885 ConstantRange Range(Lower->getValue(), Upper->getValue());
1886 if (Range.contains(Value))
1887 return false;
1888 }
1889 return true;
1890}
1891
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001892/// Return true if the given value is known to be non-zero when defined. For
1893/// vectors, return true if every element is known to be non-zero when
1894/// defined. For pointers, if the context instruction and dominator tree are
1895/// specified, perform context-sensitive analysis and return true if the
1896/// pointer couldn't possibly be null at the specified instruction.
1897/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001898bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001899 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 if (C->isNullValue())
1901 return false;
1902 if (isa<ConstantInt>(C))
1903 // Must be non-zero due to null test above.
1904 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001905
1906 // For constant vectors, check that all elements are undefined or known
1907 // non-zero to determine that the whole vector is known non-zero.
1908 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1909 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1910 Constant *Elt = C->getAggregateElement(i);
1911 if (!Elt || Elt->isNullValue())
1912 return false;
1913 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1914 return false;
1915 }
1916 return true;
1917 }
1918
Nuno Lopes404f1062017-09-09 18:23:11 +00001919 // A global variable in address space 0 is non null unless extern weak
1920 // or an absolute symbol reference. Other address spaces may have null as a
1921 // valid address for a global, so we can't assume anything.
1922 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1923 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1924 GV->getType()->getAddressSpace() == 0)
1925 return true;
1926 } else
1927 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00001928 }
1929
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001930 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001931 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001932 // If the possible ranges don't contain zero, then the value is
1933 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001934 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001935 const APInt ZeroValue(Ty->getBitWidth(), 0);
1936 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1937 return true;
1938 }
1939 }
1940 }
1941
Nuno Lopes404f1062017-09-09 18:23:11 +00001942 // Check for pointer simplifications.
1943 if (V->getType()->isPointerTy()) {
1944 // Alloca never returns null, malloc might.
1945 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1946 return true;
1947
1948 // A byval, inalloca, or nonnull argument is never null.
1949 if (const Argument *A = dyn_cast<Argument>(V))
1950 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1951 return true;
1952
1953 // A Load tagged with nonnull metadata is never null.
1954 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
1955 if (LI->getMetadata(LLVMContext::MD_nonnull))
1956 return true;
1957
1958 if (auto CS = ImmutableCallSite(V))
1959 if (CS.isReturnNonNull())
1960 return true;
1961 }
1962
Duncan Sandsd3951082011-01-25 09:38:29 +00001963 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001964 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001965 return false;
1966
Nuno Lopes404f1062017-09-09 18:23:11 +00001967 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001968 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001969 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001970 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001971
Pete Cooper35b00d52016-08-13 01:05:32 +00001972 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001973 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001974 return true;
1975 }
1976
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001977 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001978
1979 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001980 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001981 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001982 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001983
1984 // ext X != 0 if X != 0.
1985 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001986 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001987
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001988 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001989 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001990 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001991 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001992 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001993 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001994 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001995
Craig Topperb45eabc2017-04-26 16:39:58 +00001996 KnownBits Known(BitWidth);
1997 computeKnownBits(X, Known, Depth, Q);
1998 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001999 return true;
2000 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002001 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002002 // defined if the sign bit is shifted off the end.
2003 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002004 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002005 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002006 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002007 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002008
Craig Topper6e11a052017-05-08 16:22:48 +00002009 KnownBits Known = computeKnownBits(X, Depth, Q);
2010 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002011 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002012
2013 // If the shifter operand is a constant, and all of the bits shifted
2014 // out are known to be zero, and X is known non-zero then at least one
2015 // non-zero bit must remain.
2016 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002017 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2018 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002019 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002020 return true;
2021 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002022 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002023 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002024 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002025 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002026 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002027 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002028 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002029 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002030 // X + Y.
2031 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002032 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2033 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002034
2035 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002036 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002037 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002038 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002039 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002040
2041 // If X and Y are both negative (as signed values) then their sum is not
2042 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002043 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002044 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2045 // The sign bit of X is set. If some other bit is set then X is not equal
2046 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002047 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002048 return true;
2049 // The sign bit of Y is set. If some other bit is set then Y is not equal
2050 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002051 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002052 return true;
2053 }
2054
2055 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002056 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002057 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002058 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002059 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002060 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002061 return true;
2062 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002063 // X * Y.
2064 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002065 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002066 // If X and Y are non-zero then so is X * Y as long as the multiplication
2067 // does not overflow.
2068 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002069 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002070 return true;
2071 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002072 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002073 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002074 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2075 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002076 return true;
2077 }
James Molloy897048b2015-09-29 14:08:45 +00002078 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002079 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002080 // Try and detect a recurrence that monotonically increases from a
2081 // starting value, as these are common as induction variables.
2082 if (PN->getNumIncomingValues() == 2) {
2083 Value *Start = PN->getIncomingValue(0);
2084 Value *Induction = PN->getIncomingValue(1);
2085 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2086 std::swap(Start, Induction);
2087 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2088 if (!C->isZero() && !C->isNegative()) {
2089 ConstantInt *X;
2090 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2091 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2092 !X->isNegative())
2093 return true;
2094 }
2095 }
2096 }
Jun Bum Limca832662016-02-01 17:03:07 +00002097 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002098 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002099 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002100 });
2101 if (AllNonZeroConstants)
2102 return true;
James Molloy897048b2015-09-29 14:08:45 +00002103 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002104
Craig Topperb45eabc2017-04-26 16:39:58 +00002105 KnownBits Known(BitWidth);
2106 computeKnownBits(V, Known, Depth, Q);
2107 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002108}
2109
James Molloy1d88d6f2015-10-22 13:18:42 +00002110/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002111static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2112 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002113 if (!BO || BO->getOpcode() != Instruction::Add)
2114 return false;
2115 Value *Op = nullptr;
2116 if (V2 == BO->getOperand(0))
2117 Op = BO->getOperand(1);
2118 else if (V2 == BO->getOperand(1))
2119 Op = BO->getOperand(0);
2120 else
2121 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002122 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002123}
2124
2125/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002126static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002127 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002128 return false;
2129 if (V1->getType() != V2->getType())
2130 // We can't look through casts yet.
2131 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002132 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002133 return true;
2134
Craig Topper3002d5b2017-06-06 07:13:15 +00002135 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002136 // Are any known bits in V1 contradictory to known bits in V2? If V1
2137 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002138 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2139 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002140
Craig Topper8365df82017-06-06 07:13:09 +00002141 if (Known1.Zero.intersects(Known2.One) ||
2142 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002143 return true;
2144 }
2145 return false;
2146}
2147
Sanjay Patelaee84212014-11-04 16:27:42 +00002148/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2149/// simplify operations downstream. Mask is known to be zero for bits that V
2150/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002151///
2152/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002153/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002154/// where V is a vector, the mask, known zero, and known one values are the
2155/// same width as the vector element, and the bit is set only if it is true
2156/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002157bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002158 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002159 KnownBits Known(Mask.getBitWidth());
2160 computeKnownBits(V, Known, Depth, Q);
2161 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002162}
2163
Sanjay Patela06d9892016-06-22 19:20:59 +00002164/// For vector constants, loop over the elements and find the constant with the
2165/// minimum number of sign bits. Return 0 if the value is not a vector constant
2166/// or if any element was not analyzed; otherwise, return the count for the
2167/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002168static unsigned computeNumSignBitsVectorConstant(const Value *V,
2169 unsigned TyBits) {
2170 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002171 if (!CV || !CV->getType()->isVectorTy())
2172 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002173
Sanjay Patela06d9892016-06-22 19:20:59 +00002174 unsigned MinSignBits = TyBits;
2175 unsigned NumElts = CV->getType()->getVectorNumElements();
2176 for (unsigned i = 0; i != NumElts; ++i) {
2177 // If we find a non-ConstantInt, bail out.
2178 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2179 if (!Elt)
2180 return 0;
2181
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002182 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002183 }
2184
2185 return MinSignBits;
2186}
Chris Lattner965c7692008-06-02 01:18:21 +00002187
Sanjoy Das39a684d2017-02-25 20:30:45 +00002188static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2189 const Query &Q);
2190
2191static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2192 const Query &Q) {
2193 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2194 assert(Result > 0 && "At least one sign bit needs to be present!");
2195 return Result;
2196}
2197
Sanjay Patelaee84212014-11-04 16:27:42 +00002198/// Return the number of times the sign bit of the register is replicated into
2199/// the other bits. We know that at least 1 bit is always equal to the sign bit
2200/// (itself), but other cases can give us information. For example, immediately
2201/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002202/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002203/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002204static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2205 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002206 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002207
2208 // We return the minimum number of sign bits that are guaranteed to be present
2209 // in V, so for undef we have to conservatively return 1. We don't have the
2210 // same behavior for poison though -- that's a FIXME today.
2211
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002212 Type *ScalarTy = V->getType()->getScalarType();
2213 unsigned TyBits = ScalarTy->isPointerTy() ?
2214 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2215 Q.DL.getTypeSizeInBits(ScalarTy);
2216
Chris Lattner965c7692008-06-02 01:18:21 +00002217 unsigned Tmp, Tmp2;
2218 unsigned FirstAnswer = 1;
2219
Jay Foada0653a32014-05-14 21:14:37 +00002220 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002221 // below.
2222
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002223 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002224 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002225
Pete Cooper35b00d52016-08-13 01:05:32 +00002226 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002227 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002228 default: break;
2229 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002230 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002231 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002232
Nadav Rotemc99a3872015-03-06 00:23:58 +00002233 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002234 const APInt *Denominator;
2235 // sdiv X, C -> adds log(C) sign bits.
2236 if (match(U->getOperand(1), m_APInt(Denominator))) {
2237
2238 // Ignore non-positive denominator.
2239 if (!Denominator->isStrictlyPositive())
2240 break;
2241
2242 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002243 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002244
2245 // Add floor(log(C)) bits to the numerator bits.
2246 return std::min(TyBits, NumBits + Denominator->logBase2());
2247 }
2248 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002249 }
2250
2251 case Instruction::SRem: {
2252 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002253 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2254 // positive constant. This let us put a lower bound on the number of sign
2255 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002256 if (match(U->getOperand(1), m_APInt(Denominator))) {
2257
2258 // Ignore non-positive denominator.
2259 if (!Denominator->isStrictlyPositive())
2260 break;
2261
2262 // Calculate the incoming numerator bits. SRem by a positive constant
2263 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002264 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002265 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002266
2267 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002268 // denominator. Given that the denominator is positive, there are two
2269 // cases:
2270 //
2271 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2272 // (1 << ceilLogBase2(C)).
2273 //
2274 // 2. the numerator is negative. Then the result range is (-C,0] and
2275 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2276 //
2277 // Thus a lower bound on the number of sign bits is `TyBits -
2278 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002279
Sanjoy Dase561fee2015-03-25 22:33:53 +00002280 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002281 return std::max(NumrBits, ResBits);
2282 }
2283 break;
2284 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002285
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002286 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002287 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002288 // ashr X, C -> adds C sign bits. Vectors too.
2289 const APInt *ShAmt;
2290 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002291 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002292 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002293 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002294 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002295 if (Tmp > TyBits) Tmp = TyBits;
2296 }
2297 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002298 }
2299 case Instruction::Shl: {
2300 const APInt *ShAmt;
2301 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002302 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002303 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002304 if (ShAmt->uge(TyBits) || // Bad shift.
2305 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002306 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002307 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002308 }
2309 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002310 }
Chris Lattner965c7692008-06-02 01:18:21 +00002311 case Instruction::And:
2312 case Instruction::Or:
2313 case Instruction::Xor: // NOT is handled here.
2314 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002315 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002316 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002317 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002318 FirstAnswer = std::min(Tmp, Tmp2);
2319 // We computed what we know about the sign bits as our first
2320 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002321 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002322 }
2323 break;
2324
2325 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002326 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002327 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002328 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002329 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002330
Chris Lattner965c7692008-06-02 01:18:21 +00002331 case Instruction::Add:
2332 // Add can have at most one carry bit. Thus we know that the output
2333 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002334 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002335 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002336
Chris Lattner965c7692008-06-02 01:18:21 +00002337 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002338 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002339 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002340 KnownBits Known(TyBits);
2341 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002342
Chris Lattner965c7692008-06-02 01:18:21 +00002343 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2344 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002345 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002346 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002347
Chris Lattner965c7692008-06-02 01:18:21 +00002348 // If we are subtracting one from a positive number, there is no carry
2349 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002350 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002351 return Tmp;
2352 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002353
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002354 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002355 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002356 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002357
Chris Lattner965c7692008-06-02 01:18:21 +00002358 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002359 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002360 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002361
Chris Lattner965c7692008-06-02 01:18:21 +00002362 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002363 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002364 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002365 KnownBits Known(TyBits);
2366 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002367 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2368 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002369 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002370 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002371
Chris Lattner965c7692008-06-02 01:18:21 +00002372 // If the input is known to be positive (the sign bit is known clear),
2373 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002374 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002375 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002376
Chris Lattner965c7692008-06-02 01:18:21 +00002377 // Otherwise, we treat this like a SUB.
2378 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002379
Chris Lattner965c7692008-06-02 01:18:21 +00002380 // Sub can have at most one carry bit. Thus we know that the output
2381 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002382 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002383 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002384 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002385
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002386 case Instruction::Mul: {
2387 // The output of the Mul can be at most twice the valid bits in the inputs.
2388 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2389 if (SignBitsOp0 == 1) return 1; // Early out.
2390 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2391 if (SignBitsOp1 == 1) return 1;
2392 unsigned OutValidBits =
2393 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2394 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2395 }
2396
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002397 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002398 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002399 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002400 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002401 if (NumIncomingValues > 4) break;
2402 // Unreachable blocks may have zero-operand PHI nodes.
2403 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002404
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002405 // Take the minimum of all incoming values. This can't infinitely loop
2406 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002407 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002408 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002409 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002410 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002411 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002412 }
2413 return Tmp;
2414 }
2415
Chris Lattner965c7692008-06-02 01:18:21 +00002416 case Instruction::Trunc:
2417 // FIXME: it's tricky to do anything useful for this, but it is an important
2418 // case for targets like X86.
2419 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002420
2421 case Instruction::ExtractElement:
2422 // Look through extract element. At the moment we keep this simple and skip
2423 // tracking the specific element. But at least we might find information
2424 // valid for all elements of the vector (for example if vector is sign
2425 // extended, shifted, etc).
2426 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002427 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002428
Chris Lattner965c7692008-06-02 01:18:21 +00002429 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2430 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002431
2432 // If we can examine all elements of a vector constant successfully, we're
2433 // done (we can't do any better than that). If not, keep trying.
2434 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2435 return VecSignBits;
2436
Craig Topperb45eabc2017-04-26 16:39:58 +00002437 KnownBits Known(TyBits);
2438 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002439
Sanjay Patele0536212016-06-23 17:41:59 +00002440 // If we know that the sign bit is either zero or one, determine the number of
2441 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002442 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002443}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002444
Sanjay Patelaee84212014-11-04 16:27:42 +00002445/// This function computes the integer multiple of Base that equals V.
2446/// If successful, it returns true and returns the multiple in
2447/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002448/// through SExt instructions only if LookThroughSExt is true.
2449bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002450 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002451 const unsigned MaxDepth = 6;
2452
Dan Gohman6a976bb2009-11-18 00:58:27 +00002453 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002454 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002455 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002456
Chris Lattner229907c2011-07-18 04:54:35 +00002457 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002458
Dan Gohman6a976bb2009-11-18 00:58:27 +00002459 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002460
2461 if (Base == 0)
2462 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002463
Victor Hernandez47444882009-11-10 08:28:35 +00002464 if (Base == 1) {
2465 Multiple = V;
2466 return true;
2467 }
2468
2469 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2470 Constant *BaseVal = ConstantInt::get(T, Base);
2471 if (CO && CO == BaseVal) {
2472 // Multiple is 1.
2473 Multiple = ConstantInt::get(T, 1);
2474 return true;
2475 }
2476
2477 if (CI && CI->getZExtValue() % Base == 0) {
2478 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002479 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002480 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002481
Victor Hernandez47444882009-11-10 08:28:35 +00002482 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002483
Victor Hernandez47444882009-11-10 08:28:35 +00002484 Operator *I = dyn_cast<Operator>(V);
2485 if (!I) return false;
2486
2487 switch (I->getOpcode()) {
2488 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002489 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002490 if (!LookThroughSExt) return false;
2491 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002492 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002493 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002494 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2495 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002496 case Instruction::Shl:
2497 case Instruction::Mul: {
2498 Value *Op0 = I->getOperand(0);
2499 Value *Op1 = I->getOperand(1);
2500
2501 if (I->getOpcode() == Instruction::Shl) {
2502 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2503 if (!Op1CI) return false;
2504 // Turn Op0 << Op1 into Op0 * 2^Op1
2505 APInt Op1Int = Op1CI->getValue();
2506 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002507 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002508 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002509 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002510 }
2511
Craig Topper9f008862014-04-15 04:59:12 +00002512 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002513 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2514 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2515 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002516 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002517 MulC->getType()->getPrimitiveSizeInBits())
2518 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002519 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002520 MulC->getType()->getPrimitiveSizeInBits())
2521 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002522
Chris Lattner72d283c2010-09-05 17:20:46 +00002523 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2524 Multiple = ConstantExpr::getMul(MulC, Op1C);
2525 return true;
2526 }
Victor Hernandez47444882009-11-10 08:28:35 +00002527
2528 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2529 if (Mul0CI->getValue() == 1) {
2530 // V == Base * Op1, so return Op1
2531 Multiple = Op1;
2532 return true;
2533 }
2534 }
2535
Craig Topper9f008862014-04-15 04:59:12 +00002536 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002537 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2538 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2539 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002540 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002541 MulC->getType()->getPrimitiveSizeInBits())
2542 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002543 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002544 MulC->getType()->getPrimitiveSizeInBits())
2545 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002546
Chris Lattner72d283c2010-09-05 17:20:46 +00002547 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2548 Multiple = ConstantExpr::getMul(MulC, Op0C);
2549 return true;
2550 }
Victor Hernandez47444882009-11-10 08:28:35 +00002551
2552 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2553 if (Mul1CI->getValue() == 1) {
2554 // V == Base * Op0, so return Op0
2555 Multiple = Op0;
2556 return true;
2557 }
2558 }
Victor Hernandez47444882009-11-10 08:28:35 +00002559 }
2560 }
2561
2562 // We could not determine if V is a multiple of Base.
2563 return false;
2564}
2565
David Majnemerb4b27232016-04-19 19:10:21 +00002566Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2567 const TargetLibraryInfo *TLI) {
2568 const Function *F = ICS.getCalledFunction();
2569 if (!F)
2570 return Intrinsic::not_intrinsic;
2571
2572 if (F->isIntrinsic())
2573 return F->getIntrinsicID();
2574
2575 if (!TLI)
2576 return Intrinsic::not_intrinsic;
2577
David L. Jonesd21529f2017-01-23 23:16:46 +00002578 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002579 // We're going to make assumptions on the semantics of the functions, check
2580 // that the target knows that it's available in this environment and it does
2581 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002582 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2583 return Intrinsic::not_intrinsic;
2584
2585 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002586 return Intrinsic::not_intrinsic;
2587
2588 // Otherwise check if we have a call to a function that can be turned into a
2589 // vector intrinsic.
2590 switch (Func) {
2591 default:
2592 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002593 case LibFunc_sin:
2594 case LibFunc_sinf:
2595 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002596 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002597 case LibFunc_cos:
2598 case LibFunc_cosf:
2599 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002600 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002601 case LibFunc_exp:
2602 case LibFunc_expf:
2603 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002604 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002605 case LibFunc_exp2:
2606 case LibFunc_exp2f:
2607 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002608 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002609 case LibFunc_log:
2610 case LibFunc_logf:
2611 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002612 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002613 case LibFunc_log10:
2614 case LibFunc_log10f:
2615 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002616 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002617 case LibFunc_log2:
2618 case LibFunc_log2f:
2619 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002620 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002621 case LibFunc_fabs:
2622 case LibFunc_fabsf:
2623 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002624 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002625 case LibFunc_fmin:
2626 case LibFunc_fminf:
2627 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002628 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002629 case LibFunc_fmax:
2630 case LibFunc_fmaxf:
2631 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002632 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002633 case LibFunc_copysign:
2634 case LibFunc_copysignf:
2635 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002636 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002637 case LibFunc_floor:
2638 case LibFunc_floorf:
2639 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002640 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002641 case LibFunc_ceil:
2642 case LibFunc_ceilf:
2643 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002644 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002645 case LibFunc_trunc:
2646 case LibFunc_truncf:
2647 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002648 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002649 case LibFunc_rint:
2650 case LibFunc_rintf:
2651 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002652 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002653 case LibFunc_nearbyint:
2654 case LibFunc_nearbyintf:
2655 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002656 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002657 case LibFunc_round:
2658 case LibFunc_roundf:
2659 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002660 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002661 case LibFunc_pow:
2662 case LibFunc_powf:
2663 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002664 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002665 case LibFunc_sqrt:
2666 case LibFunc_sqrtf:
2667 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002668 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002669 }
2670
2671 return Intrinsic::not_intrinsic;
2672}
2673
Sanjay Patelaee84212014-11-04 16:27:42 +00002674/// Return true if we can prove that the specified FP value is never equal to
2675/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002676///
2677/// NOTE: this function will need to be revisited when we support non-default
2678/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002679bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2680 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002681 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002682 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002683
Sanjay Patel20df88a2017-11-13 17:56:23 +00002684 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002685 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002686 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002687
Sanjay Patel20df88a2017-11-13 17:56:23 +00002688 auto *Op = dyn_cast<Operator>(V);
2689 if (!Op)
2690 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002691
Sanjay Patel20df88a2017-11-13 17:56:23 +00002692 // Check if the nsz fast-math flag is set.
2693 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002694 if (FPO->hasNoSignedZeros())
2695 return true;
2696
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002697 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002698 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002699 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002700
Chris Lattnera12a6de2008-06-02 01:29:46 +00002701 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002702 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002703 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002704
Sanjay Patel20df88a2017-11-13 17:56:23 +00002705 if (auto *Call = dyn_cast<CallInst>(Op)) {
2706 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002707 switch (IID) {
2708 default:
2709 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002710 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002711 case Intrinsic::sqrt:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002712 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002713 // fabs(x) != -0.0
2714 case Intrinsic::fabs:
2715 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002716 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002717 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002718
Chris Lattnera12a6de2008-06-02 01:29:46 +00002719 return false;
2720}
2721
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002722/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2723/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2724/// bit despite comparing equal.
2725static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2726 const TargetLibraryInfo *TLI,
2727 bool SignBitOnly,
2728 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002729 // TODO: This function does not do the right thing when SignBitOnly is true
2730 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2731 // which flips the sign bits of NaNs. See
2732 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2733
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002734 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2735 return !CFP->getValueAPF().isNegative() ||
2736 (!SignBitOnly && CFP->getValueAPF().isZero());
2737 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002738
Craig Topper69c89722018-02-26 22:33:17 +00002739 // Handle vector of constants.
2740 if (auto *CV = dyn_cast<Constant>(V)) {
2741 if (CV->getType()->isVectorTy()) {
2742 unsigned NumElts = CV->getType()->getVectorNumElements();
2743 for (unsigned i = 0; i != NumElts; ++i) {
2744 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2745 if (!CFP)
2746 return false;
2747 if (CFP->getValueAPF().isNegative() &&
2748 (SignBitOnly || !CFP->getValueAPF().isZero()))
2749 return false;
2750 }
2751
2752 // All non-negative ConstantFPs.
2753 return true;
2754 }
2755 }
2756
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002757 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002758 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002759
2760 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002761 if (!I)
2762 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002763
2764 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002765 default:
2766 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002767 // Unsigned integers are always nonnegative.
2768 case Instruction::UIToFP:
2769 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002770 case Instruction::FMul:
2771 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002772 if (I->getOperand(0) == I->getOperand(1) &&
2773 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002774 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002775
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002776 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002777 case Instruction::FAdd:
2778 case Instruction::FDiv:
2779 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002780 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2781 Depth + 1) &&
2782 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2783 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002784 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002785 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2786 Depth + 1) &&
2787 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2788 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002789 case Instruction::FPExt:
2790 case Instruction::FPTrunc:
2791 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002792 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2793 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002794 case Instruction::ExtractElement:
2795 // Look through extract element. At the moment we keep this simple and skip
2796 // tracking the specific element. But at least we might find information
2797 // valid for all elements of the vector.
2798 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2799 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002800 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002801 const auto *CI = cast<CallInst>(I);
2802 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002803 switch (IID) {
2804 default:
2805 break;
2806 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002807 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2808 Depth + 1) ||
2809 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2810 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002811 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002812 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2813 Depth + 1) &&
2814 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2815 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002816 case Intrinsic::exp:
2817 case Intrinsic::exp2:
2818 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002819 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002820
2821 case Intrinsic::sqrt:
2822 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2823 if (!SignBitOnly)
2824 return true;
2825 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2826 CannotBeNegativeZero(CI->getOperand(0), TLI));
2827
David Majnemer3ee5f342016-04-13 06:55:52 +00002828 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002829 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002830 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002831 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002832 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002833 }
Justin Lebar322c1272017-01-27 00:58:34 +00002834 // TODO: This is not correct. Given that exp is an integer, here are the
2835 // ways that pow can return a negative value:
2836 //
2837 // pow(x, exp) --> negative if exp is odd and x is negative.
2838 // pow(-0, exp) --> -inf if exp is negative odd.
2839 // pow(-0, exp) --> -0 if exp is positive odd.
2840 // pow(-inf, exp) --> -0 if exp is negative odd.
2841 // pow(-inf, exp) --> -inf if exp is positive odd.
2842 //
2843 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2844 // but we must return false if x == -0. Unfortunately we do not currently
2845 // have a way of expressing this constraint. See details in
2846 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002847 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2848 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002849
David Majnemer3ee5f342016-04-13 06:55:52 +00002850 case Intrinsic::fma:
2851 case Intrinsic::fmuladd:
2852 // x*x+y is non-negative if y is non-negative.
2853 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002854 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2855 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2856 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002857 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002858 break;
2859 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002860 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002861}
2862
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002863bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2864 const TargetLibraryInfo *TLI) {
2865 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2866}
2867
2868bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2869 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2870}
2871
Sanjay Patel6840c5f2017-09-05 23:13:13 +00002872bool llvm::isKnownNeverNaN(const Value *V) {
2873 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
2874
2875 // If we're told that NaNs won't happen, assume they won't.
2876 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
2877 if (FPMathOp->hasNoNaNs())
2878 return true;
2879
2880 // TODO: Handle instructions and potentially recurse like other 'isKnown'
2881 // functions. For example, the result of sitofp is never NaN.
2882
2883 // Handle scalar constants.
2884 if (auto *CFP = dyn_cast<ConstantFP>(V))
2885 return !CFP->isNaN();
2886
2887 // Bail out for constant expressions, but try to handle vector constants.
2888 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
2889 return false;
2890
2891 // For vectors, verify that each element is not NaN.
2892 unsigned NumElts = V->getType()->getVectorNumElements();
2893 for (unsigned i = 0; i != NumElts; ++i) {
2894 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
2895 if (!Elt)
2896 return false;
2897 if (isa<UndefValue>(Elt))
2898 continue;
2899 auto *CElt = dyn_cast<ConstantFP>(Elt);
2900 if (!CElt || CElt->isNaN())
2901 return false;
2902 }
2903 // All elements were confirmed not-NaN or undefined.
2904 return true;
2905}
2906
Sanjay Patelaee84212014-11-04 16:27:42 +00002907/// If the specified value can be set by repeating the same byte in memory,
2908/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002909/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2910/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2911/// byte store (e.g. i16 0x1234), return null.
2912Value *llvm::isBytewiseValue(Value *V) {
2913 // All byte-wide stores are splatable, even of arbitrary variables.
2914 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002915
2916 // Handle 'null' ConstantArrayZero etc.
2917 if (Constant *C = dyn_cast<Constant>(V))
2918 if (C->isNullValue())
2919 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002920
Chris Lattner9cb10352010-12-26 20:15:01 +00002921 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002922 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002923 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2924 if (CFP->getType()->isFloatTy())
2925 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2926 if (CFP->getType()->isDoubleTy())
2927 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2928 // Don't handle long double formats, which have strange constraints.
2929 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002930
Benjamin Kramer17d90152015-02-07 19:29:02 +00002931 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002932 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002933 if (CI->getBitWidth() % 8 == 0) {
2934 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002935
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002936 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002937 return nullptr;
2938 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002939 }
2940 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002941
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002942 // A ConstantDataArray/Vector is splatable if all its members are equal and
2943 // also splatable.
2944 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2945 Value *Elt = CA->getElementAsConstant(0);
2946 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002947 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002948 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002949
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002950 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2951 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002952 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002953
Chris Lattner9cb10352010-12-26 20:15:01 +00002954 return Val;
2955 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002956
Chris Lattner9cb10352010-12-26 20:15:01 +00002957 // Conceptually, we could handle things like:
2958 // %a = zext i8 %X to i16
2959 // %b = shl i16 %a, 8
2960 // %c = or i16 %a, %b
2961 // but until there is an example that actually needs this, it doesn't seem
2962 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002963 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002964}
2965
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002966// This is the recursive version of BuildSubAggregate. It takes a few different
2967// arguments. Idxs is the index within the nested struct From that we are
2968// looking at now (which is of type IndexedType). IdxSkip is the number of
2969// indices from Idxs that should be left out when inserting into the resulting
2970// struct. To is the result struct built so far, new insertvalue instructions
2971// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002972static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002973 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002974 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002975 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002976 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002977 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002978 // Save the original To argument so we can modify it
2979 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002980 // General case, the type indexed by Idxs is a struct
2981 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2982 // Process each struct element recursively
2983 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002984 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002985 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002986 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002987 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002988 if (!To) {
2989 // Couldn't find any inserted value for this index? Cleanup
2990 while (PrevTo != OrigTo) {
2991 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2992 PrevTo = Del->getAggregateOperand();
2993 Del->eraseFromParent();
2994 }
2995 // Stop processing elements
2996 break;
2997 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002998 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002999 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003000 if (To)
3001 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003002 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003003 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3004 // the struct's elements had a value that was inserted directly. In the latter
3005 // case, perhaps we can't determine each of the subelements individually, but
3006 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003007
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003008 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003009 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003010
3011 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003012 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003013
Vedant Kumard3196742018-02-28 19:08:52 +00003014 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003015 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3016 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003017}
3018
3019// This helper takes a nested struct and extracts a part of it (which is again a
3020// struct) into a new value. For example, given the struct:
3021// { a, { b, { c, d }, e } }
3022// and the indices "1, 1" this returns
3023// { c, d }.
3024//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003025// It does this by inserting an insertvalue for each element in the resulting
3026// struct, as opposed to just inserting a single struct. This will only work if
3027// each of the elements of the substruct are known (ie, inserted into From by an
3028// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003029//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003030// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003031static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003032 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003033 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003034 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003035 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003036 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003037 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003038 unsigned IdxSkip = Idxs.size();
3039
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003040 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003041}
3042
Vedant Kumard3196742018-02-28 19:08:52 +00003043/// Given an aggregate and a sequence of indices, see if the scalar value
3044/// indexed is already around as a register, for example if it was inserted
3045/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003046///
3047/// If InsertBefore is not null, this function will duplicate (modified)
3048/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003049Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3050 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003051 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003052 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003053 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003054 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003055 // We have indices, so V should have an indexable type.
3056 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3057 "Not looking at a struct or array?");
3058 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3059 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003060
Chris Lattner67058832012-01-25 06:48:06 +00003061 if (Constant *C = dyn_cast<Constant>(V)) {
3062 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003063 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003064 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3065 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003066
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003067 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003068 // Loop the indices for the insertvalue instruction in parallel with the
3069 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003070 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003071 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3072 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003073 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003074 // We can't handle this without inserting insertvalues
3075 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003076 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003077
3078 // The requested index identifies a part of a nested aggregate. Handle
3079 // this specially. For example,
3080 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3081 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3082 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3083 // This can be changed into
3084 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3085 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3086 // which allows the unused 0,0 element from the nested struct to be
3087 // removed.
3088 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3089 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003090 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003091
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003092 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003093 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003094 // looking for, then.
3095 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003096 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003097 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003098 }
3099 // If we end up here, the indices of the insertvalue match with those
3100 // requested (though possibly only partially). Now we recursively look at
3101 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003102 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003103 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003104 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003105 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003106
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003107 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003108 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003109 // something else, we can extract from that something else directly instead.
3110 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003111
3112 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003113 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003114 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003115 SmallVector<unsigned, 5> Idxs;
3116 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003117 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003118 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003119
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003120 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003121 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003122
Craig Topper1bef2c82012-12-22 19:15:35 +00003123 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003124 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003125
Jay Foad57aa6362011-07-13 10:26:04 +00003126 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003127 }
3128 // Otherwise, we don't know (such as, extracting from a function return value
3129 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003130 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003131}
Evan Chengda3db112008-06-30 07:31:25 +00003132
Sanjay Patelaee84212014-11-04 16:27:42 +00003133/// Analyze the specified pointer to see if it can be expressed as a base
3134/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003135Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003136 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003137 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003138 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003139
3140 // We walk up the defs but use a visited set to handle unreachable code. In
3141 // that case, we stop after accumulating the cycle once (not that it
3142 // matters).
3143 SmallPtrSet<Value *, 16> Visited;
3144 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003145 if (Ptr->getType()->isVectorTy())
3146 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003147
Nuno Lopes368c4d02012-12-31 20:48:35 +00003148 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003149 // If one of the values we have visited is an addrspacecast, then
3150 // the pointer type of this GEP may be different from the type
3151 // of the Ptr parameter which was passed to this function. This
3152 // means when we construct GEPOffset, we need to use the size
3153 // of GEP's pointer type rather than the size of the original
3154 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003155 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003156 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3157 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003158
Tom Stellard17eb3412016-10-07 14:23:29 +00003159 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003160
Nuno Lopes368c4d02012-12-31 20:48:35 +00003161 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003162 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3163 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003164 Ptr = cast<Operator>(Ptr)->getOperand(0);
3165 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003166 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003167 break;
3168 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003169 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003170 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003171 }
3172 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003173 Offset = ByteOffset.getSExtValue();
3174 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003175}
3176
Matthias Braun50ec0b52017-05-19 22:37:09 +00003177bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3178 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003179 // Make sure the GEP has exactly three arguments.
3180 if (GEP->getNumOperands() != 3)
3181 return false;
3182
Matthias Braun50ec0b52017-05-19 22:37:09 +00003183 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3184 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003185 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003186 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003187 return false;
3188
3189 // Check to make sure that the first operand of the GEP is an integer and
3190 // has value 0 so that we are sure we're indexing into the initializer.
3191 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3192 if (!FirstIdx || !FirstIdx->isZero())
3193 return false;
3194
3195 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003196}
Chris Lattnere28618d2010-11-30 22:25:26 +00003197
Matthias Braun50ec0b52017-05-19 22:37:09 +00003198bool llvm::getConstantDataArrayInfo(const Value *V,
3199 ConstantDataArraySlice &Slice,
3200 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003201 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003202
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003203 // Look through bitcast instructions and geps.
3204 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003205
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003206 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003207 // offset.
3208 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003209 // The GEP operator should be based on a pointer to string constant, and is
3210 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003211 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003212 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003213
Evan Chengda3db112008-06-30 07:31:25 +00003214 // If the second index isn't a ConstantInt, then this is a variable index
3215 // into the array. If this occurs, we can't say anything meaningful about
3216 // the string.
3217 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003218 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003219 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003220 else
3221 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003222 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3223 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003224 }
Nick Lewycky46209882011-10-20 00:34:35 +00003225
Evan Chengda3db112008-06-30 07:31:25 +00003226 // The GEP instruction, constant or instruction, must reference a global
3227 // variable that is a constant and is initialized. The referenced constant
3228 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003229 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003230 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003231 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003232
Matthias Braun50ec0b52017-05-19 22:37:09 +00003233 const ConstantDataArray *Array;
3234 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003235 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003236 Type *GVTy = GV->getValueType();
3237 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003238 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003239 Array = nullptr;
3240 } else {
3241 const DataLayout &DL = GV->getParent()->getDataLayout();
3242 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3243 uint64_t Length = SizeInBytes / (ElementSize / 8);
3244 if (Length <= Offset)
3245 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003246
Matthias Braun50ec0b52017-05-19 22:37:09 +00003247 Slice.Array = nullptr;
3248 Slice.Offset = 0;
3249 Slice.Length = Length - Offset;
3250 return true;
3251 }
3252 } else {
3253 // This must be a ConstantDataArray.
3254 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3255 if (!Array)
3256 return false;
3257 ArrayTy = Array->getType();
3258 }
3259 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003260 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003261
Matthias Braun50ec0b52017-05-19 22:37:09 +00003262 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003263 if (Offset > NumElts)
3264 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003265
Matthias Braun50ec0b52017-05-19 22:37:09 +00003266 Slice.Array = Array;
3267 Slice.Offset = Offset;
3268 Slice.Length = NumElts - Offset;
3269 return true;
3270}
3271
3272/// This function computes the length of a null-terminated C string pointed to
3273/// by V. If successful, it returns true and returns the string in Str.
3274/// If unsuccessful, it returns false.
3275bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3276 uint64_t Offset, bool TrimAtNul) {
3277 ConstantDataArraySlice Slice;
3278 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3279 return false;
3280
3281 if (Slice.Array == nullptr) {
3282 if (TrimAtNul) {
3283 Str = StringRef();
3284 return true;
3285 }
3286 if (Slice.Length == 1) {
3287 Str = StringRef("", 1);
3288 return true;
3289 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003290 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003291 // of 0s at hand.
3292 return false;
3293 }
3294
3295 // Start out with the entire array in the StringRef.
3296 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003297 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003298 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003299
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003300 if (TrimAtNul) {
3301 // Trim off the \0 and anything after it. If the array is not nul
3302 // terminated, we just return the whole end of string. The client may know
3303 // some other way that the string is length-bound.
3304 Str = Str.substr(0, Str.find('\0'));
3305 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003306 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003307}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003308
3309// These next two are very similar to the above, but also look through PHI
3310// nodes.
3311// TODO: See if we can integrate these two together.
3312
Sanjay Patelaee84212014-11-04 16:27:42 +00003313/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003314/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003315static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003316 SmallPtrSetImpl<const PHINode*> &PHIs,
3317 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003318 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003319 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003320
3321 // If this is a PHI node, there are two cases: either we have already seen it
3322 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003323 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003324 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003325 return ~0ULL; // already in the set.
3326
3327 // If it was new, see if all the input strings are the same length.
3328 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003329 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003330 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003331 if (Len == 0) return 0; // Unknown length -> unknown.
3332
3333 if (Len == ~0ULL) continue;
3334
3335 if (Len != LenSoFar && LenSoFar != ~0ULL)
3336 return 0; // Disagree -> unknown.
3337 LenSoFar = Len;
3338 }
3339
3340 // Success, all agree.
3341 return LenSoFar;
3342 }
3343
3344 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003345 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003346 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003347 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003348 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003349 if (Len2 == 0) return 0;
3350 if (Len1 == ~0ULL) return Len2;
3351 if (Len2 == ~0ULL) return Len1;
3352 if (Len1 != Len2) return 0;
3353 return Len1;
3354 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003355
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003356 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003357 ConstantDataArraySlice Slice;
3358 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003359 return 0;
3360
Matthias Braun50ec0b52017-05-19 22:37:09 +00003361 if (Slice.Array == nullptr)
3362 return 1;
3363
3364 // Search for nul characters
3365 unsigned NullIndex = 0;
3366 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3367 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3368 break;
3369 }
3370
3371 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003372}
3373
Sanjay Patelaee84212014-11-04 16:27:42 +00003374/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003375/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003376uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003377 if (!V->getType()->isPointerTy()) return 0;
3378
Pete Cooper35b00d52016-08-13 01:05:32 +00003379 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003380 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003381 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3382 // an empty string as a length.
3383 return Len == ~0ULL ? 1 : Len;
3384}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003385
Adam Nemete2b885c2015-04-23 20:09:20 +00003386/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3387/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003388static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3389 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003390 // Find the loop-defined value.
3391 Loop *L = LI->getLoopFor(PN->getParent());
3392 if (PN->getNumIncomingValues() != 2)
3393 return true;
3394
3395 // Find the value from previous iteration.
3396 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3397 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3398 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3399 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3400 return true;
3401
3402 // If a new pointer is loaded in the loop, the pointer references a different
3403 // object in every iteration. E.g.:
3404 // for (i)
3405 // int *p = a[i];
3406 // ...
3407 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3408 if (!L->isLoopInvariant(Load->getPointerOperand()))
3409 return false;
3410 return true;
3411}
3412
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003413Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3414 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003415 if (!V->getType()->isPointerTy())
3416 return V;
3417 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3418 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3419 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003420 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3421 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003422 V = cast<Operator>(V)->getOperand(0);
3423 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003424 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003425 return V;
3426 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003427 } else if (isa<AllocaInst>(V)) {
3428 // An alloca can't be further simplified.
3429 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003430 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003431 if (auto CS = CallSite(V))
3432 if (Value *RV = CS.getReturnedArgOperand()) {
3433 V = RV;
3434 continue;
3435 }
3436
Dan Gohman05b18f12010-12-15 20:49:55 +00003437 // See if InstructionSimplify knows any relevant tricks.
3438 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003439 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003440 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003441 V = Simplified;
3442 continue;
3443 }
3444
Dan Gohmana4fcd242010-12-15 20:02:24 +00003445 return V;
3446 }
3447 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3448 }
3449 return V;
3450}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003451
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003452void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003453 const DataLayout &DL, LoopInfo *LI,
3454 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003455 SmallPtrSet<Value *, 4> Visited;
3456 SmallVector<Value *, 4> Worklist;
3457 Worklist.push_back(V);
3458 do {
3459 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003460 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003461
David Blaikie70573dc2014-11-19 07:49:26 +00003462 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003463 continue;
3464
3465 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3466 Worklist.push_back(SI->getTrueValue());
3467 Worklist.push_back(SI->getFalseValue());
3468 continue;
3469 }
3470
3471 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003472 // If this PHI changes the underlying object in every iteration of the
3473 // loop, don't look through it. Consider:
3474 // int **A;
3475 // for (i) {
3476 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3477 // Curr = A[i];
3478 // *Prev, *Curr;
3479 //
3480 // Prev is tracking Curr one iteration behind so they refer to different
3481 // underlying objects.
3482 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3483 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003484 for (Value *IncValue : PN->incoming_values())
3485 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003486 continue;
3487 }
3488
3489 Objects.push_back(P);
3490 } while (!Worklist.empty());
3491}
3492
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003493/// This is the function that does the work of looking through basic
3494/// ptrtoint+arithmetic+inttoptr sequences.
3495static const Value *getUnderlyingObjectFromInt(const Value *V) {
3496 do {
3497 if (const Operator *U = dyn_cast<Operator>(V)) {
3498 // If we find a ptrtoint, we can transfer control back to the
3499 // regular getUnderlyingObjectFromInt.
3500 if (U->getOpcode() == Instruction::PtrToInt)
3501 return U->getOperand(0);
3502 // If we find an add of a constant, a multiplied value, or a phi, it's
3503 // likely that the other operand will lead us to the base
3504 // object. We don't have to worry about the case where the
3505 // object address is somehow being computed by the multiply,
3506 // because our callers only care when the result is an
3507 // identifiable object.
3508 if (U->getOpcode() != Instruction::Add ||
3509 (!isa<ConstantInt>(U->getOperand(1)) &&
3510 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3511 !isa<PHINode>(U->getOperand(1))))
3512 return V;
3513 V = U->getOperand(0);
3514 } else {
3515 return V;
3516 }
3517 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3518 } while (true);
3519}
3520
3521/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3522/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003523/// It returns false if unidentified object is found in GetUnderlyingObjects.
3524bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003525 SmallVectorImpl<Value *> &Objects,
3526 const DataLayout &DL) {
3527 SmallPtrSet<const Value *, 16> Visited;
3528 SmallVector<const Value *, 4> Working(1, V);
3529 do {
3530 V = Working.pop_back_val();
3531
3532 SmallVector<Value *, 4> Objs;
3533 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3534
3535 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003536 if (!Visited.insert(V).second)
3537 continue;
3538 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3539 const Value *O =
3540 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3541 if (O->getType()->isPointerTy()) {
3542 Working.push_back(O);
3543 continue;
3544 }
3545 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003546 // If GetUnderlyingObjects fails to find an identifiable object,
3547 // getUnderlyingObjectsForCodeGen also fails for safety.
3548 if (!isIdentifiedObject(V)) {
3549 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003550 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003551 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003552 Objects.push_back(const_cast<Value *>(V));
3553 }
3554 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003555 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003556}
3557
Sanjay Patelaee84212014-11-04 16:27:42 +00003558/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003559bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003560 for (const User *U : V->users()) {
3561 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003562 if (!II) return false;
3563
3564 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3565 II->getIntrinsicID() != Intrinsic::lifetime_end)
3566 return false;
3567 }
3568 return true;
3569}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003570
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003571bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3572 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003573 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003574 const Operator *Inst = dyn_cast<Operator>(V);
3575 if (!Inst)
3576 return false;
3577
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003578 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3579 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3580 if (C->canTrap())
3581 return false;
3582
3583 switch (Inst->getOpcode()) {
3584 default:
3585 return true;
3586 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003587 case Instruction::URem: {
3588 // x / y is undefined if y == 0.
3589 const APInt *V;
3590 if (match(Inst->getOperand(1), m_APInt(V)))
3591 return *V != 0;
3592 return false;
3593 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003594 case Instruction::SDiv:
3595 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003596 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003597 const APInt *Numerator, *Denominator;
3598 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3599 return false;
3600 // We cannot hoist this division if the denominator is 0.
3601 if (*Denominator == 0)
3602 return false;
3603 // It's safe to hoist if the denominator is not 0 or -1.
3604 if (*Denominator != -1)
3605 return true;
3606 // At this point we know that the denominator is -1. It is safe to hoist as
3607 // long we know that the numerator is not INT_MIN.
3608 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3609 return !Numerator->isMinSignedValue();
3610 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003611 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003612 }
3613 case Instruction::Load: {
3614 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003615 if (!LI->isUnordered() ||
3616 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003617 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003618 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003619 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3620 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003621 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003622 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003623 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3624 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003625 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003626 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003627 auto *CI = cast<const CallInst>(Inst);
3628 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003629
Matt Arsenault6a288c12017-05-03 02:26:10 +00003630 // The called function could have undefined behavior or side-effects, even
3631 // if marked readnone nounwind.
3632 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003633 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003634 case Instruction::VAArg:
3635 case Instruction::Alloca:
3636 case Instruction::Invoke:
3637 case Instruction::PHI:
3638 case Instruction::Store:
3639 case Instruction::Ret:
3640 case Instruction::Br:
3641 case Instruction::IndirectBr:
3642 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003643 case Instruction::Unreachable:
3644 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003645 case Instruction::AtomicRMW:
3646 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003647 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003648 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003649 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003650 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003651 case Instruction::CatchRet:
3652 case Instruction::CleanupPad:
3653 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003654 return false; // Misc instructions which have effects
3655 }
3656}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003657
Quentin Colombet6443cce2015-08-06 18:44:34 +00003658bool llvm::mayBeMemoryDependent(const Instruction &I) {
3659 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3660}
3661
Pete Cooper35b00d52016-08-13 01:05:32 +00003662OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3663 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003664 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003665 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003666 const Instruction *CxtI,
3667 const DominatorTree *DT) {
3668 // Multiplying n * m significant bits yields a result of n + m significant
3669 // bits. If the total number of significant bits does not exceed the
3670 // result bit width (minus 1), there is no overflow.
3671 // This means if we have enough leading zero bits in the operands
3672 // we can guarantee that the result does not overflow.
3673 // Ref: "Hacker's Delight" by Henry Warren
3674 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003675 KnownBits LHSKnown(BitWidth);
3676 KnownBits RHSKnown(BitWidth);
3677 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3678 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003679 // Note that underestimating the number of zero bits gives a more
3680 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003681 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3682 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003683 // First handle the easy case: if we have enough zero bits there's
3684 // definitely no overflow.
3685 if (ZeroBits >= BitWidth)
3686 return OverflowResult::NeverOverflows;
3687
3688 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003689 APInt LHSMax = ~LHSKnown.Zero;
3690 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003691
3692 // We know the multiply operation doesn't overflow if the maximum values for
3693 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003694 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003695 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003696 if (!MaxOverflow)
3697 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003698
David Majnemerc8a576b2015-01-02 07:29:47 +00003699 // We know it always overflows if multiplying the smallest possible values for
3700 // the operands also results in overflow.
3701 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003702 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003703 if (MinOverflow)
3704 return OverflowResult::AlwaysOverflows;
3705
3706 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003707}
David Majnemer5310c1e2015-01-07 00:39:50 +00003708
Pete Cooper35b00d52016-08-13 01:05:32 +00003709OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3710 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003711 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003712 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003713 const Instruction *CxtI,
3714 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003715 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3716 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3717 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003718
Craig Topper6e11a052017-05-08 16:22:48 +00003719 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003720 // The sign bit is set in both cases: this MUST overflow.
3721 // Create a simple add instruction, and insert it into the struct.
3722 return OverflowResult::AlwaysOverflows;
3723 }
3724
Craig Topper6e11a052017-05-08 16:22:48 +00003725 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003726 // The sign bit is clear in both cases: this CANNOT overflow.
3727 // Create a simple add instruction, and insert it into the struct.
3728 return OverflowResult::NeverOverflows;
3729 }
3730 }
3731
3732 return OverflowResult::MayOverflow;
3733}
James Molloy71b91c22015-05-11 14:42:20 +00003734
Craig Topperbb973722017-05-15 02:44:08 +00003735/// \brief Return true if we can prove that adding the two values of the
3736/// knownbits will not overflow.
3737/// Otherwise return false.
3738static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3739 const KnownBits &RHSKnown) {
3740 // Addition of two 2's complement numbers having opposite signs will never
3741 // overflow.
3742 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3743 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3744 return true;
3745
3746 // If either of the values is known to be non-negative, adding them can only
3747 // overflow if the second is also non-negative, so we can assume that.
3748 // Two non-negative numbers will only overflow if there is a carry to the
3749 // sign bit, so we can check if even when the values are as big as possible
3750 // there is no overflow to the sign bit.
3751 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3752 APInt MaxLHS = ~LHSKnown.Zero;
3753 MaxLHS.clearSignBit();
3754 APInt MaxRHS = ~RHSKnown.Zero;
3755 MaxRHS.clearSignBit();
3756 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3757 return Result.isSignBitClear();
3758 }
3759
3760 // If either of the values is known to be negative, adding them can only
3761 // overflow if the second is also negative, so we can assume that.
3762 // Two negative number will only overflow if there is no carry to the sign
3763 // bit, so we can check if even when the values are as small as possible
3764 // there is overflow to the sign bit.
3765 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3766 APInt MinLHS = LHSKnown.One;
3767 MinLHS.clearSignBit();
3768 APInt MinRHS = RHSKnown.One;
3769 MinRHS.clearSignBit();
3770 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3771 return Result.isSignBitSet();
3772 }
3773
3774 // If we reached here it means that we know nothing about the sign bits.
3775 // In this case we can't know if there will be an overflow, since by
3776 // changing the sign bits any two values can be made to overflow.
3777 return false;
3778}
3779
Pete Cooper35b00d52016-08-13 01:05:32 +00003780static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3781 const Value *RHS,
3782 const AddOperator *Add,
3783 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003784 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003785 const Instruction *CxtI,
3786 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003787 if (Add && Add->hasNoSignedWrap()) {
3788 return OverflowResult::NeverOverflows;
3789 }
3790
Craig Topperbb973722017-05-15 02:44:08 +00003791 // If LHS and RHS each have at least two sign bits, the addition will look
3792 // like
3793 //
3794 // XX..... +
3795 // YY.....
3796 //
3797 // If the carry into the most significant position is 0, X and Y can't both
3798 // be 1 and therefore the carry out of the addition is also 0.
3799 //
3800 // If the carry into the most significant position is 1, X and Y can't both
3801 // be 0 and therefore the carry out of the addition is also 1.
3802 //
3803 // Since the carry into the most significant position is always equal to
3804 // the carry out of the addition, there is no signed overflow.
3805 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3806 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3807 return OverflowResult::NeverOverflows;
3808
Craig Topper6e11a052017-05-08 16:22:48 +00003809 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3810 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003811
Craig Topperbb973722017-05-15 02:44:08 +00003812 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003813 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003814
3815 // The remaining code needs Add to be available. Early returns if not so.
3816 if (!Add)
3817 return OverflowResult::MayOverflow;
3818
3819 // If the sign of Add is the same as at least one of the operands, this add
3820 // CANNOT overflow. This is particularly useful when the sum is
3821 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3822 // operands.
3823 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003824 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003825 bool LHSOrRHSKnownNegative =
3826 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003827 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003828 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3829 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3830 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003831 return OverflowResult::NeverOverflows;
3832 }
3833 }
3834
3835 return OverflowResult::MayOverflow;
3836}
3837
Pete Cooper35b00d52016-08-13 01:05:32 +00003838bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3839 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003840#ifndef NDEBUG
3841 auto IID = II->getIntrinsicID();
3842 assert((IID == Intrinsic::sadd_with_overflow ||
3843 IID == Intrinsic::uadd_with_overflow ||
3844 IID == Intrinsic::ssub_with_overflow ||
3845 IID == Intrinsic::usub_with_overflow ||
3846 IID == Intrinsic::smul_with_overflow ||
3847 IID == Intrinsic::umul_with_overflow) &&
3848 "Not an overflow intrinsic!");
3849#endif
3850
Pete Cooper35b00d52016-08-13 01:05:32 +00003851 SmallVector<const BranchInst *, 2> GuardingBranches;
3852 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003853
Pete Cooper35b00d52016-08-13 01:05:32 +00003854 for (const User *U : II->users()) {
3855 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003856 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3857
3858 if (EVI->getIndices()[0] == 0)
3859 Results.push_back(EVI);
3860 else {
3861 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3862
Pete Cooper35b00d52016-08-13 01:05:32 +00003863 for (const auto *U : EVI->users())
3864 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003865 assert(B->isConditional() && "How else is it using an i1?");
3866 GuardingBranches.push_back(B);
3867 }
3868 }
3869 } else {
3870 // We are using the aggregate directly in a way we don't want to analyze
3871 // here (storing it to a global, say).
3872 return false;
3873 }
3874 }
3875
Pete Cooper35b00d52016-08-13 01:05:32 +00003876 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003877 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3878 if (!NoWrapEdge.isSingleEdge())
3879 return false;
3880
3881 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003882 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003883 // If the extractvalue itself is not executed on overflow, the we don't
3884 // need to check each use separately, since domination is transitive.
3885 if (DT.dominates(NoWrapEdge, Result->getParent()))
3886 continue;
3887
3888 for (auto &RU : Result->uses())
3889 if (!DT.dominates(NoWrapEdge, RU))
3890 return false;
3891 }
3892
3893 return true;
3894 };
3895
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003896 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003897}
3898
3899
Pete Cooper35b00d52016-08-13 01:05:32 +00003900OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003901 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003902 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003903 const Instruction *CxtI,
3904 const DominatorTree *DT) {
3905 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003906 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003907}
3908
Pete Cooper35b00d52016-08-13 01:05:32 +00003909OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3910 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003911 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003912 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003913 const Instruction *CxtI,
3914 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003915 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003916}
3917
Jingyue Wu42f1d672015-07-28 18:22:40 +00003918bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003919 // A memory operation returns normally if it isn't volatile. A volatile
3920 // operation is allowed to trap.
3921 //
3922 // An atomic operation isn't guaranteed to return in a reasonable amount of
3923 // time because it's possible for another thread to interfere with it for an
3924 // arbitrary length of time, but programs aren't allowed to rely on that.
3925 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3926 return !LI->isVolatile();
3927 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3928 return !SI->isVolatile();
3929 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3930 return !CXI->isVolatile();
3931 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3932 return !RMWI->isVolatile();
3933 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3934 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003935
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003936 // If there is no successor, then execution can't transfer to it.
3937 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3938 return !CRI->unwindsToCaller();
3939 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3940 return !CatchSwitch->unwindsToCaller();
3941 if (isa<ResumeInst>(I))
3942 return false;
3943 if (isa<ReturnInst>(I))
3944 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003945 if (isa<UnreachableInst>(I))
3946 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003947
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003948 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003949 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003950 // Call sites that throw have implicit non-local control flow.
3951 if (!CS.doesNotThrow())
3952 return false;
3953
3954 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3955 // etc. and thus not return. However, LLVM already assumes that
3956 //
3957 // - Thread exiting actions are modeled as writes to memory invisible to
3958 // the program.
3959 //
3960 // - Loops that don't have side effects (side effects are volatile/atomic
3961 // stores and IO) always terminate (see http://llvm.org/PR965).
3962 // Furthermore IO itself is also modeled as writes to memory invisible to
3963 // the program.
3964 //
3965 // We rely on those assumptions here, and use the memory effects of the call
3966 // target as a proxy for checking that it always returns.
3967
3968 // FIXME: This isn't aggressive enough; a call which only writes to a global
3969 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003970 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00003971 match(I, m_Intrinsic<Intrinsic::assume>()) ||
3972 match(I, m_Intrinsic<Intrinsic::sideeffect>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003973 }
3974
3975 // Other instructions return normally.
3976 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003977}
3978
Philip Reamesfbffd122018-03-08 21:25:30 +00003979bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
3980 // TODO: This is slightly consdervative for invoke instruction since exiting
3981 // via an exception *is* normal control for them.
3982 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
3983 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
3984 return false;
3985 return true;
3986}
3987
Jingyue Wu42f1d672015-07-28 18:22:40 +00003988bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3989 const Loop *L) {
3990 // The loop header is guaranteed to be executed for every iteration.
3991 //
3992 // FIXME: Relax this constraint to cover all basic blocks that are
3993 // guaranteed to be executed at every iteration.
3994 if (I->getParent() != L->getHeader()) return false;
3995
3996 for (const Instruction &LI : *L->getHeader()) {
3997 if (&LI == I) return true;
3998 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3999 }
4000 llvm_unreachable("Instruction not contained in its own parent basic block.");
4001}
4002
4003bool llvm::propagatesFullPoison(const Instruction *I) {
4004 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004005 case Instruction::Add:
4006 case Instruction::Sub:
4007 case Instruction::Xor:
4008 case Instruction::Trunc:
4009 case Instruction::BitCast:
4010 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004011 case Instruction::Mul:
4012 case Instruction::Shl:
4013 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004014 // These operations all propagate poison unconditionally. Note that poison
4015 // is not any particular value, so xor or subtraction of poison with
4016 // itself still yields poison, not zero.
4017 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004018
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004019 case Instruction::AShr:
4020 case Instruction::SExt:
4021 // For these operations, one bit of the input is replicated across
4022 // multiple output bits. A replicated poison bit is still poison.
4023 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004024
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004025 case Instruction::ICmp:
4026 // Comparing poison with any value yields poison. This is why, for
4027 // instance, x s< (x +nsw 1) can be folded to true.
4028 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004029
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004030 default:
4031 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004032 }
4033}
4034
4035const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4036 switch (I->getOpcode()) {
4037 case Instruction::Store:
4038 return cast<StoreInst>(I)->getPointerOperand();
4039
4040 case Instruction::Load:
4041 return cast<LoadInst>(I)->getPointerOperand();
4042
4043 case Instruction::AtomicCmpXchg:
4044 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4045
4046 case Instruction::AtomicRMW:
4047 return cast<AtomicRMWInst>(I)->getPointerOperand();
4048
4049 case Instruction::UDiv:
4050 case Instruction::SDiv:
4051 case Instruction::URem:
4052 case Instruction::SRem:
4053 return I->getOperand(1);
4054
4055 default:
4056 return nullptr;
4057 }
4058}
4059
Sanjoy Das08989c72017-04-30 19:41:19 +00004060bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004061 // We currently only look for uses of poison values within the same basic
4062 // block, as that makes it easier to guarantee that the uses will be
4063 // executed given that PoisonI is executed.
4064 //
4065 // FIXME: Expand this to consider uses beyond the same basic block. To do
4066 // this, look out for the distinction between post-dominance and strong
4067 // post-dominance.
4068 const BasicBlock *BB = PoisonI->getParent();
4069
4070 // Set of instructions that we have proved will yield poison if PoisonI
4071 // does.
4072 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004073 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004074 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004075 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004076
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004077 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004078
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004079 unsigned Iter = 0;
4080 while (Iter++ < MaxDepth) {
4081 for (auto &I : make_range(Begin, End)) {
4082 if (&I != PoisonI) {
4083 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4084 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4085 return true;
4086 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4087 return false;
4088 }
4089
4090 // Mark poison that propagates from I through uses of I.
4091 if (YieldsPoison.count(&I)) {
4092 for (const User *User : I.users()) {
4093 const Instruction *UserI = cast<Instruction>(User);
4094 if (propagatesFullPoison(UserI))
4095 YieldsPoison.insert(User);
4096 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004097 }
4098 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004099
4100 if (auto *NextBB = BB->getSingleSuccessor()) {
4101 if (Visited.insert(NextBB).second) {
4102 BB = NextBB;
4103 Begin = BB->getFirstNonPHI()->getIterator();
4104 End = BB->end();
4105 continue;
4106 }
4107 }
4108
4109 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004110 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004111 return false;
4112}
4113
Pete Cooper35b00d52016-08-13 01:05:32 +00004114static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004115 if (FMF.noNaNs())
4116 return true;
4117
4118 if (auto *C = dyn_cast<ConstantFP>(V))
4119 return !C->isNaN();
4120 return false;
4121}
4122
Pete Cooper35b00d52016-08-13 01:05:32 +00004123static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004124 if (auto *C = dyn_cast<ConstantFP>(V))
4125 return !C->isZero();
4126 return false;
4127}
4128
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004129/// Match clamp pattern for float types without care about NaNs or signed zeros.
4130/// Given non-min/max outer cmp/select from the clamp pattern this
4131/// function recognizes if it can be substitued by a "canonical" min/max
4132/// pattern.
4133static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4134 Value *CmpLHS, Value *CmpRHS,
4135 Value *TrueVal, Value *FalseVal,
4136 Value *&LHS, Value *&RHS) {
4137 // Try to match
4138 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4139 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4140 // and return description of the outer Max/Min.
4141
4142 // First, check if select has inverse order:
4143 if (CmpRHS == FalseVal) {
4144 std::swap(TrueVal, FalseVal);
4145 Pred = CmpInst::getInversePredicate(Pred);
4146 }
4147
4148 // Assume success now. If there's no match, callers should not use these anyway.
4149 LHS = TrueVal;
4150 RHS = FalseVal;
4151
4152 const APFloat *FC1;
4153 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4154 return {SPF_UNKNOWN, SPNB_NA, false};
4155
4156 const APFloat *FC2;
4157 switch (Pred) {
4158 case CmpInst::FCMP_OLT:
4159 case CmpInst::FCMP_OLE:
4160 case CmpInst::FCMP_ULT:
4161 case CmpInst::FCMP_ULE:
4162 if (match(FalseVal,
4163 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4164 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4165 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4166 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4167 break;
4168 case CmpInst::FCMP_OGT:
4169 case CmpInst::FCMP_OGE:
4170 case CmpInst::FCMP_UGT:
4171 case CmpInst::FCMP_UGE:
4172 if (match(FalseVal,
4173 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4174 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4175 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4176 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4177 break;
4178 default:
4179 break;
4180 }
4181
4182 return {SPF_UNKNOWN, SPNB_NA, false};
4183}
4184
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004185/// Recognize variations of:
4186/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4187static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4188 Value *CmpLHS, Value *CmpRHS,
4189 Value *TrueVal, Value *FalseVal) {
4190 // Swap the select operands and predicate to match the patterns below.
4191 if (CmpRHS != TrueVal) {
4192 Pred = ICmpInst::getSwappedPredicate(Pred);
4193 std::swap(TrueVal, FalseVal);
4194 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004195 const APInt *C1;
4196 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4197 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004198 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4199 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004200 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004201 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004202
4203 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4204 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004205 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004206 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004207
4208 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4209 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004210 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004211 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004212
4213 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4214 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004215 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004216 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004217 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004218 return {SPF_UNKNOWN, SPNB_NA, false};
4219}
4220
Sanjay Patel78114302018-01-02 20:56:45 +00004221/// Recognize variations of:
4222/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4223static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4224 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004225 Value *TVal, Value *FVal,
4226 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004227 // TODO: Allow FP min/max with nnan/nsz.
4228 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4229
4230 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004231 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004232 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4233 return {SPF_UNKNOWN, SPNB_NA, false};
4234
4235 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004236 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004237 if (L.Flavor != R.Flavor)
4238 return {SPF_UNKNOWN, SPNB_NA, false};
4239
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004240 // We have something like: x Pred y ? min(a, b) : min(c, d).
4241 // Try to match the compare to the min/max operations of the select operands.
4242 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004243 switch (L.Flavor) {
4244 case SPF_SMIN:
4245 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4246 Pred = ICmpInst::getSwappedPredicate(Pred);
4247 std::swap(CmpLHS, CmpRHS);
4248 }
4249 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4250 break;
4251 return {SPF_UNKNOWN, SPNB_NA, false};
4252 case SPF_SMAX:
4253 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4254 Pred = ICmpInst::getSwappedPredicate(Pred);
4255 std::swap(CmpLHS, CmpRHS);
4256 }
4257 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4258 break;
4259 return {SPF_UNKNOWN, SPNB_NA, false};
4260 case SPF_UMIN:
4261 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4262 Pred = ICmpInst::getSwappedPredicate(Pred);
4263 std::swap(CmpLHS, CmpRHS);
4264 }
4265 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4266 break;
4267 return {SPF_UNKNOWN, SPNB_NA, false};
4268 case SPF_UMAX:
4269 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4270 Pred = ICmpInst::getSwappedPredicate(Pred);
4271 std::swap(CmpLHS, CmpRHS);
4272 }
4273 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4274 break;
4275 return {SPF_UNKNOWN, SPNB_NA, false};
4276 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004277 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004278 }
4279
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004280 // If there is a common operand in the already matched min/max and the other
4281 // min/max operands match the compare operands (either directly or inverted),
4282 // then this is min/max of the same flavor.
4283
Sanjay Patel78114302018-01-02 20:56:45 +00004284 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004285 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4286 if (D == B) {
4287 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4288 match(A, m_Not(m_Specific(CmpRHS)))))
4289 return {L.Flavor, SPNB_NA, false};
4290 }
Sanjay Patel78114302018-01-02 20:56:45 +00004291 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004292 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4293 if (C == B) {
4294 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4295 match(A, m_Not(m_Specific(CmpRHS)))))
4296 return {L.Flavor, SPNB_NA, false};
4297 }
Sanjay Patel78114302018-01-02 20:56:45 +00004298 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004299 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4300 if (D == A) {
4301 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4302 match(B, m_Not(m_Specific(CmpRHS)))))
4303 return {L.Flavor, SPNB_NA, false};
4304 }
Sanjay Patel78114302018-01-02 20:56:45 +00004305 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004306 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4307 if (C == A) {
4308 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4309 match(B, m_Not(m_Specific(CmpRHS)))))
4310 return {L.Flavor, SPNB_NA, false};
4311 }
Sanjay Patel78114302018-01-02 20:56:45 +00004312
4313 return {SPF_UNKNOWN, SPNB_NA, false};
4314}
4315
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004316/// Match non-obvious integer minimum and maximum sequences.
4317static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4318 Value *CmpLHS, Value *CmpRHS,
4319 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004320 Value *&LHS, Value *&RHS,
4321 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004322 // Assume success. If there's no match, callers should not use these anyway.
4323 LHS = TrueVal;
4324 RHS = FalseVal;
4325
4326 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4327 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4328 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004329
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004330 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004331 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4332 return SPR;
4333
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004334 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004335 return {SPF_UNKNOWN, SPNB_NA, false};
4336
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004337 // Z = X -nsw Y
4338 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4339 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4340 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004341 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004342 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004343
4344 // Z = X -nsw Y
4345 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4346 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4347 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004348 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004349 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004350
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004351 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004352 if (!match(CmpRHS, m_APInt(C1)))
4353 return {SPF_UNKNOWN, SPNB_NA, false};
4354
4355 // An unsigned min/max can be written with a signed compare.
4356 const APInt *C2;
4357 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4358 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4359 // Is the sign bit set?
4360 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4361 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004362 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4363 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004364 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004365
4366 // Is the sign bit clear?
4367 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4368 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004369 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4370 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004371 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004372 }
4373
4374 // Look through 'not' ops to find disguised signed min/max.
4375 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4376 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4377 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004378 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004379 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004380
4381 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4382 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4383 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004384 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004385 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004386
4387 return {SPF_UNKNOWN, SPNB_NA, false};
4388}
4389
James Molloy134bec22015-08-11 09:12:57 +00004390static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4391 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004392 Value *CmpLHS, Value *CmpRHS,
4393 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004394 Value *&LHS, Value *&RHS,
4395 unsigned Depth) {
James Molloy71b91c22015-05-11 14:42:20 +00004396 LHS = CmpLHS;
4397 RHS = CmpRHS;
4398
Sanjay Patel9a399792017-12-26 15:09:19 +00004399 // Signed zero may return inconsistent results between implementations.
4400 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4401 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4402 // Therefore, we behave conservatively and only proceed if at least one of the
4403 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004404 switch (Pred) {
4405 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004406 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004407 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4408 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4409 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4410 !isKnownNonZero(CmpRHS))
4411 return {SPF_UNKNOWN, SPNB_NA, false};
4412 }
4413
4414 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4415 bool Ordered = false;
4416
4417 // When given one NaN and one non-NaN input:
4418 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4419 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4420 // ordered comparison fails), which could be NaN or non-NaN.
4421 // so here we discover exactly what NaN behavior is required/accepted.
4422 if (CmpInst::isFPPredicate(Pred)) {
4423 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4424 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4425
4426 if (LHSSafe && RHSSafe) {
4427 // Both operands are known non-NaN.
4428 NaNBehavior = SPNB_RETURNS_ANY;
4429 } else if (CmpInst::isOrdered(Pred)) {
4430 // An ordered comparison will return false when given a NaN, so it
4431 // returns the RHS.
4432 Ordered = true;
4433 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004434 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004435 NaNBehavior = SPNB_RETURNS_NAN;
4436 else if (RHSSafe)
4437 NaNBehavior = SPNB_RETURNS_OTHER;
4438 else
4439 // Completely unsafe.
4440 return {SPF_UNKNOWN, SPNB_NA, false};
4441 } else {
4442 Ordered = false;
4443 // An unordered comparison will return true when given a NaN, so it
4444 // returns the LHS.
4445 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004446 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004447 NaNBehavior = SPNB_RETURNS_OTHER;
4448 else if (RHSSafe)
4449 NaNBehavior = SPNB_RETURNS_NAN;
4450 else
4451 // Completely unsafe.
4452 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004453 }
4454 }
4455
James Molloy71b91c22015-05-11 14:42:20 +00004456 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004457 std::swap(CmpLHS, CmpRHS);
4458 Pred = CmpInst::getSwappedPredicate(Pred);
4459 if (NaNBehavior == SPNB_RETURNS_NAN)
4460 NaNBehavior = SPNB_RETURNS_OTHER;
4461 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4462 NaNBehavior = SPNB_RETURNS_NAN;
4463 Ordered = !Ordered;
4464 }
4465
4466 // ([if]cmp X, Y) ? X : Y
4467 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004468 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004469 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004470 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004471 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004472 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004473 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004474 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004475 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004476 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004477 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4478 case FCmpInst::FCMP_UGT:
4479 case FCmpInst::FCMP_UGE:
4480 case FCmpInst::FCMP_OGT:
4481 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4482 case FCmpInst::FCMP_ULT:
4483 case FCmpInst::FCMP_ULE:
4484 case FCmpInst::FCMP_OLT:
4485 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004486 }
4487 }
4488
Sanjay Patele372aec2016-10-27 15:26:10 +00004489 const APInt *C1;
4490 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004491 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4492 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4493
4494 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4495 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Craig Topper81d772c2017-11-08 19:38:45 +00004496 if (Pred == ICmpInst::ICMP_SGT &&
4497 (C1->isNullValue() || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004498 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004499 }
4500
4501 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4502 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Craig Topper81d772c2017-11-08 19:38:45 +00004503 if (Pred == ICmpInst::ICMP_SLT &&
4504 (C1->isNullValue() || C1->isOneValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004505 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004506 }
4507 }
James Molloy71b91c22015-05-11 14:42:20 +00004508 }
4509
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004510 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004511 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004512
4513 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4514 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4515 // semantics than minNum. Be conservative in such case.
4516 if (NaNBehavior != SPNB_RETURNS_ANY ||
4517 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4518 !isKnownNonZero(CmpRHS)))
4519 return {SPF_UNKNOWN, SPNB_NA, false};
4520
4521 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004522}
James Molloy270ef8c2015-05-15 16:04:50 +00004523
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004524/// Helps to match a select pattern in case of a type mismatch.
4525///
4526/// The function processes the case when type of true and false values of a
4527/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004528/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004529/// operation after "select". If yes, it returns the new second value of
4530/// "select" (with the assumption that cast is moved):
4531/// 1. As operand of cast instruction when both values of "select" are same cast
4532/// instructions.
4533/// 2. As restored constant (by applying reverse cast operation) when the first
4534/// value of the "select" is a cast operation and the second value is a
4535/// constant.
4536/// NOTE: We return only the new second value because the first value could be
4537/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004538static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4539 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004540 auto *Cast1 = dyn_cast<CastInst>(V1);
4541 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004542 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004543
Sanjay Patel14a4b812017-01-29 16:34:57 +00004544 *CastOp = Cast1->getOpcode();
4545 Type *SrcTy = Cast1->getSrcTy();
4546 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4547 // If V1 and V2 are both the same cast from the same type, look through V1.
4548 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4549 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004550 return nullptr;
4551 }
4552
Sanjay Patel14a4b812017-01-29 16:34:57 +00004553 auto *C = dyn_cast<Constant>(V2);
4554 if (!C)
4555 return nullptr;
4556
David Majnemerd2a074b2016-04-29 18:40:34 +00004557 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004558 switch (*CastOp) {
4559 case Instruction::ZExt:
4560 if (CmpI->isUnsigned())
4561 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4562 break;
4563 case Instruction::SExt:
4564 if (CmpI->isSigned())
4565 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4566 break;
4567 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004568 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004569 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4570 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004571 // Here we have the following case:
4572 //
4573 // %cond = cmp iN %x, CmpConst
4574 // %tr = trunc iN %x to iK
4575 // %narrowsel = select i1 %cond, iK %t, iK C
4576 //
4577 // We can always move trunc after select operation:
4578 //
4579 // %cond = cmp iN %x, CmpConst
4580 // %widesel = select i1 %cond, iN %x, iN CmpConst
4581 // %tr = trunc iN %widesel to iK
4582 //
4583 // Note that C could be extended in any way because we don't care about
4584 // upper bits after truncation. It can't be abs pattern, because it would
4585 // look like:
4586 //
4587 // select i1 %cond, x, -x.
4588 //
4589 // So only min/max pattern could be matched. Such match requires widened C
4590 // == CmpConst. That is why set widened C = CmpConst, condition trunc
4591 // CmpConst == C is checked below.
4592 CastedTo = CmpConst;
4593 } else {
4594 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4595 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00004596 break;
4597 case Instruction::FPTrunc:
4598 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4599 break;
4600 case Instruction::FPExt:
4601 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4602 break;
4603 case Instruction::FPToUI:
4604 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4605 break;
4606 case Instruction::FPToSI:
4607 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4608 break;
4609 case Instruction::UIToFP:
4610 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4611 break;
4612 case Instruction::SIToFP:
4613 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4614 break;
4615 default:
4616 break;
4617 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004618
4619 if (!CastedTo)
4620 return nullptr;
4621
David Majnemerd2a074b2016-04-29 18:40:34 +00004622 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004623 Constant *CastedBack =
4624 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004625 if (CastedBack != C)
4626 return nullptr;
4627
4628 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004629}
4630
Sanjay Patele8dc0902016-05-23 17:57:54 +00004631SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004632 Instruction::CastOps *CastOp,
4633 unsigned Depth) {
4634 if (Depth >= MaxDepth)
4635 return {SPF_UNKNOWN, SPNB_NA, false};
4636
James Molloy270ef8c2015-05-15 16:04:50 +00004637 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004638 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004639
James Molloy134bec22015-08-11 09:12:57 +00004640 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4641 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004642
James Molloy134bec22015-08-11 09:12:57 +00004643 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004644 Value *CmpLHS = CmpI->getOperand(0);
4645 Value *CmpRHS = CmpI->getOperand(1);
4646 Value *TrueVal = SI->getTrueValue();
4647 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004648 FastMathFlags FMF;
4649 if (isa<FPMathOperator>(CmpI))
4650 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004651
4652 // Bail out early.
4653 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004654 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004655
4656 // Deal with type mismatches.
4657 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00004658 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
4659 // If this is a potential fmin/fmax with a cast to integer, then ignore
4660 // -0.0 because there is no corresponding integer value.
4661 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4662 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004663 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004664 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004665 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004666 }
4667 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
4668 // If this is a potential fmin/fmax with a cast to integer, then ignore
4669 // -0.0 because there is no corresponding integer value.
4670 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4671 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004672 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004673 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004674 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004675 }
James Molloy270ef8c2015-05-15 16:04:50 +00004676 }
James Molloy134bec22015-08-11 09:12:57 +00004677 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004678 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00004679}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004680
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00004681CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
4682 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
4683 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
4684 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
4685 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
4686 if (SPF == SPF_FMINNUM)
4687 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
4688 if (SPF == SPF_FMAXNUM)
4689 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
4690 llvm_unreachable("unhandled!");
4691}
4692
4693SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
4694 if (SPF == SPF_SMIN) return SPF_SMAX;
4695 if (SPF == SPF_UMIN) return SPF_UMAX;
4696 if (SPF == SPF_SMAX) return SPF_SMIN;
4697 if (SPF == SPF_UMAX) return SPF_UMIN;
4698 llvm_unreachable("unhandled!");
4699}
4700
4701CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
4702 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
4703}
4704
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004705/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004706static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4707 const Value *RHS, const DataLayout &DL,
4708 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004709 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004710 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4711 return true;
4712
4713 switch (Pred) {
4714 default:
4715 return false;
4716
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004717 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004718 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004719
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004720 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004721 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004722 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004723 return false;
4724 }
4725
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004726 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004727 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004728
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004729 // LHS u<= LHS +_{nuw} C for any C
4730 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004731 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004732
4733 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004734 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4735 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004736 const APInt *&CA, const APInt *&CB) {
4737 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4738 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4739 return true;
4740
4741 // If X & C == 0 then (X | C) == X +_{nuw} C
4742 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4743 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004744 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004745 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4746 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004747 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004748 return true;
4749 }
4750
4751 return false;
4752 };
4753
Pete Cooper35b00d52016-08-13 01:05:32 +00004754 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004755 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004756 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4757 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004758
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004759 return false;
4760 }
4761 }
4762}
4763
4764/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004765/// ALHS ARHS" is true. Otherwise, return None.
4766static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004767isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004768 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4769 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004770 switch (Pred) {
4771 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004772 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004773
4774 case CmpInst::ICMP_SLT:
4775 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004776 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4777 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004778 return true;
4779 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004780
4781 case CmpInst::ICMP_ULT:
4782 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004783 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4784 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004785 return true;
4786 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004787 }
4788}
4789
Chad Rosier226a7342016-05-05 17:41:19 +00004790/// Return true if the operands of the two compares match. IsSwappedOps is true
4791/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004792static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4793 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004794 bool &IsSwappedOps) {
4795
4796 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4797 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4798 return IsMatchingOps || IsSwappedOps;
4799}
4800
Chad Rosier41dd31f2016-04-20 19:15:26 +00004801/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4802/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4803/// BRHS" is false. Otherwise, return None if we can't infer anything.
4804static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004805 const Value *ALHS,
4806 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004807 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004808 const Value *BLHS,
4809 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004810 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004811 // Canonicalize the operands so they're matching.
4812 if (IsSwappedOps) {
4813 std::swap(BLHS, BRHS);
4814 BPred = ICmpInst::getSwappedPredicate(BPred);
4815 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004816 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004817 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004818 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004819 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004820
Chad Rosier41dd31f2016-04-20 19:15:26 +00004821 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004822}
4823
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004824/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4825/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4826/// C2" is false. Otherwise, return None if we can't infer anything.
4827static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004828isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4829 const ConstantInt *C1,
4830 CmpInst::Predicate BPred,
4831 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004832 assert(ALHS == BLHS && "LHS operands must match.");
4833 ConstantRange DomCR =
4834 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4835 ConstantRange CR =
4836 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4837 ConstantRange Intersection = DomCR.intersectWith(CR);
4838 ConstantRange Difference = DomCR.difference(CR);
4839 if (Intersection.isEmptySet())
4840 return false;
4841 if (Difference.isEmptySet())
4842 return true;
4843 return None;
4844}
4845
Chad Rosier2f498032017-07-28 18:47:43 +00004846/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4847/// false. Otherwise, return None if we can't infer anything.
4848static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4849 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004850 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004851 unsigned Depth) {
4852 Value *ALHS = LHS->getOperand(0);
4853 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00004854 // The rest of the logic assumes the LHS condition is true. If that's not the
4855 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00004856 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004857 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00004858
4859 Value *BLHS = RHS->getOperand(0);
4860 Value *BRHS = RHS->getOperand(1);
4861 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00004862
Chad Rosier226a7342016-05-05 17:41:19 +00004863 // Can we infer anything when the two compares have matching operands?
4864 bool IsSwappedOps;
4865 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4866 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4867 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004868 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004869 // No amount of additional analysis will infer the second condition, so
4870 // early exit.
4871 return None;
4872 }
4873
4874 // Can we infer anything when the LHS operands match and the RHS operands are
4875 // constants (not necessarily matching)?
4876 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4877 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4878 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4879 cast<ConstantInt>(BRHS)))
4880 return Implication;
4881 // No amount of additional analysis will infer the second condition, so
4882 // early exit.
4883 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004884 }
4885
Chad Rosier41dd31f2016-04-20 19:15:26 +00004886 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00004887 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00004888 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004889}
Chad Rosier2f498032017-07-28 18:47:43 +00004890
Chad Rosierf73a10d2017-08-01 19:22:36 +00004891/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4892/// false. Otherwise, return None if we can't infer anything. We expect the
4893/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4894static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4895 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004896 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00004897 unsigned Depth) {
4898 // The LHS must be an 'or' or an 'and' instruction.
4899 assert((LHS->getOpcode() == Instruction::And ||
4900 LHS->getOpcode() == Instruction::Or) &&
4901 "Expected LHS to be 'and' or 'or'.");
4902
Davide Italiano1a943a92017-08-09 16:06:54 +00004903 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00004904
4905 // If the result of an 'or' is false, then we know both legs of the 'or' are
4906 // false. Similarly, if the result of an 'and' is true, then we know both
4907 // legs of the 'and' are true.
4908 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00004909 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4910 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00004911 // FIXME: Make this non-recursion.
4912 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004913 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004914 return Implication;
4915 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004916 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004917 return Implication;
4918 return None;
4919 }
4920 return None;
4921}
4922
Chad Rosier2f498032017-07-28 18:47:43 +00004923Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004924 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004925 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00004926 // Bail out when we hit the limit.
4927 if (Depth == MaxDepth)
4928 return None;
4929
Chad Rosierf73a10d2017-08-01 19:22:36 +00004930 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4931 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00004932 if (LHS->getType() != RHS->getType())
4933 return None;
4934
4935 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00004936 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00004937
4938 // LHS ==> RHS by definition
4939 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004940 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00004941
Chad Rosierf73a10d2017-08-01 19:22:36 +00004942 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00004943 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00004944 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00004945
Chad Rosier2f498032017-07-28 18:47:43 +00004946 assert(OpTy->isIntegerTy(1) && "implied by above");
4947
Chad Rosier2f498032017-07-28 18:47:43 +00004948 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00004949 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4950 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4951 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004952 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004953
Chad Rosierf73a10d2017-08-01 19:22:36 +00004954 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
4955 // an icmp. FIXME: Add support for and/or on the RHS.
4956 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4957 if (LHSBO && RHSCmp) {
4958 if ((LHSBO->getOpcode() == Instruction::And ||
4959 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00004960 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004961 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00004962 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00004963}