blob: 49a328bbc9ba381f74e42961d9916de1055da9f9 [file] [log] [blame]
Chris Lattner965c7692008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner965c7692008-06-02 01:18:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
James Molloy493e57d2015-10-26 14:10:46 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000022#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000027#include "llvm/Analysis/AssumptionCache.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000028#include "llvm/Analysis/GuardUtils.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"
Matthias Braun50ec0b52017-05-19 22:37:09 +000041#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000042#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000043#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000044#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000045#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000047#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000049#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000053#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000056#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000058#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000059#include "llvm/IR/Type.h"
60#include "llvm/IR/User.h"
61#include "llvm/IR/Value.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Compiler.h"
65#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000066#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000067#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000068#include <algorithm>
69#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000070#include <cassert>
71#include <cstdint>
72#include <iterator>
Fangrui Songf78650a2018-07-30 19:41:25 +000073#include <utility>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000074
Chris Lattner965c7692008-06-02 01:18:21 +000075using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000076using namespace llvm::PatternMatch;
77
78const unsigned MaxDepth = 6;
79
Philip Reames1c292272015-03-10 22:43:20 +000080// Controls the number of uses of the value searched for possible
81// dominating comparisons.
82static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000083 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000084
Craig Topper6b3940a2017-05-03 22:25:19 +000085/// Returns the bitwidth of the given scalar or pointer type. For vector types,
86/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000087static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000088 if (unsigned BitWidth = Ty->getScalarSizeInBits())
89 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000090
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000091 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000092}
Chris Lattner965c7692008-06-02 01:18:21 +000093
Benjamin Kramercfd8d902014-09-12 08:56:53 +000094namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000095
Hal Finkel60db0582014-09-07 18:57:58 +000096// Simplifying using an assume can only be done in a particular control-flow
97// context (the context instruction provides that context). If an assume and
98// the context instruction are not in the same block then the DT helps in
99// figuring out if we can use it.
100struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000101 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000102 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000103 const Instruction *CxtI;
104 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000105
Sanjay Patel54656ca2017-02-06 18:26:06 +0000106 // Unlike the other analyses, this may be a nullptr because not all clients
107 // provide it currently.
108 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000109
Matthias Braun37e5d792016-01-28 06:29:33 +0000110 /// Set of assumptions that should be excluded from further queries.
111 /// This is because of the potential for mutual recursion to cause
112 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
113 /// classic case of this is assume(x = y), which will attempt to determine
114 /// bits in x from bits in y, which will attempt to determine bits in y from
115 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000116 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
117 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000118 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000119
Florian Hahn19f9e322018-08-17 14:39:04 +0000120 /// If true, it is safe to use metadata during simplification.
121 InstrInfoQuery IIQ;
122
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000123 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000124
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000125 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000126 const DominatorTree *DT, bool UseInstrInfo,
127 OptimizationRemarkEmitter *ORE = nullptr)
128 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000129
130 Query(const Query &Q, const Value *NewExcl)
Florian Hahn19f9e322018-08-17 14:39:04 +0000131 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE), IIQ(Q.IIQ),
Sanjay Patel54656ca2017-02-06 18:26:06 +0000132 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000133 Excluded = Q.Excluded;
134 Excluded[NumExcluded++] = NewExcl;
135 assert(NumExcluded <= Excluded.size());
136 }
137
138 bool isExcluded(const Value *Value) const {
139 if (NumExcluded == 0)
140 return false;
141 auto End = Excluded.begin() + NumExcluded;
142 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000143 }
144};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000145
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000146} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000147
Sanjay Patel547e9752014-11-04 16:09:50 +0000148// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000149// the preferred context instruction (if any).
150static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
151 // If we've been provided with a context instruction, then use that (provided
152 // it has been inserted).
153 if (CxtI && CxtI->getParent())
154 return CxtI;
155
156 // If the value is really an already-inserted instruction, then use that.
157 CxtI = dyn_cast<Instruction>(V);
158 if (CxtI && CxtI->getParent())
159 return CxtI;
160
161 return nullptr;
162}
163
Craig Topperb45eabc2017-04-26 16:39:58 +0000164static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000165 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000166
Craig Topperb45eabc2017-04-26 16:39:58 +0000167void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000169 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000170 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000171 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000172 ::computeKnownBits(V, Known, Depth,
Florian Hahn19f9e322018-08-17 14:39:04 +0000173 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000174}
175
Craig Topper6e11a052017-05-08 16:22:48 +0000176static KnownBits computeKnownBits(const Value *V, unsigned Depth,
177 const Query &Q);
178
179KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
180 unsigned Depth, AssumptionCache *AC,
181 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000182 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000183 OptimizationRemarkEmitter *ORE,
184 bool UseInstrInfo) {
185 return ::computeKnownBits(
186 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000187}
188
Pete Cooper35b00d52016-08-13 01:05:32 +0000189bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
Florian Hahn19f9e322018-08-17 14:39:04 +0000190 const DataLayout &DL, AssumptionCache *AC,
191 const Instruction *CxtI, const DominatorTree *DT,
192 bool UseInstrInfo) {
Jingyue Wuca321902015-05-14 23:53:19 +0000193 assert(LHS->getType() == RHS->getType() &&
194 "LHS and RHS should have the same type");
195 assert(LHS->getType()->isIntOrIntVectorTy() &&
196 "LHS and RHS should be integers");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000197 // Look for an inverted mask: (X & ~M) op (Y & M).
198 Value *M;
199 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
200 match(RHS, m_c_And(m_Specific(M), m_Value())))
201 return true;
202 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
203 match(LHS, m_c_And(m_Specific(M), m_Value())))
204 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000205 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000206 KnownBits LHSKnown(IT->getBitWidth());
207 KnownBits RHSKnown(IT->getBitWidth());
Florian Hahn19f9e322018-08-17 14:39:04 +0000208 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
209 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topperb45eabc2017-04-26 16:39:58 +0000210 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000211}
212
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000213bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
214 for (const User *U : CxtI->users()) {
215 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
216 if (IC->isEquality())
217 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
218 if (C->isNullValue())
219 continue;
220 return false;
221 }
222 return true;
223}
224
Pete Cooper35b00d52016-08-13 01:05:32 +0000225static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000226 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000227
Pete Cooper35b00d52016-08-13 01:05:32 +0000228bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000229 bool OrZero, unsigned Depth,
230 AssumptionCache *AC, const Instruction *CxtI,
231 const DominatorTree *DT, bool UseInstrInfo) {
232 return ::isKnownToBeAPowerOfTwo(
233 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000234}
235
Pete Cooper35b00d52016-08-13 01:05:32 +0000236static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237
Pete Cooper35b00d52016-08-13 01:05:32 +0000238bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000239 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000240 const DominatorTree *DT, bool UseInstrInfo) {
241 return ::isKnownNonZero(V, Depth,
242 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243}
244
Pete Cooper35b00d52016-08-13 01:05:32 +0000245bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000246 unsigned Depth, AssumptionCache *AC,
247 const Instruction *CxtI, const DominatorTree *DT,
248 bool UseInstrInfo) {
249 KnownBits Known =
250 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000251 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000252}
253
Pete Cooper35b00d52016-08-13 01:05:32 +0000254bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000255 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000256 const DominatorTree *DT, bool UseInstrInfo) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000257 if (auto *CI = dyn_cast<ConstantInt>(V))
258 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000259
Philip Reames8f12eba2016-03-09 21:31:47 +0000260 // TODO: We'd doing two recursive queries here. We should factor this such
261 // that only a single query is needed.
Florian Hahn19f9e322018-08-17 14:39:04 +0000262 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
263 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
Philip Reames8f12eba2016-03-09 21:31:47 +0000264}
265
Pete Cooper35b00d52016-08-13 01:05:32 +0000266bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000267 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000268 const DominatorTree *DT, bool UseInstrInfo) {
269 KnownBits Known =
270 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000271 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000272}
273
Pete Cooper35b00d52016-08-13 01:05:32 +0000274static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000275
Pete Cooper35b00d52016-08-13 01:05:32 +0000276bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Florian Hahn19f9e322018-08-17 14:39:04 +0000277 const DataLayout &DL, AssumptionCache *AC,
278 const Instruction *CxtI, const DominatorTree *DT,
279 bool UseInstrInfo) {
280 return ::isKnownNonEqual(V1, V2,
281 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
282 UseInstrInfo, /*ORE=*/nullptr));
James Molloy1d88d6f2015-10-22 13:18:42 +0000283}
284
Pete Cooper35b00d52016-08-13 01:05:32 +0000285static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000286 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287
Pete Cooper35b00d52016-08-13 01:05:32 +0000288bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
Florian Hahn19f9e322018-08-17 14:39:04 +0000289 const DataLayout &DL, unsigned Depth,
290 AssumptionCache *AC, const Instruction *CxtI,
291 const DominatorTree *DT, bool UseInstrInfo) {
292 return ::MaskedValueIsZero(
293 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294}
295
Pete Cooper35b00d52016-08-13 01:05:32 +0000296static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
297 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298
Pete Cooper35b00d52016-08-13 01:05:32 +0000299unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000300 unsigned Depth, AssumptionCache *AC,
301 const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000302 const DominatorTree *DT, bool UseInstrInfo) {
303 return ::ComputeNumSignBits(
304 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Hal Finkel60db0582014-09-07 18:57:58 +0000305}
306
Craig Topper8fbb74b2017-03-24 22:12:10 +0000307static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
308 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000309 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000310 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000311 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000312
313 // If an initial sequence of bits in the result is not needed, the
314 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000315 KnownBits LHSKnown(BitWidth);
316 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
317 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000318
Craig Topperb498a232017-08-08 16:29:35 +0000319 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000320}
321
Pete Cooper35b00d52016-08-13 01:05:32 +0000322static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000323 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000324 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000325 unsigned BitWidth = Known.getBitWidth();
326 computeKnownBits(Op1, Known, Depth + 1, Q);
327 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000328
329 bool isKnownNegative = false;
330 bool isKnownNonNegative = false;
331 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000332 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000333 if (Op0 == Op1) {
334 // The product of a number with itself is non-negative.
335 isKnownNonNegative = true;
336 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000337 bool isKnownNonNegativeOp1 = Known.isNonNegative();
338 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
339 bool isKnownNegativeOp1 = Known.isNegative();
340 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000341 // The product of two numbers with the same sign is non-negative.
342 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
343 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
344 // The product of a negative number and a non-negative number is either
345 // negative or zero.
346 if (!isKnownNonNegative)
347 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000348 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000349 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000350 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000351 }
352 }
353
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000354 assert(!Known.hasConflict() && !Known2.hasConflict());
355 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000356 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
357 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000358 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000359 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000360
361 // The result of the bottom bits of an integer multiply can be
362 // inferred by looking at the bottom bits of both operands and
363 // multiplying them together.
364 // We can infer at least the minimum number of known trailing bits
365 // of both operands. Depending on number of trailing zeros, we can
366 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
367 // a and b are divisible by m and n respectively.
368 // We then calculate how many of those bits are inferrable and set
369 // the output. For example, the i8 mul:
370 // a = XXXX1100 (12)
371 // b = XXXX1110 (14)
372 // We know the bottom 3 bits are zero since the first can be divided by
373 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
374 // Applying the multiplication to the trimmed arguments gets:
375 // XX11 (3)
376 // X111 (7)
377 // -------
378 // XX11
379 // XX11
380 // XX11
381 // XX11
382 // -------
383 // XXXXX01
384 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
385 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
386 // The proof for this can be described as:
387 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
388 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
389 // umin(countTrailingZeros(C2), C6) +
390 // umin(C5 - umin(countTrailingZeros(C1), C5),
391 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
392 // %aa = shl i8 %a, C5
393 // %bb = shl i8 %b, C6
394 // %aaa = or i8 %aa, C1
395 // %bbb = or i8 %bb, C2
396 // %mul = mul i8 %aaa, %bbb
397 // %mask = and i8 %mul, C7
398 // =>
399 // %mask = i8 ((C1*C2)&C7)
400 // Where C5, C6 describe the known bits of %a, %b
401 // C1, C2 describe the known bottom bits of %a, %b.
402 // C7 describes the mask of the known bits of the result.
403 APInt Bottom0 = Known.One;
404 APInt Bottom1 = Known2.One;
405
406 // How many times we'd be able to divide each argument by 2 (shr by 1).
407 // This gives us the number of trailing zeros on the multiplication result.
408 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
409 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
410 unsigned TrailZero0 = Known.countMinTrailingZeros();
411 unsigned TrailZero1 = Known2.countMinTrailingZeros();
412 unsigned TrailZ = TrailZero0 + TrailZero1;
413
414 // Figure out the fewest known-bits operand.
415 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
416 TrailBitsKnown1 - TrailZero1);
417 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
418
419 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
420 Bottom1.getLoBits(TrailBitsKnown1);
421
Craig Topperf0aeee02017-05-05 17:36:09 +0000422 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000423 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000424 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
425 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000426
427 // Only make use of no-wrap flags if we failed to compute the sign bit
428 // directly. This matters if the multiplication always overflows, in
429 // which case we prefer to follow the result of the direct computation,
430 // though as the program is invoking undefined behaviour we can choose
431 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000432 if (isKnownNonNegative && !Known.isNegative())
433 Known.makeNonNegative();
434 else if (isKnownNegative && !Known.isNonNegative())
435 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000436}
437
Jingyue Wu37fcb592014-06-19 16:50:16 +0000438void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000439 KnownBits &Known) {
440 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000441 unsigned NumRanges = Ranges.getNumOperands() / 2;
442 assert(NumRanges >= 1);
443
Craig Topperf42b23f2017-04-28 06:28:56 +0000444 Known.Zero.setAllBits();
445 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000446
Rafael Espindola53190532012-03-30 15:52:11 +0000447 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000448 ConstantInt *Lower =
449 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
450 ConstantInt *Upper =
451 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000452 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000453
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000454 // The first CommonPrefixBits of all values in Range are equal.
455 unsigned CommonPrefixBits =
456 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
457
458 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000459 Known.One &= Range.getUnsignedMax() & Mask;
460 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000461 }
Rafael Espindola53190532012-03-30 15:52:11 +0000462}
Jay Foad5a29c362014-05-15 12:12:55 +0000463
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000464static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000465 SmallVector<const Value *, 16> WorkSet(1, I);
466 SmallPtrSet<const Value *, 32> Visited;
467 SmallPtrSet<const Value *, 16> EphValues;
468
Hal Finkelf2199b22015-10-23 20:37:08 +0000469 // The instruction defining an assumption's condition itself is always
470 // considered ephemeral to that assumption (even if it has other
471 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000472 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000473 return true;
474
Hal Finkel60db0582014-09-07 18:57:58 +0000475 while (!WorkSet.empty()) {
476 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000477 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000478 continue;
479
480 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000481 if (llvm::all_of(V->users(), [&](const User *U) {
482 return EphValues.count(U);
483 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000484 if (V == E)
485 return true;
486
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000487 if (V == I || isSafeToSpeculativelyExecute(V)) {
488 EphValues.insert(V);
489 if (const User *U = dyn_cast<User>(V))
490 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
491 J != JE; ++J)
492 WorkSet.push_back(*J);
493 }
Hal Finkel60db0582014-09-07 18:57:58 +0000494 }
495 }
496
497 return false;
498}
499
500// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000501bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000502 if (const CallInst *CI = dyn_cast<CallInst>(I))
503 if (Function *F = CI->getCalledFunction())
504 switch (F->getIntrinsicID()) {
505 default: break;
506 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
507 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000508 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000509 case Intrinsic::dbg_declare:
510 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000511 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000512 case Intrinsic::invariant_start:
513 case Intrinsic::invariant_end:
514 case Intrinsic::lifetime_start:
515 case Intrinsic::lifetime_end:
516 case Intrinsic::objectsize:
517 case Intrinsic::ptr_annotation:
518 case Intrinsic::var_annotation:
519 return true;
520 }
521
522 return false;
523}
524
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000525bool llvm::isValidAssumeForContext(const Instruction *Inv,
526 const Instruction *CxtI,
527 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000528 // There are two restrictions on the use of an assume:
529 // 1. The assume must dominate the context (or the control flow must
530 // reach the assume whenever it reaches the context).
531 // 2. The context must not be in the assume's set of ephemeral values
532 // (otherwise we will use the assume to prove that the condition
533 // feeding the assume is trivially true, thus causing the removal of
534 // the assume).
535
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000536 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000537 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000538 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000539 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
540 // We don't have a DT, but this trivially dominates.
541 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000542 }
543
Pete Cooper54a02552016-08-12 01:00:15 +0000544 // With or without a DT, the only remaining case we will check is if the
545 // instructions are in the same BB. Give up if that is not the case.
546 if (Inv->getParent() != CxtI->getParent())
547 return false;
548
Vedant Kumard3196742018-02-28 19:08:52 +0000549 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000550 // the other instruction. If we don't have a dom tree then we can check if
551 // the assume is first in the BB.
552 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000553 // Search forward from the assume until we reach the context (or the end
554 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000555 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000556 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000557 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000558 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000559 }
560
Pete Cooper54a02552016-08-12 01:00:15 +0000561 // The context comes first, but they're both in the same block. Make sure
562 // there is nothing in between that might interrupt the control flow.
563 for (BasicBlock::const_iterator I =
564 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
565 I != IE; ++I)
566 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
567 return false;
568
569 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000570}
571
Craig Topperb45eabc2017-04-26 16:39:58 +0000572static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
573 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000574 // Use of assumptions is context-sensitive. If we don't have a context, we
575 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000576 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000577 return;
578
Craig Topperb45eabc2017-04-26 16:39:58 +0000579 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000580
Hal Finkel8a9a7832017-01-11 13:24:24 +0000581 // Note that the patterns below need to be kept in sync with the code
582 // in AssumptionCache::updateAffectedValues.
583
584 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000585 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000586 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 CallInst *I = cast<CallInst>(AssumeVH);
588 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
589 "Got assumption for the wrong function!");
590 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000591 continue;
592
Vedant Kumard3196742018-02-28 19:08:52 +0000593 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000594 // We're running this loop for once for each value queried resulting in a
595 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000596
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000597 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
598 "must be an assume intrinsic");
599
600 Value *Arg = I->getArgOperand(0);
601
602 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000603 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000604 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000605 return;
606 }
Sanjay Patel96669962017-01-17 18:15:49 +0000607 if (match(Arg, m_Not(m_Specific(V))) &&
608 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
609 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000610 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000611 return;
612 }
Hal Finkel60db0582014-09-07 18:57:58 +0000613
David Majnemer9b609752014-12-12 23:59:29 +0000614 // The remaining tests are all recursive, so bail out if we hit the limit.
615 if (Depth == MaxDepth)
616 continue;
617
Sander de Smalen0e66db52019-04-10 16:24:48 +0000618 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
619 if (!Cmp)
620 continue;
621
Hal Finkel60db0582014-09-07 18:57:58 +0000622 Value *A, *B;
Sanjay Patel2a707032019-03-03 18:59:33 +0000623 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
Hal Finkel60db0582014-09-07 18:57:58 +0000624
625 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000626 uint64_t C;
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000627 switch (Cmp->getPredicate()) {
628 default:
629 break;
630 case ICmpInst::ICMP_EQ:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000631 // assume(v = a)
632 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
633 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
634 KnownBits RHSKnown(BitWidth);
635 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
636 Known.Zero |= RHSKnown.Zero;
637 Known.One |= RHSKnown.One;
638 // assume(v & b = a)
639 } else if (match(Cmp,
640 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
641 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
642 KnownBits RHSKnown(BitWidth);
643 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
644 KnownBits MaskKnown(BitWidth);
645 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000646
Sander de Smalen0e66db52019-04-10 16:24:48 +0000647 // For those bits in the mask that are known to be one, we can propagate
648 // known bits from the RHS to V.
649 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
650 Known.One |= RHSKnown.One & MaskKnown.One;
651 // assume(~(v & b) = a)
652 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
653 m_Value(A))) &&
654 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
655 KnownBits RHSKnown(BitWidth);
656 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
657 KnownBits MaskKnown(BitWidth);
658 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000659
Sander de Smalen0e66db52019-04-10 16:24:48 +0000660 // For those bits in the mask that are known to be one, we can propagate
661 // inverted known bits from the RHS to V.
662 Known.Zero |= RHSKnown.One & MaskKnown.One;
663 Known.One |= RHSKnown.Zero & MaskKnown.One;
664 // assume(v | b = a)
665 } else if (match(Cmp,
666 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
667 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
668 KnownBits RHSKnown(BitWidth);
669 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
670 KnownBits BKnown(BitWidth);
671 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000672
Sander de Smalen0e66db52019-04-10 16:24:48 +0000673 // For those bits in B that are known to be zero, we can propagate known
674 // bits from the RHS to V.
675 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
676 Known.One |= RHSKnown.One & BKnown.Zero;
677 // assume(~(v | b) = a)
678 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
679 m_Value(A))) &&
680 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
681 KnownBits RHSKnown(BitWidth);
682 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
683 KnownBits BKnown(BitWidth);
684 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000685
Sander de Smalen0e66db52019-04-10 16:24:48 +0000686 // For those bits in B that are known to be zero, we can propagate
687 // inverted known bits from the RHS to V.
688 Known.Zero |= RHSKnown.One & BKnown.Zero;
689 Known.One |= RHSKnown.Zero & BKnown.Zero;
690 // assume(v ^ b = a)
691 } else if (match(Cmp,
692 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
693 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
694 KnownBits RHSKnown(BitWidth);
695 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
696 KnownBits BKnown(BitWidth);
697 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698
Sander de Smalen0e66db52019-04-10 16:24:48 +0000699 // For those bits in B that are known to be zero, we can propagate known
700 // bits from the RHS to V. For those bits in B that are known to be one,
701 // we can propagate inverted known bits from the RHS to V.
702 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
703 Known.One |= RHSKnown.One & BKnown.Zero;
704 Known.Zero |= RHSKnown.One & BKnown.One;
705 Known.One |= RHSKnown.Zero & BKnown.One;
706 // assume(~(v ^ b) = a)
707 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
708 m_Value(A))) &&
709 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
710 KnownBits RHSKnown(BitWidth);
711 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
712 KnownBits BKnown(BitWidth);
713 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000714
Sander de Smalen0e66db52019-04-10 16:24:48 +0000715 // For those bits in B that are known to be zero, we can propagate
716 // inverted known bits from the RHS to V. For those bits in B that are
717 // known to be one, we can propagate known bits from the RHS to V.
718 Known.Zero |= RHSKnown.One & BKnown.Zero;
719 Known.One |= RHSKnown.Zero & BKnown.Zero;
720 Known.Zero |= RHSKnown.Zero & BKnown.One;
721 Known.One |= RHSKnown.One & BKnown.One;
722 // assume(v << c = a)
723 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
724 m_Value(A))) &&
725 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
726 KnownBits RHSKnown(BitWidth);
727 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
728 // For those bits in RHS that are known, we can propagate them to known
729 // bits in V shifted to the right by C.
730 RHSKnown.Zero.lshrInPlace(C);
731 Known.Zero |= RHSKnown.Zero;
732 RHSKnown.One.lshrInPlace(C);
733 Known.One |= RHSKnown.One;
734 // assume(~(v << c) = a)
735 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
736 m_Value(A))) &&
737 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
738 KnownBits RHSKnown(BitWidth);
739 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
740 // For those bits in RHS that are known, we can propagate them inverted
741 // to known bits in V shifted to the right by C.
742 RHSKnown.One.lshrInPlace(C);
743 Known.Zero |= RHSKnown.One;
744 RHSKnown.Zero.lshrInPlace(C);
745 Known.One |= RHSKnown.Zero;
746 // assume(v >> c = a)
747 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
748 m_Value(A))) &&
749 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
750 KnownBits RHSKnown(BitWidth);
751 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
752 // For those bits in RHS that are known, we can propagate them to known
753 // bits in V shifted to the right by C.
754 Known.Zero |= RHSKnown.Zero << C;
755 Known.One |= RHSKnown.One << C;
756 // assume(~(v >> c) = a)
757 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
758 m_Value(A))) &&
759 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
760 KnownBits RHSKnown(BitWidth);
761 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
762 // For those bits in RHS that are known, we can propagate them inverted
763 // to known bits in V shifted to the right by C.
764 Known.Zero |= RHSKnown.One << C;
765 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000766 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000767 break;
768 case ICmpInst::ICMP_SGE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000769 // assume(v >=_s c) where c is non-negative
770 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
771 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
772 KnownBits RHSKnown(BitWidth);
773 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000774
Sander de Smalen0e66db52019-04-10 16:24:48 +0000775 if (RHSKnown.isNonNegative()) {
776 // We know that the sign bit is zero.
777 Known.makeNonNegative();
778 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000779 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000780 break;
781 case ICmpInst::ICMP_SGT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000782 // assume(v >_s c) where c is at least -1.
783 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
784 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
785 KnownBits RHSKnown(BitWidth);
786 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000787
Sander de Smalen0e66db52019-04-10 16:24:48 +0000788 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
789 // We know that the sign bit is zero.
790 Known.makeNonNegative();
791 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000792 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000793 break;
794 case ICmpInst::ICMP_SLE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000795 // assume(v <=_s c) where c is negative
796 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
797 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
798 KnownBits RHSKnown(BitWidth);
799 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000800
Sander de Smalen0e66db52019-04-10 16:24:48 +0000801 if (RHSKnown.isNegative()) {
802 // We know that the sign bit is one.
803 Known.makeNegative();
804 }
805 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000806 break;
807 case ICmpInst::ICMP_SLT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000808 // assume(v <_s c) where c is non-positive
809 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
810 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
811 KnownBits RHSKnown(BitWidth);
812 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
813
814 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
815 // We know that the sign bit is one.
816 Known.makeNegative();
817 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000818 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000819 break;
820 case ICmpInst::ICMP_ULE:
821 // assume(v <=_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000822 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
823 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
824 KnownBits RHSKnown(BitWidth);
825 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000826
Sander de Smalen0e66db52019-04-10 16:24:48 +0000827 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000828 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Sander de Smalen0e66db52019-04-10 16:24:48 +0000829 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000830 break;
831 case ICmpInst::ICMP_ULT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000832 // assume(v <_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000833 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
834 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
835 KnownBits RHSKnown(BitWidth);
836 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
837
838 // If the RHS is known zero, then this assumption must be wrong (nothing
839 // is unsigned less than zero). Signal a conflict and get out of here.
840 if (RHSKnown.isZero()) {
841 Known.Zero.setAllBits();
842 Known.One.setAllBits();
843 break;
844 }
845
846 // Whatever high bits in c are zero are known to be zero (if c is a power
847 // of 2, then one more).
848 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
849 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
850 else
851 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
852 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000853 break;
Hal Finkel60db0582014-09-07 18:57:58 +0000854 }
855 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000856
857 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000858 // have a logical fallacy. It's possible that the assumption is not reachable,
859 // so this isn't a real bug. On the other hand, the program may have undefined
860 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
861 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000862 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000863 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000864
Vivek Pandya95906582017-10-11 17:12:59 +0000865 if (Q.ORE)
866 Q.ORE->emit([&]() {
867 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
868 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
869 CxtI)
870 << "Detected conflicting code assumptions. Program may "
871 "have undefined behavior, or compiler may have "
872 "internal error.";
873 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000874 }
Hal Finkel60db0582014-09-07 18:57:58 +0000875}
876
Sanjay Patelb7d12382017-10-16 14:46:37 +0000877/// Compute known bits from a shift operator, including those with a
878/// non-constant shift amount. Known is the output of this function. Known2 is a
879/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000880/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000881/// respectively, and a shift amount, compute the implied known-zero or
882/// known-one bits of the shift operator's result respectively for that shift
883/// amount. The results from calling KZF and KOF are conservatively combined for
884/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000885static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000886 const Operator *I, KnownBits &Known, KnownBits &Known2,
887 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000888 function_ref<APInt(const APInt &, unsigned)> KZF,
889 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000890 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000891
892 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
893 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
894
Craig Topperb45eabc2017-04-26 16:39:58 +0000895 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000896 Known.Zero = KZF(Known.Zero, ShiftAmt);
897 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000898 // If the known bits conflict, this must be an overflowing left shift, so
899 // the shift result is poison. We can return anything we want. Choose 0 for
900 // the best folding opportunity.
901 if (Known.hasConflict())
902 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000903
Hal Finkelf2199b22015-10-23 20:37:08 +0000904 return;
905 }
906
Craig Topperb45eabc2017-04-26 16:39:58 +0000907 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000908
Sanjay Patele272be72017-10-12 17:31:46 +0000909 // If the shift amount could be greater than or equal to the bit-width of the
910 // LHS, the value could be poison, but bail out because the check below is
911 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000912 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000913 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000914 return;
915 }
916
Craig Topperb45eabc2017-04-26 16:39:58 +0000917 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000918 // BitWidth > 64 and any upper bits are known, we'll end up returning the
919 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000920 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
921 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000922
923 // It would be more-clearly correct to use the two temporaries for this
924 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000925 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000926
James Molloy493e57d2015-10-26 14:10:46 +0000927 // If we know the shifter operand is nonzero, we can sometimes infer more
928 // known bits. However this is expensive to compute, so be lazy about it and
929 // only compute it when absolutely necessary.
930 Optional<bool> ShifterOperandIsNonZero;
931
Hal Finkelf2199b22015-10-23 20:37:08 +0000932 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000933 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
934 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000935 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000936 if (!*ShifterOperandIsNonZero)
937 return;
938 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000939
Craig Topperb45eabc2017-04-26 16:39:58 +0000940 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000941
Craig Topperb45eabc2017-04-26 16:39:58 +0000942 Known.Zero.setAllBits();
943 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000944 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
945 // Combine the shifted known input bits only for those shift amounts
946 // compatible with its known constraints.
947 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
948 continue;
949 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
950 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000951 // If we know the shifter is nonzero, we may be able to infer more known
952 // bits. This check is sunk down as far as possible to avoid the expensive
953 // call to isKnownNonZero if the cheaper checks above fail.
954 if (ShiftAmt == 0) {
955 if (!ShifterOperandIsNonZero.hasValue())
956 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000957 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000958 if (*ShifterOperandIsNonZero)
959 continue;
960 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000961
Sam McCalld0d43e62017-12-04 12:51:49 +0000962 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
963 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000964 }
965
Sanjay Patele272be72017-10-12 17:31:46 +0000966 // If the known bits conflict, the result is poison. Return a 0 and hope the
967 // caller can further optimize that.
968 if (Known.hasConflict())
969 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000970}
971
Craig Topperb45eabc2017-04-26 16:39:58 +0000972static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
973 unsigned Depth, const Query &Q) {
974 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000975
Craig Topperb45eabc2017-04-26 16:39:58 +0000976 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000977 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000978 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000979 case Instruction::Load:
Florian Hahn19f9e322018-08-17 14:39:04 +0000980 if (MDNode *MD =
981 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000982 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000983 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000984 case Instruction::And: {
985 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
987 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000988
Chris Lattner965c7692008-06-02 01:18:21 +0000989 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000990 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000991 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000992 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000993
994 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
995 // here we handle the more general case of adding any odd number by
996 // matching the form add(x, add(x, y)) where y is odd.
997 // TODO: This could be generalized to clearing any bit set in y where the
998 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +0000999 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +00001000 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001001 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001002 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001003 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001004 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001005 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +00001006 }
Jay Foad5a29c362014-05-15 12:12:55 +00001007 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001008 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001009 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +00001010 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1011 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001012
Chris Lattner965c7692008-06-02 01:18:21 +00001013 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001014 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001015 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001016 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001017 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001018 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001019 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1020 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001021
Chris Lattner965c7692008-06-02 01:18:21 +00001022 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001023 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001024 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001025 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1026 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001027 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001028 }
1029 case Instruction::Mul: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001030 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Craig Topperb45eabc2017-04-26 16:39:58 +00001031 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1032 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001033 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001034 }
1035 case Instruction::UDiv: {
1036 // For the purposes of computing leading zeros we can conservatively
1037 // treat a udiv as a logical right shift by the power of 2 known to
1038 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001039 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001040 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001041
Craig Topperf0aeee02017-05-05 17:36:09 +00001042 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001043 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001044 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1045 if (RHSMaxLeadingZeros != BitWidth)
1046 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001047
Craig Topperb45eabc2017-04-26 16:39:58 +00001048 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001049 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001050 }
David Majnemera19d0f22016-08-06 08:16:00 +00001051 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001052 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001053 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1054 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001055 computeKnownBits(RHS, Known, Depth + 1, Q);
1056 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001057 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001058 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1059 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001060 }
1061
1062 unsigned MaxHighOnes = 0;
1063 unsigned MaxHighZeros = 0;
1064 if (SPF == SPF_SMAX) {
1065 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001066 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001067 // We can derive a lower bound on the result by taking the max of the
1068 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001069 MaxHighOnes =
1070 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001071 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001072 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001073 MaxHighZeros = 1;
1074 } else if (SPF == SPF_SMIN) {
1075 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001076 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001077 // We can derive an upper bound on the result by taking the max of the
1078 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001079 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1080 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001081 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001082 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001083 MaxHighOnes = 1;
1084 } else if (SPF == SPF_UMAX) {
1085 // We can derive a lower bound on the result by taking the max of the
1086 // leading one bits.
1087 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001088 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001089 } else if (SPF == SPF_UMIN) {
1090 // We can derive an upper bound on the result by taking the max of the
1091 // leading zero bits.
1092 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001093 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001094 } else if (SPF == SPF_ABS) {
1095 // RHS from matchSelectPattern returns the negation part of abs pattern.
1096 // If the negate has an NSW flag we can assume the sign bit of the result
1097 // will be 0 because that makes abs(INT_MIN) undefined.
Florian Hahn19f9e322018-08-17 14:39:04 +00001098 if (Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Craig Topper8f77dca2018-05-25 19:18:09 +00001099 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001100 }
1101
Chris Lattner965c7692008-06-02 01:18:21 +00001102 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001103 Known.One &= Known2.One;
1104 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001105 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001106 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001107 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001108 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001109 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001110 }
Chris Lattner965c7692008-06-02 01:18:21 +00001111 case Instruction::FPTrunc:
1112 case Instruction::FPExt:
1113 case Instruction::FPToUI:
1114 case Instruction::FPToSI:
1115 case Instruction::SIToFP:
1116 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001117 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001118 case Instruction::PtrToInt:
1119 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001120 // Fall through and handle them the same as zext/trunc.
1121 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001122 case Instruction::ZExt:
1123 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001124 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001125
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001126 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001127 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1128 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001129 Type *ScalarTy = SrcTy->getScalarType();
1130 SrcBitWidth = ScalarTy->isPointerTy() ?
1131 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1132 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001133
1134 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001135 Known = Known.zextOrTrunc(SrcBitWidth, false);
Craig Topperb45eabc2017-04-26 16:39:58 +00001136 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001137 Known = Known.zextOrTrunc(BitWidth, true /* ExtendedBitsAreKnownZero */);
Jay Foad5a29c362014-05-15 12:12:55 +00001138 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001139 }
1140 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001141 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001142 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001143 // TODO: For now, not handling conversions like:
1144 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001145 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001146 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001147 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001148 }
1149 break;
1150 }
1151 case Instruction::SExt: {
1152 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001153 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001154
Craig Topperd938fd12017-05-03 22:07:25 +00001155 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001156 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001157 // If the sign bit of the input is known set or clear, then we know the
1158 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001159 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001160 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001161 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001162 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001163 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001164 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Sam McCalld0d43e62017-12-04 12:51:49 +00001165 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1166 APInt KZResult = KnownZero << ShiftAmt;
1167 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001168 // If this shift has "nsw" keyword, then the result is either a poison
1169 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001170 if (NSW && KnownZero.isSignBitSet())
1171 KZResult.setSignBit();
1172 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001173 };
1174
Sam McCalld0d43e62017-12-04 12:51:49 +00001175 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1176 APInt KOResult = KnownOne << ShiftAmt;
1177 if (NSW && KnownOne.isSignBitSet())
1178 KOResult.setSignBit();
1179 return KOResult;
1180 };
1181
1182 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001183 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001184 }
1185 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001186 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001187 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1188 APInt KZResult = KnownZero.lshr(ShiftAmt);
1189 // High bits known zero.
1190 KZResult.setHighBits(ShiftAmt);
1191 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001192 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001193
Sam McCalld0d43e62017-12-04 12:51:49 +00001194 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1195 return KnownOne.lshr(ShiftAmt);
1196 };
1197
1198 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001199 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001200 }
1201 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001202 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001203 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1204 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001205 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001206
Sam McCalld0d43e62017-12-04 12:51:49 +00001207 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1208 return KnownOne.ashr(ShiftAmt);
1209 };
1210
1211 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001212 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001213 }
Chris Lattner965c7692008-06-02 01:18:21 +00001214 case Instruction::Sub: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001215 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001216 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001218 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001219 }
Chris Lattner965c7692008-06-02 01:18:21 +00001220 case Instruction::Add: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001221 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001222 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001223 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001224 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001225 }
1226 case Instruction::SRem:
1227 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001228 APInt RA = Rem->getValue().abs();
1229 if (RA.isPowerOf2()) {
1230 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001231 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001232
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001233 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001234 Known.Zero = Known2.Zero & LowBits;
1235 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001236
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001237 // If the first operand is non-negative or has all low bits zero, then
1238 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001239 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001240 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001241
1242 // If the first operand is negative and not all low bits are zero, then
1243 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001244 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001245 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001246
Craig Topperb45eabc2017-04-26 16:39:58 +00001247 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001248 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001249 }
1250 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001251
1252 // The sign bit is the LHS's sign bit, except when the result of the
1253 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001254 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001255 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001256 if (Known2.isNonNegative())
1257 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001258
Chris Lattner965c7692008-06-02 01:18:21 +00001259 break;
1260 case Instruction::URem: {
1261 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001262 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001263 if (RA.isPowerOf2()) {
1264 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001265 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1266 Known.Zero |= ~LowBits;
1267 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001268 break;
1269 }
1270 }
1271
1272 // Since the result is less than or equal to either operand, any leading
1273 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001274 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1275 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001276
Craig Topper8df66c62017-05-12 17:20:30 +00001277 unsigned Leaders =
1278 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001279 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001280 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001281 break;
1282 }
1283
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001284 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001285 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001286 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001287 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001288 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001289
Chris Lattner965c7692008-06-02 01:18:21 +00001290 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001291 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001292 break;
1293 }
1294 case Instruction::GetElementPtr: {
1295 // Analyze all of the subscripts of this getelementptr instruction
1296 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001297 KnownBits LocalKnown(BitWidth);
1298 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001299 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001300
1301 gep_type_iterator GTI = gep_type_begin(I);
1302 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1303 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001304 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001305 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001306
1307 // Handle case when index is vector zeroinitializer
1308 Constant *CIndex = cast<Constant>(Index);
1309 if (CIndex->isZeroValue())
1310 continue;
1311
1312 if (CIndex->getType()->isVectorTy())
1313 Index = CIndex->getSplatValue();
1314
Chris Lattner965c7692008-06-02 01:18:21 +00001315 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001316 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001317 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001318 TrailZ = std::min<unsigned>(TrailZ,
1319 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001320 } else {
1321 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001322 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001323 if (!IndexedTy->isSized()) {
1324 TrailZ = 0;
1325 break;
1326 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001327 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001328 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001329 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1330 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001331 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001332 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001333 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001334 }
1335 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001336
Craig Topperb45eabc2017-04-26 16:39:58 +00001337 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001338 break;
1339 }
1340 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001341 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001342 // Handle the case of a simple two-predecessor recurrence PHI.
1343 // There's a lot more that could theoretically be done here, but
1344 // this is sufficient to catch some interesting cases.
1345 if (P->getNumIncomingValues() == 2) {
1346 for (unsigned i = 0; i != 2; ++i) {
1347 Value *L = P->getIncomingValue(i);
1348 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001349 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001350 if (!LU)
1351 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001352 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001353 // Check for operations that have the property that if
1354 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001355 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001356 if (Opcode == Instruction::Add ||
1357 Opcode == Instruction::Sub ||
1358 Opcode == Instruction::And ||
1359 Opcode == Instruction::Or ||
1360 Opcode == Instruction::Mul) {
1361 Value *LL = LU->getOperand(0);
1362 Value *LR = LU->getOperand(1);
1363 // Find a recurrence.
1364 if (LL == I)
1365 L = LR;
1366 else if (LR == I)
1367 L = LL;
1368 else
1369 break;
1370 // Ok, we have a PHI of the form L op= R. Check for low
1371 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001372 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001373
1374 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001375 KnownBits Known3(Known);
1376 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001377
Craig Topper8df66c62017-05-12 17:20:30 +00001378 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1379 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001380
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001381 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
Florian Hahn19f9e322018-08-17 14:39:04 +00001382 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001383 // If initial value of recurrence is nonnegative, and we are adding
1384 // a nonnegative number with nsw, the result can only be nonnegative
1385 // or poison value regardless of the number of times we execute the
1386 // add in phi recurrence. If initial value is negative and we are
1387 // adding a negative number with nsw, the result can only be
1388 // negative or poison value. Similar arguments apply to sub and mul.
1389 //
1390 // (add non-negative, non-negative) --> non-negative
1391 // (add negative, negative) --> negative
1392 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001393 if (Known2.isNonNegative() && Known3.isNonNegative())
1394 Known.makeNonNegative();
1395 else if (Known2.isNegative() && Known3.isNegative())
1396 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001397 }
1398
1399 // (sub nsw non-negative, negative) --> non-negative
1400 // (sub nsw negative, non-negative) --> negative
1401 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001402 if (Known2.isNonNegative() && Known3.isNegative())
1403 Known.makeNonNegative();
1404 else if (Known2.isNegative() && Known3.isNonNegative())
1405 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001406 }
1407
1408 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001409 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1410 Known3.isNonNegative())
1411 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001412 }
1413
Chris Lattner965c7692008-06-02 01:18:21 +00001414 break;
1415 }
1416 }
1417 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001418
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001419 // Unreachable blocks may have zero-operand PHI nodes.
1420 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001421 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001422
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001423 // Otherwise take the unions of the known bit sets of the operands,
1424 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001425 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001426 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001427 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001428 break;
1429
Craig Topperb45eabc2017-04-26 16:39:58 +00001430 Known.Zero.setAllBits();
1431 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001432 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001433 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001434 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001435
Craig Topperb45eabc2017-04-26 16:39:58 +00001436 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001439 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1440 Known.Zero &= Known2.Zero;
1441 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001442 // If all bits have been ruled out, there's no need to check
1443 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001444 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001445 break;
1446 }
1447 }
Chris Lattner965c7692008-06-02 01:18:21 +00001448 break;
1449 }
1450 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001451 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001452 // If range metadata is attached to this call, set known bits from that,
1453 // and then intersect with known bits based on other properties of the
1454 // function.
Florian Hahn19f9e322018-08-17 14:39:04 +00001455 if (MDNode *MD =
1456 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001457 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001458 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001459 computeKnownBits(RV, Known2, Depth + 1, Q);
1460 Known.Zero |= Known2.Zero;
1461 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001462 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001463 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001464 switch (II->getIntrinsicID()) {
1465 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001466 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001467 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1468 Known.Zero |= Known2.Zero.reverseBits();
1469 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001470 break;
Philip Reames675418e2015-10-06 20:20:45 +00001471 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001472 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1473 Known.Zero |= Known2.Zero.byteSwap();
1474 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001475 break;
Craig Topper868813f2017-05-08 17:22:34 +00001476 case Intrinsic::ctlz: {
1477 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1478 // If we have a known 1, its position is our upper bound.
1479 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001480 // If this call is undefined for 0, the result will be less than 2^n.
1481 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001482 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1483 unsigned LowBits = Log2_32(PossibleLZ)+1;
1484 Known.Zero.setBitsFrom(LowBits);
1485 break;
1486 }
1487 case Intrinsic::cttz: {
1488 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1489 // If we have a known 1, its position is our upper bound.
1490 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1491 // If this call is undefined for 0, the result will be less than 2^n.
1492 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1493 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1494 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001495 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001496 break;
1497 }
1498 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001499 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001500 // We can bound the space the count needs. Also, bits known to be zero
1501 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001502 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001503 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001504 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001505 // TODO: we could bound KnownOne using the lower bound on the number
1506 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001507 break;
1508 }
Nikita Popov687b92c2018-12-02 14:14:11 +00001509 case Intrinsic::fshr:
1510 case Intrinsic::fshl: {
1511 const APInt *SA;
1512 if (!match(I->getOperand(2), m_APInt(SA)))
1513 break;
1514
1515 // Normalize to funnel shift left.
1516 uint64_t ShiftAmt = SA->urem(BitWidth);
1517 if (II->getIntrinsicID() == Intrinsic::fshr)
1518 ShiftAmt = BitWidth - ShiftAmt;
1519
1520 KnownBits Known3(Known);
1521 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1522 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1523
1524 Known.Zero =
1525 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1526 Known.One =
1527 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1528 break;
1529 }
Nikita Popoved3ca922019-03-01 20:07:04 +00001530 case Intrinsic::uadd_sat:
1531 case Intrinsic::usub_sat: {
1532 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1533 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1534 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1535
1536 // Add: Leading ones of either operand are preserved.
1537 // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1538 // as leading zeros in the result.
1539 unsigned LeadingKnown;
1540 if (IsAdd)
1541 LeadingKnown = std::max(Known.countMinLeadingOnes(),
1542 Known2.countMinLeadingOnes());
1543 else
1544 LeadingKnown = std::max(Known.countMinLeadingZeros(),
1545 Known2.countMinLeadingOnes());
1546
1547 Known = KnownBits::computeForAddSub(
1548 IsAdd, /* NSW */ false, Known, Known2);
1549
1550 // We select between the operation result and all-ones/zero
1551 // respectively, so we can preserve known ones/zeros.
1552 if (IsAdd) {
1553 Known.One.setHighBits(LeadingKnown);
1554 Known.Zero.clearAllBits();
1555 } else {
1556 Known.Zero.setHighBits(LeadingKnown);
1557 Known.One.clearAllBits();
1558 }
1559 break;
1560 }
Chad Rosierb3628842011-05-26 23:13:19 +00001561 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001562 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001563 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001564 }
1565 }
1566 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001567 case Instruction::ExtractElement:
1568 // Look through extract element. At the moment we keep this simple and skip
1569 // tracking the specific element. But at least we might find information
1570 // valid for all elements of the vector (for example if vector is sign
1571 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001572 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001573 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001574 case Instruction::ExtractValue:
1575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001576 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001577 if (EVI->getNumIndices() != 1) break;
1578 if (EVI->getIndices()[0] == 0) {
1579 switch (II->getIntrinsicID()) {
1580 default: break;
1581 case Intrinsic::uadd_with_overflow:
1582 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001583 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001584 II->getArgOperand(1), false, Known, Known2,
1585 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001586 break;
1587 case Intrinsic::usub_with_overflow:
1588 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001589 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001590 II->getArgOperand(1), false, Known, Known2,
1591 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001592 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001593 case Intrinsic::umul_with_overflow:
1594 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001595 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001596 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001597 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001598 }
1599 }
1600 }
Chris Lattner965c7692008-06-02 01:18:21 +00001601 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001602}
1603
1604/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001605/// them.
1606KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1607 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1608 computeKnownBits(V, Known, Depth, Q);
1609 return Known;
1610}
1611
1612/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001613/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001614///
1615/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1616/// we cannot optimize based on the assumption that it is zero without changing
1617/// it to be an explicit zero. If we don't change it to zero, other code could
1618/// optimized based on the contradictory assumption that it is non-zero.
1619/// Because instcombine aggressively folds operations with undef args anyway,
1620/// this won't lose us code quality.
1621///
1622/// This function is defined on values with integer type, values with pointer
1623/// type, and vectors of integers. In the case
1624/// where V is a vector, known zero, and known one values are the
1625/// same width as the vector element, and the bit is set only if it is true
1626/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001627void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1628 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001629 assert(V && "No Value?");
1630 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001631 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001632
Craig Topperfde47232017-07-09 07:04:03 +00001633 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001634 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001635 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001636
1637 Type *ScalarTy = V->getType()->getScalarType();
1638 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1639 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1640 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001641 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001642 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001643
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001644 const APInt *C;
1645 if (match(V, m_APInt(C))) {
1646 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001647 Known.One = *C;
1648 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001649 return;
1650 }
1651 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001652 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001653 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001654 return;
1655 }
1656 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001657 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001658 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001659 // We know that CDS must be a vector of integers. Take the intersection of
1660 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001661 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001662 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001663 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001664 Known.Zero &= ~Elt;
1665 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001666 }
1667 return;
1668 }
1669
Pete Cooper35b00d52016-08-13 01:05:32 +00001670 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001671 // We know that CV must be a vector of integers. Take the intersection of
1672 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001673 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001674 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1675 Constant *Element = CV->getAggregateElement(i);
1676 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1677 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001678 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001679 return;
1680 }
Craig Topperb98ee582017-10-21 16:35:39 +00001681 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001682 Known.Zero &= ~Elt;
1683 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001684 }
1685 return;
1686 }
1687
Jingyue Wu12b0c282015-06-15 05:46:29 +00001688 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001689 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001690
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001691 // We can't imply anything about undefs.
1692 if (isa<UndefValue>(V))
1693 return;
1694
1695 // There's no point in looking through other users of ConstantData for
1696 // assumptions. Confirm that we've handled them all.
1697 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1698
Jingyue Wu12b0c282015-06-15 05:46:29 +00001699 // Limit search depth.
1700 // All recursive calls that increase depth must come after this.
1701 if (Depth == MaxDepth)
1702 return;
1703
1704 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1705 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001706 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001707 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001708 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001709 return;
1710 }
1711
Pete Cooper35b00d52016-08-13 01:05:32 +00001712 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001713 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001714
Craig Topperb45eabc2017-04-26 16:39:58 +00001715 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001716 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001717 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001718 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001719 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001720 }
1721
Craig Topperb45eabc2017-04-26 16:39:58 +00001722 // computeKnownBitsFromAssume strictly refines Known.
1723 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001724
1725 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001726 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001727
Craig Topperb45eabc2017-04-26 16:39:58 +00001728 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001729}
1730
Sanjay Patelaee84212014-11-04 16:27:42 +00001731/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001732/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001733/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001734/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001735bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001736 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001737 assert(Depth <= MaxDepth && "Limit Search Depth");
1738
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001739 // Attempt to match against constants.
1740 if (OrZero && match(V, m_Power2OrZero()))
1741 return true;
1742 if (match(V, m_Power2()))
1743 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001744
1745 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1746 // it is shifted off the end then the result is undefined.
1747 if (match(V, m_Shl(m_One(), m_Value())))
1748 return true;
1749
Craig Topperbcfd2d12017-04-20 16:56:25 +00001750 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1751 // the bottom. If it is shifted off the bottom then the result is undefined.
1752 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001753 return true;
1754
1755 // The remaining tests are all recursive, so bail out if we hit the limit.
1756 if (Depth++ == MaxDepth)
1757 return false;
1758
Craig Topper9f008862014-04-15 04:59:12 +00001759 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001760 // A shift left or a logical shift right of a power of two is a power of two
1761 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001762 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001763 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001764 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001765
Pete Cooper35b00d52016-08-13 01:05:32 +00001766 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001767 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001768
Pete Cooper35b00d52016-08-13 01:05:32 +00001769 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001770 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1771 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001772
Duncan Sandsba286d72011-10-26 20:55:21 +00001773 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1774 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001775 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1776 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001777 return true;
1778 // X & (-X) is always a power of two or zero.
1779 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1780 return true;
1781 return false;
1782 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001783
David Majnemerb7d54092013-07-30 21:01:36 +00001784 // Adding a power-of-two or zero to the same power-of-two or zero yields
1785 // either the original power-of-two, a larger power-of-two or zero.
1786 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001787 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00001788 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1789 Q.IIQ.hasNoSignedWrap(VOBO)) {
David Majnemerb7d54092013-07-30 21:01:36 +00001790 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1791 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001792 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001793 return true;
1794 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1795 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001796 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001797 return true;
1798
1799 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001800 KnownBits LHSBits(BitWidth);
1801 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001802
Craig Topperb45eabc2017-04-26 16:39:58 +00001803 KnownBits RHSBits(BitWidth);
1804 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001805 // If i8 V is a power of two or zero:
1806 // ZeroBits: 1 1 1 0 1 1 1 1
1807 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001808 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001809 // If OrZero isn't set, we cannot give back a zero result.
1810 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001811 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001812 return true;
1813 }
1814 }
David Majnemerbeab5672013-05-18 19:30:37 +00001815
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001816 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001817 // is a power of two only if the first operand is a power of two and not
1818 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001819 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1820 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001821 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001822 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001823 }
1824
Duncan Sandsd3951082011-01-25 09:38:29 +00001825 return false;
1826}
1827
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001828/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001829///
1830/// Uses properties inherent in a GEP to try to determine whether it is known
1831/// to be non-null.
1832///
1833/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001834static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001835 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001836 const Function *F = nullptr;
1837 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1838 F = I->getFunction();
1839
1840 if (!GEP->isInBounds() ||
1841 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001842 return false;
1843
1844 // FIXME: Support vector-GEPs.
1845 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1846
1847 // If the base pointer is non-null, we cannot walk to a null address with an
1848 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001849 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001850 return true;
1851
Chandler Carruth80d3e562012-12-07 02:08:58 +00001852 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1853 // If so, then the GEP cannot produce a null pointer, as doing so would
1854 // inherently violate the inbounds contract within address space zero.
1855 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1856 GTI != GTE; ++GTI) {
1857 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001858 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001859 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1860 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001861 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001862 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1863 if (ElementOffset > 0)
1864 return true;
1865 continue;
1866 }
1867
1868 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001869 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001870 continue;
1871
1872 // Fast path the constant operand case both for efficiency and so we don't
1873 // increment Depth when just zipping down an all-constant GEP.
1874 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1875 if (!OpC->isZero())
1876 return true;
1877 continue;
1878 }
1879
1880 // We post-increment Depth here because while isKnownNonZero increments it
1881 // as well, when we pop back up that increment won't persist. We don't want
1882 // to recurse 10k times just because we have 10k GEP operands. We don't
1883 // bail completely out because we want to handle constant GEPs regardless
1884 // of depth.
1885 if (Depth++ >= MaxDepth)
1886 continue;
1887
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001888 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001889 return true;
1890 }
1891
1892 return false;
1893}
1894
Nikita Popov9fd02a72019-05-08 14:50:01 +00001895static bool isKnownNonNullFromDominatingCondition(const Value *V,
Nuno Lopes404f1062017-09-09 18:23:11 +00001896 const Instruction *CtxI,
1897 const DominatorTree *DT) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00001898 assert(V->getType()->isPointerTy() && "V must be pointer type");
Nuno Lopes404f1062017-09-09 18:23:11 +00001899 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1900
1901 if (!CtxI || !DT)
1902 return false;
1903
1904 unsigned NumUsesExplored = 0;
1905 for (auto *U : V->users()) {
1906 // Avoid massive lists
1907 if (NumUsesExplored >= DomConditionsMaxUses)
1908 break;
1909 NumUsesExplored++;
1910
Nikita Popov9fd02a72019-05-08 14:50:01 +00001911 // If the value is used as an argument to a call or invoke, then argument
1912 // attributes may provide an answer about null-ness.
1913 if (auto CS = ImmutableCallSite(U))
1914 if (auto *CalledFunc = CS.getCalledFunction())
1915 for (const Argument &Arg : CalledFunc->args())
1916 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1917 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1918 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001919
1920 // Consider only compare instructions uniquely controlling a branch
1921 CmpInst::Predicate Pred;
1922 if (!match(const_cast<User *>(U),
1923 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1924 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1925 continue;
1926
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001927 SmallVector<const User *, 4> WorkList;
1928 SmallPtrSet<const User *, 4> Visited;
Nuno Lopes404f1062017-09-09 18:23:11 +00001929 for (auto *CmpU : U->users()) {
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001930 assert(WorkList.empty() && "Should be!");
1931 if (Visited.insert(CmpU).second)
1932 WorkList.push_back(CmpU);
Nuno Lopes404f1062017-09-09 18:23:11 +00001933
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001934 while (!WorkList.empty()) {
1935 auto *Curr = WorkList.pop_back_val();
1936
1937 // If a user is an AND, add all its users to the work list. We only
1938 // propagate "pred != null" condition through AND because it is only
1939 // correct to assume that all conditions of AND are met in true branch.
1940 // TODO: Support similar logic of OR and EQ predicate?
1941 if (Pred == ICmpInst::ICMP_NE)
1942 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1943 if (BO->getOpcode() == Instruction::And) {
1944 for (auto *BOU : BO->users())
1945 if (Visited.insert(BOU).second)
1946 WorkList.push_back(BOU);
1947 continue;
1948 }
1949
1950 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1951 assert(BI->isConditional() && "uses a comparison!");
1952
1953 BasicBlock *NonNullSuccessor =
1954 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1955 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1956 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1957 return true;
Max Kazantsev3c284bd2018-08-30 03:39:16 +00001958 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001959 DT->dominates(cast<Instruction>(Curr), CtxI)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001960 return true;
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001961 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001962 }
1963 }
1964 }
1965
1966 return false;
1967}
1968
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001969/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1970/// ensure that the value it's attached to is never Value? 'RangeType' is
1971/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001972static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001973 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1974 assert(NumRanges >= 1);
1975 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001976 ConstantInt *Lower =
1977 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1978 ConstantInt *Upper =
1979 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001980 ConstantRange Range(Lower->getValue(), Upper->getValue());
1981 if (Range.contains(Value))
1982 return false;
1983 }
1984 return true;
1985}
1986
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001987/// Return true if the given value is known to be non-zero when defined. For
1988/// vectors, return true if every element is known to be non-zero when
1989/// defined. For pointers, if the context instruction and dominator tree are
1990/// specified, perform context-sensitive analysis and return true if the
1991/// pointer couldn't possibly be null at the specified instruction.
1992/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001993bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001994 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001995 if (C->isNullValue())
1996 return false;
1997 if (isa<ConstantInt>(C))
1998 // Must be non-zero due to null test above.
1999 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00002000
Johannes Doerfert2d63fbb2019-07-15 03:24:35 +00002001 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2002 // See the comment for IntToPtr/PtrToInt instructions below.
2003 if (CE->getOpcode() == Instruction::IntToPtr ||
2004 CE->getOpcode() == Instruction::PtrToInt)
2005 if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType()) <=
2006 Q.DL.getTypeSizeInBits(CE->getType()))
2007 return isKnownNonZero(CE->getOperand(0), Depth, Q);
2008 }
2009
Sanjay Patel23019d12016-05-24 14:18:49 +00002010 // For constant vectors, check that all elements are undefined or known
2011 // non-zero to determine that the whole vector is known non-zero.
2012 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
2013 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2014 Constant *Elt = C->getAggregateElement(i);
2015 if (!Elt || Elt->isNullValue())
2016 return false;
2017 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2018 return false;
2019 }
2020 return true;
2021 }
2022
Nuno Lopes404f1062017-09-09 18:23:11 +00002023 // A global variable in address space 0 is non null unless extern weak
2024 // or an absolute symbol reference. Other address spaces may have null as a
2025 // valid address for a global, so we can't assume anything.
2026 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2027 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2028 GV->getType()->getAddressSpace() == 0)
2029 return true;
2030 } else
2031 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00002032 }
2033
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002034 if (auto *I = dyn_cast<Instruction>(V)) {
Florian Hahn19f9e322018-08-17 14:39:04 +00002035 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002036 // If the possible ranges don't contain zero, then the value is
2037 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002038 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002039 const APInt ZeroValue(Ty->getBitWidth(), 0);
2040 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2041 return true;
2042 }
2043 }
2044 }
2045
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002046 // Some of the tests below are recursive, so bail out if we hit the limit.
2047 if (Depth++ >= MaxDepth)
2048 return false;
2049
Nuno Lopes404f1062017-09-09 18:23:11 +00002050 // Check for pointer simplifications.
2051 if (V->getType()->isPointerTy()) {
2052 // Alloca never returns null, malloc might.
2053 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2054 return true;
2055
2056 // A byval, inalloca, or nonnull argument is never null.
2057 if (const Argument *A = dyn_cast<Argument>(V))
2058 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
2059 return true;
2060
2061 // A Load tagged with nonnull metadata is never null.
2062 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Florian Hahn19f9e322018-08-17 14:39:04 +00002063 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
Nuno Lopes404f1062017-09-09 18:23:11 +00002064 return true;
2065
Chandler Carruth363ac682019-01-07 05:42:51 +00002066 if (const auto *Call = dyn_cast<CallBase>(V)) {
2067 if (Call->isReturnNonNull())
Nuno Lopes404f1062017-09-09 18:23:11 +00002068 return true;
Chandler Carruth363ac682019-01-07 05:42:51 +00002069 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002070 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00002071 }
Nuno Lopes404f1062017-09-09 18:23:11 +00002072 }
2073
Duncan Sandsd3951082011-01-25 09:38:29 +00002074
Nuno Lopes404f1062017-09-09 18:23:11 +00002075 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00002076 if (V->getType()->isPointerTy()) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00002077 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2078 return true;
2079
Johannes Doerfert00102c72019-01-26 23:40:35 +00002080 // Look through bitcast operations, GEPs, and int2ptr instructions as they
2081 // do not alter the value, or at least not the nullness property of the
2082 // value, e.g., int2ptr is allowed to zero/sign extend the value.
2083 //
2084 // Note that we have to take special care to avoid looking through
2085 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2086 // as casts that can alter the value, e.g., AddrSpaceCasts.
Pete Cooper35b00d52016-08-13 01:05:32 +00002087 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002088 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00002089 return true;
Johannes Doerfert00102c72019-01-26 23:40:35 +00002090
2091 if (auto *BCO = dyn_cast<BitCastOperator>(V))
2092 return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2093
2094 if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2095 if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()) <=
2096 Q.DL.getTypeSizeInBits(I2P->getDestTy()))
2097 return isKnownNonZero(I2P->getOperand(0), Depth, Q);
Chandler Carruth80d3e562012-12-07 02:08:58 +00002098 }
2099
Johannes Doerfert00102c72019-01-26 23:40:35 +00002100 // Similar to int2ptr above, we can look through ptr2int here if the cast
2101 // is a no-op or an extend and not a truncate.
2102 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2103 if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()) <=
2104 Q.DL.getTypeSizeInBits(P2I->getDestTy()))
2105 return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2106
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002107 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00002108
2109 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00002110 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00002111 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002112 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002113
2114 // ext X != 0 if X != 0.
2115 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002116 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002117
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002118 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002119 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002120 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002121 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002122 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00002123 if (Q.IIQ.hasNoUnsignedWrap(BO))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002124 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002125
Craig Topperb45eabc2017-04-26 16:39:58 +00002126 KnownBits Known(BitWidth);
2127 computeKnownBits(X, Known, Depth, Q);
2128 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002129 return true;
2130 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002131 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002132 // defined if the sign bit is shifted off the end.
2133 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002134 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002135 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002136 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002137 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002138
Craig Topper6e11a052017-05-08 16:22:48 +00002139 KnownBits Known = computeKnownBits(X, Depth, Q);
2140 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002141 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002142
2143 // If the shifter operand is a constant, and all of the bits shifted
2144 // out are known to be zero, and X is known non-zero then at least one
2145 // non-zero bit must remain.
2146 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002147 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2148 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002149 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002150 return true;
2151 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002152 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002153 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002154 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002155 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002156 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002157 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002158 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002159 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002160 // X + Y.
2161 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002162 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2163 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002164
2165 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002166 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002167 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002168 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002169 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002170
2171 // If X and Y are both negative (as signed values) then their sum is not
2172 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002173 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002174 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2175 // The sign bit of X is set. If some other bit is set then X is not equal
2176 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002177 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002178 return true;
2179 // The sign bit of Y is set. If some other bit is set then Y is not equal
2180 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002181 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002182 return true;
2183 }
2184
2185 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002186 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002187 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002188 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002189 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002190 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002191 return true;
2192 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002193 // X * Y.
2194 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002195 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002196 // If X and Y are non-zero then so is X * Y as long as the multiplication
2197 // does not overflow.
Florian Hahn19f9e322018-08-17 14:39:04 +00002198 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002199 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002200 return true;
2201 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002202 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002203 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002204 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2205 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002206 return true;
2207 }
James Molloy897048b2015-09-29 14:08:45 +00002208 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002209 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002210 // Try and detect a recurrence that monotonically increases from a
2211 // starting value, as these are common as induction variables.
2212 if (PN->getNumIncomingValues() == 2) {
2213 Value *Start = PN->getIncomingValue(0);
2214 Value *Induction = PN->getIncomingValue(1);
2215 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2216 std::swap(Start, Induction);
2217 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2218 if (!C->isZero() && !C->isNegative()) {
2219 ConstantInt *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00002220 if (Q.IIQ.UseInstrInfo &&
2221 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
James Molloy897048b2015-09-29 14:08:45 +00002222 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2223 !X->isNegative())
2224 return true;
2225 }
2226 }
2227 }
Jun Bum Limca832662016-02-01 17:03:07 +00002228 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002229 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002230 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002231 });
2232 if (AllNonZeroConstants)
2233 return true;
James Molloy897048b2015-09-29 14:08:45 +00002234 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002235
Craig Topperb45eabc2017-04-26 16:39:58 +00002236 KnownBits Known(BitWidth);
2237 computeKnownBits(V, Known, Depth, Q);
2238 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002239}
2240
James Molloy1d88d6f2015-10-22 13:18:42 +00002241/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002242static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2243 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002244 if (!BO || BO->getOpcode() != Instruction::Add)
2245 return false;
2246 Value *Op = nullptr;
2247 if (V2 == BO->getOperand(0))
2248 Op = BO->getOperand(1);
2249 else if (V2 == BO->getOperand(1))
2250 Op = BO->getOperand(0);
2251 else
2252 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002253 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002254}
2255
2256/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002257static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002258 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002259 return false;
2260 if (V1->getType() != V2->getType())
2261 // We can't look through casts yet.
2262 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002263 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002264 return true;
2265
Craig Topper3002d5b2017-06-06 07:13:15 +00002266 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002267 // Are any known bits in V1 contradictory to known bits in V2? If V1
2268 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002269 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2270 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002271
Craig Topper8365df82017-06-06 07:13:09 +00002272 if (Known1.Zero.intersects(Known2.One) ||
2273 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002274 return true;
2275 }
2276 return false;
2277}
2278
Sanjay Patelaee84212014-11-04 16:27:42 +00002279/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2280/// simplify operations downstream. Mask is known to be zero for bits that V
2281/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002282///
2283/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002284/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002285/// where V is a vector, the mask, known zero, and known one values are the
2286/// same width as the vector element, and the bit is set only if it is true
2287/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002288bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002289 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002290 KnownBits Known(Mask.getBitWidth());
2291 computeKnownBits(V, Known, Depth, Q);
2292 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002293}
2294
Craig Topperbec15b62018-08-22 23:27:50 +00002295// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2296// Returns the input and lower/upper bounds.
2297static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2298 const APInt *&CLow, const APInt *&CHigh) {
Craig Topper15f86922018-08-23 17:15:02 +00002299 assert(isa<Operator>(Select) &&
2300 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
Craig Topperdfa176e2018-08-23 17:45:53 +00002301 "Input should be a Select!");
Craig Topperbec15b62018-08-22 23:27:50 +00002302
2303 const Value *LHS, *RHS, *LHS2, *RHS2;
2304 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2305 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2306 return false;
2307
2308 if (!match(RHS, m_APInt(CLow)))
2309 return false;
2310
2311 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2312 if (getInverseMinMaxFlavor(SPF) != SPF2)
2313 return false;
2314
2315 if (!match(RHS2, m_APInt(CHigh)))
2316 return false;
2317
2318 if (SPF == SPF_SMIN)
2319 std::swap(CLow, CHigh);
2320
2321 In = LHS2;
2322 return CLow->sle(*CHigh);
2323}
2324
Sanjay Patela06d9892016-06-22 19:20:59 +00002325/// For vector constants, loop over the elements and find the constant with the
2326/// minimum number of sign bits. Return 0 if the value is not a vector constant
2327/// or if any element was not analyzed; otherwise, return the count for the
2328/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002329static unsigned computeNumSignBitsVectorConstant(const Value *V,
2330 unsigned TyBits) {
2331 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002332 if (!CV || !CV->getType()->isVectorTy())
2333 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002334
Sanjay Patela06d9892016-06-22 19:20:59 +00002335 unsigned MinSignBits = TyBits;
2336 unsigned NumElts = CV->getType()->getVectorNumElements();
2337 for (unsigned i = 0; i != NumElts; ++i) {
2338 // If we find a non-ConstantInt, bail out.
2339 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2340 if (!Elt)
2341 return 0;
2342
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002343 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002344 }
2345
2346 return MinSignBits;
2347}
Chris Lattner965c7692008-06-02 01:18:21 +00002348
Sanjoy Das39a684d2017-02-25 20:30:45 +00002349static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2350 const Query &Q);
2351
2352static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2353 const Query &Q) {
2354 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2355 assert(Result > 0 && "At least one sign bit needs to be present!");
2356 return Result;
2357}
2358
Sanjay Patelaee84212014-11-04 16:27:42 +00002359/// Return the number of times the sign bit of the register is replicated into
2360/// the other bits. We know that at least 1 bit is always equal to the sign bit
2361/// (itself), but other cases can give us information. For example, immediately
2362/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002363/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002364/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002365static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2366 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002367 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002368
2369 // We return the minimum number of sign bits that are guaranteed to be present
2370 // in V, so for undef we have to conservatively return 1. We don't have the
2371 // same behavior for poison though -- that's a FIXME today.
2372
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002373 Type *ScalarTy = V->getType()->getScalarType();
2374 unsigned TyBits = ScalarTy->isPointerTy() ?
2375 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2376 Q.DL.getTypeSizeInBits(ScalarTy);
2377
Chris Lattner965c7692008-06-02 01:18:21 +00002378 unsigned Tmp, Tmp2;
2379 unsigned FirstAnswer = 1;
2380
Jay Foada0653a32014-05-14 21:14:37 +00002381 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002382 // below.
2383
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002384 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002385 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002386
Pete Cooper35b00d52016-08-13 01:05:32 +00002387 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002388 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002389 default: break;
2390 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002391 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002392 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002393
Nadav Rotemc99a3872015-03-06 00:23:58 +00002394 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002395 const APInt *Denominator;
2396 // sdiv X, C -> adds log(C) sign bits.
2397 if (match(U->getOperand(1), m_APInt(Denominator))) {
2398
2399 // Ignore non-positive denominator.
2400 if (!Denominator->isStrictlyPositive())
2401 break;
2402
2403 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002404 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002405
2406 // Add floor(log(C)) bits to the numerator bits.
2407 return std::min(TyBits, NumBits + Denominator->logBase2());
2408 }
2409 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002410 }
2411
2412 case Instruction::SRem: {
2413 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002414 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2415 // positive constant. This let us put a lower bound on the number of sign
2416 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002417 if (match(U->getOperand(1), m_APInt(Denominator))) {
2418
2419 // Ignore non-positive denominator.
2420 if (!Denominator->isStrictlyPositive())
2421 break;
2422
2423 // Calculate the incoming numerator bits. SRem by a positive constant
2424 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002425 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002426 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002427
2428 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002429 // denominator. Given that the denominator is positive, there are two
2430 // cases:
2431 //
2432 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2433 // (1 << ceilLogBase2(C)).
2434 //
2435 // 2. the numerator is negative. Then the result range is (-C,0] and
2436 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2437 //
2438 // Thus a lower bound on the number of sign bits is `TyBits -
2439 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002440
Sanjoy Dase561fee2015-03-25 22:33:53 +00002441 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002442 return std::max(NumrBits, ResBits);
2443 }
2444 break;
2445 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002446
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002447 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002448 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002449 // ashr X, C -> adds C sign bits. Vectors too.
2450 const APInt *ShAmt;
2451 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002452 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002453 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002454 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002455 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002456 if (Tmp > TyBits) Tmp = TyBits;
2457 }
2458 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002459 }
2460 case Instruction::Shl: {
2461 const APInt *ShAmt;
2462 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002463 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002464 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002465 if (ShAmt->uge(TyBits) || // Bad shift.
2466 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002467 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002468 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002469 }
2470 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002471 }
Chris Lattner965c7692008-06-02 01:18:21 +00002472 case Instruction::And:
2473 case Instruction::Or:
2474 case Instruction::Xor: // NOT is handled here.
2475 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002476 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002477 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002478 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002479 FirstAnswer = std::min(Tmp, Tmp2);
2480 // We computed what we know about the sign bits as our first
2481 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002482 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002483 }
2484 break;
2485
Craig Topperbec15b62018-08-22 23:27:50 +00002486 case Instruction::Select: {
2487 // If we have a clamp pattern, we know that the number of sign bits will be
2488 // the minimum of the clamp min/max range.
2489 const Value *X;
2490 const APInt *CLow, *CHigh;
2491 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2492 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2493
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002494 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002495 if (Tmp == 1) break;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002496 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002497 return std::min(Tmp, Tmp2);
Craig Topperbec15b62018-08-22 23:27:50 +00002498 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002499
Chris Lattner965c7692008-06-02 01:18:21 +00002500 case Instruction::Add:
2501 // Add can have at most one carry bit. Thus we know that the output
2502 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002503 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002504 if (Tmp == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002505
Chris Lattner965c7692008-06-02 01:18:21 +00002506 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002507 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002508 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002509 KnownBits Known(TyBits);
2510 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002511
Chris Lattner965c7692008-06-02 01:18:21 +00002512 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2513 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002514 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002515 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002516
Chris Lattner965c7692008-06-02 01:18:21 +00002517 // If we are subtracting one from a positive number, there is no carry
2518 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002519 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002520 return Tmp;
2521 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002522
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002523 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002524 if (Tmp2 == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002525 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002526
Chris Lattner965c7692008-06-02 01:18:21 +00002527 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002528 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002529 if (Tmp2 == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002530
Chris Lattner965c7692008-06-02 01:18:21 +00002531 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002532 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002533 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002534 KnownBits Known(TyBits);
2535 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002536 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2537 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002538 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002539 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002540
Chris Lattner965c7692008-06-02 01:18:21 +00002541 // If the input is known to be positive (the sign bit is known clear),
2542 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002543 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002544 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002545
Chris Lattner965c7692008-06-02 01:18:21 +00002546 // Otherwise, we treat this like a SUB.
2547 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002548
Chris Lattner965c7692008-06-02 01:18:21 +00002549 // Sub can have at most one carry bit. Thus we know that the output
2550 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002551 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002552 if (Tmp == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002553 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002554
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002555 case Instruction::Mul: {
2556 // The output of the Mul can be at most twice the valid bits in the inputs.
2557 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002558 if (SignBitsOp0 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002559 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002560 if (SignBitsOp1 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002561 unsigned OutValidBits =
2562 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2563 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2564 }
2565
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002566 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002567 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002568 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002569 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002570 if (NumIncomingValues > 4) break;
2571 // Unreachable blocks may have zero-operand PHI nodes.
2572 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002573
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002574 // Take the minimum of all incoming values. This can't infinitely loop
2575 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002576 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002577 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002578 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002579 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002580 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002581 }
2582 return Tmp;
2583 }
2584
Chris Lattner965c7692008-06-02 01:18:21 +00002585 case Instruction::Trunc:
2586 // FIXME: it's tricky to do anything useful for this, but it is an important
2587 // case for targets like X86.
2588 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002589
2590 case Instruction::ExtractElement:
2591 // Look through extract element. At the moment we keep this simple and skip
2592 // tracking the specific element. But at least we might find information
2593 // valid for all elements of the vector (for example if vector is sign
2594 // extended, shifted, etc).
2595 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002596
Sanjay Patela68096c2018-11-02 15:51:47 +00002597 case Instruction::ShuffleVector: {
Sanjay Patelcac28b42018-11-03 13:18:55 +00002598 // TODO: This is copied almost directly from the SelectionDAG version of
2599 // ComputeNumSignBits. It would be better if we could share common
2600 // code. If not, make sure that changes are translated to the DAG.
2601
2602 // Collect the minimum number of sign bits that are shared by every vector
2603 // element referenced by the shuffle.
2604 auto *Shuf = cast<ShuffleVectorInst>(U);
2605 int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2606 int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2607 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2608 for (int i = 0; i != NumMaskElts; ++i) {
2609 int M = Shuf->getMaskValue(i);
2610 assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2611 // For undef elements, we don't know anything about the common state of
2612 // the shuffle result.
2613 if (M == -1)
2614 return 1;
2615 if (M < NumElts)
2616 DemandedLHS.setBit(M % NumElts);
2617 else
2618 DemandedRHS.setBit(M % NumElts);
2619 }
2620 Tmp = std::numeric_limits<unsigned>::max();
2621 if (!!DemandedLHS)
2622 Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2623 if (!!DemandedRHS) {
2624 Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2625 Tmp = std::min(Tmp, Tmp2);
2626 }
2627 // If we don't know anything, early out and try computeKnownBits fall-back.
2628 if (Tmp == 1)
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002629 break;
Sanjay Patelcac28b42018-11-03 13:18:55 +00002630 assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2631 "Failed to determine minimum sign bits");
2632 return Tmp;
Chris Lattner965c7692008-06-02 01:18:21 +00002633 }
Sanjay Patela68096c2018-11-02 15:51:47 +00002634 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002635
Chris Lattner965c7692008-06-02 01:18:21 +00002636 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2637 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002638
2639 // If we can examine all elements of a vector constant successfully, we're
2640 // done (we can't do any better than that). If not, keep trying.
2641 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2642 return VecSignBits;
2643
Craig Topperb45eabc2017-04-26 16:39:58 +00002644 KnownBits Known(TyBits);
2645 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002646
Sanjay Patele0536212016-06-23 17:41:59 +00002647 // If we know that the sign bit is either zero or one, determine the number of
2648 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002649 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002650}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002651
Sanjay Patelaee84212014-11-04 16:27:42 +00002652/// This function computes the integer multiple of Base that equals V.
2653/// If successful, it returns true and returns the multiple in
2654/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002655/// through SExt instructions only if LookThroughSExt is true.
2656bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002657 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002658 const unsigned MaxDepth = 6;
2659
Dan Gohman6a976bb2009-11-18 00:58:27 +00002660 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002661 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002662 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002663
Chris Lattner229907c2011-07-18 04:54:35 +00002664 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002665
Dan Gohman6a976bb2009-11-18 00:58:27 +00002666 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002667
2668 if (Base == 0)
2669 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002670
Victor Hernandez47444882009-11-10 08:28:35 +00002671 if (Base == 1) {
2672 Multiple = V;
2673 return true;
2674 }
2675
2676 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2677 Constant *BaseVal = ConstantInt::get(T, Base);
2678 if (CO && CO == BaseVal) {
2679 // Multiple is 1.
2680 Multiple = ConstantInt::get(T, 1);
2681 return true;
2682 }
2683
2684 if (CI && CI->getZExtValue() % Base == 0) {
2685 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002686 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002687 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002688
Victor Hernandez47444882009-11-10 08:28:35 +00002689 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002690
Victor Hernandez47444882009-11-10 08:28:35 +00002691 Operator *I = dyn_cast<Operator>(V);
2692 if (!I) return false;
2693
2694 switch (I->getOpcode()) {
2695 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002696 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002697 if (!LookThroughSExt) return false;
2698 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002699 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002700 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002701 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2702 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002703 case Instruction::Shl:
2704 case Instruction::Mul: {
2705 Value *Op0 = I->getOperand(0);
2706 Value *Op1 = I->getOperand(1);
2707
2708 if (I->getOpcode() == Instruction::Shl) {
2709 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2710 if (!Op1CI) return false;
2711 // Turn Op0 << Op1 into Op0 * 2^Op1
2712 APInt Op1Int = Op1CI->getValue();
2713 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002714 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002715 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002716 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002717 }
2718
Craig Topper9f008862014-04-15 04:59:12 +00002719 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002720 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2721 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2722 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002723 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002724 MulC->getType()->getPrimitiveSizeInBits())
2725 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002726 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002727 MulC->getType()->getPrimitiveSizeInBits())
2728 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002729
Chris Lattner72d283c2010-09-05 17:20:46 +00002730 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2731 Multiple = ConstantExpr::getMul(MulC, Op1C);
2732 return true;
2733 }
Victor Hernandez47444882009-11-10 08:28:35 +00002734
2735 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2736 if (Mul0CI->getValue() == 1) {
2737 // V == Base * Op1, so return Op1
2738 Multiple = Op1;
2739 return true;
2740 }
2741 }
2742
Craig Topper9f008862014-04-15 04:59:12 +00002743 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002744 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2745 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2746 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002747 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002748 MulC->getType()->getPrimitiveSizeInBits())
2749 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002750 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002751 MulC->getType()->getPrimitiveSizeInBits())
2752 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002753
Chris Lattner72d283c2010-09-05 17:20:46 +00002754 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2755 Multiple = ConstantExpr::getMul(MulC, Op0C);
2756 return true;
2757 }
Victor Hernandez47444882009-11-10 08:28:35 +00002758
2759 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2760 if (Mul1CI->getValue() == 1) {
2761 // V == Base * Op0, so return Op0
2762 Multiple = Op0;
2763 return true;
2764 }
2765 }
Victor Hernandez47444882009-11-10 08:28:35 +00002766 }
2767 }
2768
2769 // We could not determine if V is a multiple of Base.
2770 return false;
2771}
2772
David Majnemerb4b27232016-04-19 19:10:21 +00002773Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2774 const TargetLibraryInfo *TLI) {
2775 const Function *F = ICS.getCalledFunction();
2776 if (!F)
2777 return Intrinsic::not_intrinsic;
2778
2779 if (F->isIntrinsic())
2780 return F->getIntrinsicID();
2781
2782 if (!TLI)
2783 return Intrinsic::not_intrinsic;
2784
David L. Jonesd21529f2017-01-23 23:16:46 +00002785 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002786 // We're going to make assumptions on the semantics of the functions, check
2787 // that the target knows that it's available in this environment and it does
2788 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002789 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2790 return Intrinsic::not_intrinsic;
2791
2792 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002793 return Intrinsic::not_intrinsic;
2794
2795 // Otherwise check if we have a call to a function that can be turned into a
2796 // vector intrinsic.
2797 switch (Func) {
2798 default:
2799 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002800 case LibFunc_sin:
2801 case LibFunc_sinf:
2802 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002803 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002804 case LibFunc_cos:
2805 case LibFunc_cosf:
2806 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002807 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002808 case LibFunc_exp:
2809 case LibFunc_expf:
2810 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002811 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002812 case LibFunc_exp2:
2813 case LibFunc_exp2f:
2814 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002815 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002816 case LibFunc_log:
2817 case LibFunc_logf:
2818 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002819 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002820 case LibFunc_log10:
2821 case LibFunc_log10f:
2822 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002823 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002824 case LibFunc_log2:
2825 case LibFunc_log2f:
2826 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002827 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002828 case LibFunc_fabs:
2829 case LibFunc_fabsf:
2830 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002831 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002832 case LibFunc_fmin:
2833 case LibFunc_fminf:
2834 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002835 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002836 case LibFunc_fmax:
2837 case LibFunc_fmaxf:
2838 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002839 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002840 case LibFunc_copysign:
2841 case LibFunc_copysignf:
2842 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002843 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002844 case LibFunc_floor:
2845 case LibFunc_floorf:
2846 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002847 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002848 case LibFunc_ceil:
2849 case LibFunc_ceilf:
2850 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002851 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002852 case LibFunc_trunc:
2853 case LibFunc_truncf:
2854 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002855 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002856 case LibFunc_rint:
2857 case LibFunc_rintf:
2858 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002859 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002860 case LibFunc_nearbyint:
2861 case LibFunc_nearbyintf:
2862 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002863 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002864 case LibFunc_round:
2865 case LibFunc_roundf:
2866 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002867 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002868 case LibFunc_pow:
2869 case LibFunc_powf:
2870 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002871 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002872 case LibFunc_sqrt:
2873 case LibFunc_sqrtf:
2874 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002875 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002876 }
2877
2878 return Intrinsic::not_intrinsic;
2879}
2880
Sanjay Patelaee84212014-11-04 16:27:42 +00002881/// Return true if we can prove that the specified FP value is never equal to
2882/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002883///
2884/// NOTE: this function will need to be revisited when we support non-default
2885/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002886bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2887 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002888 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002889 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002890
Sanjay Patel20df88a2017-11-13 17:56:23 +00002891 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002892 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002893 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002894
Sanjay Patel20df88a2017-11-13 17:56:23 +00002895 auto *Op = dyn_cast<Operator>(V);
2896 if (!Op)
2897 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002898
Sanjay Patel20df88a2017-11-13 17:56:23 +00002899 // Check if the nsz fast-math flag is set.
2900 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002901 if (FPO->hasNoSignedZeros())
2902 return true;
2903
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002904 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002905 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002906 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002907
Chris Lattnera12a6de2008-06-02 01:29:46 +00002908 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002909 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002910 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002911
Sanjay Patel20df88a2017-11-13 17:56:23 +00002912 if (auto *Call = dyn_cast<CallInst>(Op)) {
2913 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002914 switch (IID) {
2915 default:
2916 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002917 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002918 case Intrinsic::sqrt:
Matt Arsenault56b31d82018-08-06 15:16:26 +00002919 case Intrinsic::canonicalize:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002920 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002921 // fabs(x) != -0.0
2922 case Intrinsic::fabs:
2923 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002924 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002925 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002926
Chris Lattnera12a6de2008-06-02 01:29:46 +00002927 return false;
2928}
2929
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002930/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2931/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2932/// bit despite comparing equal.
2933static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2934 const TargetLibraryInfo *TLI,
2935 bool SignBitOnly,
2936 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002937 // TODO: This function does not do the right thing when SignBitOnly is true
2938 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2939 // which flips the sign bits of NaNs. See
2940 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2941
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002942 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2943 return !CFP->getValueAPF().isNegative() ||
2944 (!SignBitOnly && CFP->getValueAPF().isZero());
2945 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002946
Craig Topper69c89722018-02-26 22:33:17 +00002947 // Handle vector of constants.
2948 if (auto *CV = dyn_cast<Constant>(V)) {
2949 if (CV->getType()->isVectorTy()) {
2950 unsigned NumElts = CV->getType()->getVectorNumElements();
2951 for (unsigned i = 0; i != NumElts; ++i) {
2952 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2953 if (!CFP)
2954 return false;
2955 if (CFP->getValueAPF().isNegative() &&
2956 (SignBitOnly || !CFP->getValueAPF().isZero()))
2957 return false;
2958 }
2959
2960 // All non-negative ConstantFPs.
2961 return true;
2962 }
2963 }
2964
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002965 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002966 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002967
2968 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002969 if (!I)
2970 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002971
2972 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002973 default:
2974 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002975 // Unsigned integers are always nonnegative.
2976 case Instruction::UIToFP:
2977 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002978 case Instruction::FMul:
2979 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002980 if (I->getOperand(0) == I->getOperand(1) &&
2981 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002982 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002983
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002984 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002985 case Instruction::FAdd:
2986 case Instruction::FDiv:
2987 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002988 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2989 Depth + 1) &&
2990 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2991 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002992 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002993 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2994 Depth + 1) &&
2995 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2996 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002997 case Instruction::FPExt:
2998 case Instruction::FPTrunc:
2999 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003000 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3001 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00003002 case Instruction::ExtractElement:
3003 // Look through extract element. At the moment we keep this simple and skip
3004 // tracking the specific element. But at least we might find information
3005 // valid for all elements of the vector.
3006 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3007 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003008 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003009 const auto *CI = cast<CallInst>(I);
3010 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00003011 switch (IID) {
3012 default:
3013 break;
3014 case Intrinsic::maxnum:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003015 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003016 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
3017 SignBitOnly, Depth + 1)) ||
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003018 (isKnownNeverNaN(I->getOperand(1), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003019 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3020 SignBitOnly, Depth + 1));
3021
Thomas Livelyc3392502018-10-19 19:01:26 +00003022 case Intrinsic::maximum:
3023 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3024 Depth + 1) ||
3025 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3026 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003027 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00003028 case Intrinsic::minimum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003029 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3030 Depth + 1) &&
3031 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3032 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003033 case Intrinsic::exp:
3034 case Intrinsic::exp2:
3035 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00003036 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00003037
3038 case Intrinsic::sqrt:
3039 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3040 if (!SignBitOnly)
3041 return true;
3042 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3043 CannotBeNegativeZero(CI->getOperand(0), TLI));
3044
David Majnemer3ee5f342016-04-13 06:55:52 +00003045 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003046 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00003047 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00003048 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00003049 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003050 }
Justin Lebar322c1272017-01-27 00:58:34 +00003051 // TODO: This is not correct. Given that exp is an integer, here are the
3052 // ways that pow can return a negative value:
3053 //
3054 // pow(x, exp) --> negative if exp is odd and x is negative.
3055 // pow(-0, exp) --> -inf if exp is negative odd.
3056 // pow(-0, exp) --> -0 if exp is positive odd.
3057 // pow(-inf, exp) --> -0 if exp is negative odd.
3058 // pow(-inf, exp) --> -inf if exp is positive odd.
3059 //
3060 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3061 // but we must return false if x == -0. Unfortunately we do not currently
3062 // have a way of expressing this constraint. See details in
3063 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003064 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3065 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00003066
David Majnemer3ee5f342016-04-13 06:55:52 +00003067 case Intrinsic::fma:
3068 case Intrinsic::fmuladd:
3069 // x*x+y is non-negative if y is non-negative.
3070 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003071 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3072 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3073 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003074 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003075 break;
3076 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003077 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003078}
3079
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003080bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3081 const TargetLibraryInfo *TLI) {
3082 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3083}
3084
3085bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3086 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3087}
3088
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003089bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3090 unsigned Depth) {
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003091 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3092
3093 // If we're told that NaNs won't happen, assume they won't.
3094 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3095 if (FPMathOp->hasNoNaNs())
3096 return true;
3097
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003098 // Handle scalar constants.
3099 if (auto *CFP = dyn_cast<ConstantFP>(V))
3100 return !CFP->isNaN();
3101
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003102 if (Depth == MaxDepth)
3103 return false;
3104
Matt Arsenault450fcc72018-08-20 16:51:00 +00003105 if (auto *Inst = dyn_cast<Instruction>(V)) {
3106 switch (Inst->getOpcode()) {
3107 case Instruction::FAdd:
3108 case Instruction::FMul:
3109 case Instruction::FSub:
3110 case Instruction::FDiv:
3111 case Instruction::FRem: {
3112 // TODO: Need isKnownNeverInfinity
3113 return false;
3114 }
3115 case Instruction::Select: {
3116 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3117 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3118 }
3119 case Instruction::SIToFP:
3120 case Instruction::UIToFP:
3121 return true;
3122 case Instruction::FPTrunc:
3123 case Instruction::FPExt:
3124 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3125 default:
3126 break;
3127 }
3128 }
3129
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003130 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3131 switch (II->getIntrinsicID()) {
3132 case Intrinsic::canonicalize:
3133 case Intrinsic::fabs:
3134 case Intrinsic::copysign:
Matt Arsenault450fcc72018-08-20 16:51:00 +00003135 case Intrinsic::exp:
3136 case Intrinsic::exp2:
3137 case Intrinsic::floor:
3138 case Intrinsic::ceil:
3139 case Intrinsic::trunc:
3140 case Intrinsic::rint:
3141 case Intrinsic::nearbyint:
3142 case Intrinsic::round:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003143 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3144 case Intrinsic::sqrt:
3145 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3146 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
Sanjay Patele088d032019-05-07 22:58:31 +00003147 case Intrinsic::minnum:
3148 case Intrinsic::maxnum:
3149 // If either operand is not NaN, the result is not NaN.
3150 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3151 isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003152 default:
3153 return false;
3154 }
3155 }
3156
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003157 // Bail out for constant expressions, but try to handle vector constants.
3158 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3159 return false;
3160
3161 // For vectors, verify that each element is not NaN.
3162 unsigned NumElts = V->getType()->getVectorNumElements();
3163 for (unsigned i = 0; i != NumElts; ++i) {
3164 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3165 if (!Elt)
3166 return false;
3167 if (isa<UndefValue>(Elt))
3168 continue;
3169 auto *CElt = dyn_cast<ConstantFP>(Elt);
3170 if (!CElt || CElt->isNaN())
3171 return false;
3172 }
3173 // All elements were confirmed not-NaN or undefined.
3174 return true;
3175}
3176
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003177Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003178
Chris Lattner9cb10352010-12-26 20:15:01 +00003179 // All byte-wide stores are splatable, even of arbitrary variables.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003180 if (V->getType()->isIntegerTy(8))
3181 return V;
3182
3183 LLVMContext &Ctx = V->getContext();
3184
3185 // Undef don't care.
3186 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3187 if (isa<UndefValue>(V))
3188 return UndefInt8;
3189
Vitaly Buka52096ee2019-07-12 02:23:07 +00003190 const uint64_t Size = DL.getTypeStoreSize(V->getType());
3191 if (!Size)
3192 return UndefInt8;
3193
JF Bastien73d8e4e2018-09-21 05:17:42 +00003194 Constant *C = dyn_cast<Constant>(V);
3195 if (!C) {
3196 // Conceptually, we could handle things like:
3197 // %a = zext i8 %X to i16
3198 // %b = shl i16 %a, 8
3199 // %c = or i16 %a, %b
3200 // but until there is an example that actually needs this, it doesn't seem
3201 // worth worrying about.
3202 return nullptr;
3203 }
Chris Lattneracf6b072011-02-19 19:35:49 +00003204
3205 // Handle 'null' ConstantArrayZero etc.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003206 if (C->isNullValue())
3207 return Constant::getNullValue(Type::getInt8Ty(Ctx));
Craig Topper1bef2c82012-12-22 19:15:35 +00003208
JF Bastien73d8e4e2018-09-21 05:17:42 +00003209 // Constant floating-point values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00003210 // corresponding integer value is "byteable". An important case is 0.0.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003211 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3212 Type *Ty = nullptr;
3213 if (CFP->getType()->isHalfTy())
3214 Ty = Type::getInt16Ty(Ctx);
3215 else if (CFP->getType()->isFloatTy())
3216 Ty = Type::getInt32Ty(Ctx);
3217 else if (CFP->getType()->isDoubleTy())
3218 Ty = Type::getInt64Ty(Ctx);
Chris Lattner9cb10352010-12-26 20:15:01 +00003219 // Don't handle long double formats, which have strange constraints.
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003220 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3221 : nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003222 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003223
Benjamin Kramer17d90152015-02-07 19:29:02 +00003224 // We can handle constant integers that are multiple of 8 bits.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003225 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00003226 if (CI->getBitWidth() % 8 == 0) {
3227 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Benjamin Kramerb4b51502015-03-25 16:49:59 +00003228 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00003229 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003230 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00003231 }
3232 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003233
Vitaly Bukac559e632019-07-12 01:42:03 +00003234 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3235 if (CE->getOpcode() == Instruction::IntToPtr) {
3236 auto PS = DL.getPointerSizeInBits(
3237 cast<PointerType>(CE->getType())->getAddressSpace());
3238 return isBytewiseValue(
3239 ConstantExpr::getIntegerCast(CE->getOperand(0),
3240 Type::getIntNTy(Ctx, PS), false),
3241 DL);
3242 }
3243 }
3244
JF Bastien73d8e4e2018-09-21 05:17:42 +00003245 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3246 if (LHS == RHS)
3247 return LHS;
3248 if (!LHS || !RHS)
Craig Topper9f008862014-04-15 04:59:12 +00003249 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003250 if (LHS == UndefInt8)
3251 return RHS;
3252 if (RHS == UndefInt8)
3253 return LHS;
3254 return nullptr;
3255 };
Craig Topper1bef2c82012-12-22 19:15:35 +00003256
JF Bastien73d8e4e2018-09-21 05:17:42 +00003257 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3258 Value *Val = UndefInt8;
3259 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003260 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
Craig Topper9f008862014-04-15 04:59:12 +00003261 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003262 return Val;
3263 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00003264
Vitaly Bukab1bff762019-07-12 22:37:55 +00003265 if (isa<ConstantAggregate>(C)) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003266 Value *Val = UndefInt8;
3267 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00003268 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
JF Bastien73d8e4e2018-09-21 05:17:42 +00003269 return nullptr;
3270 return Val;
3271 }
3272
3273 // Don't try to handle the handful of other constants.
Craig Topper9f008862014-04-15 04:59:12 +00003274 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003275}
3276
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003277// This is the recursive version of BuildSubAggregate. It takes a few different
3278// arguments. Idxs is the index within the nested struct From that we are
3279// looking at now (which is of type IndexedType). IdxSkip is the number of
3280// indices from Idxs that should be left out when inserting into the resulting
3281// struct. To is the result struct built so far, new insertvalue instructions
3282// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00003283static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00003284 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003285 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003286 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003287 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003288 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003289 // Save the original To argument so we can modify it
3290 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003291 // General case, the type indexed by Idxs is a struct
3292 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3293 // Process each struct element recursively
3294 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003295 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003296 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003297 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003298 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003299 if (!To) {
3300 // Couldn't find any inserted value for this index? Cleanup
3301 while (PrevTo != OrigTo) {
3302 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3303 PrevTo = Del->getAggregateOperand();
3304 Del->eraseFromParent();
3305 }
3306 // Stop processing elements
3307 break;
3308 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003309 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003310 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003311 if (To)
3312 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003313 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003314 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3315 // the struct's elements had a value that was inserted directly. In the latter
3316 // case, perhaps we can't determine each of the subelements individually, but
3317 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003318
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003319 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003320 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003321
3322 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003323 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003324
Vedant Kumard3196742018-02-28 19:08:52 +00003325 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003326 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3327 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003328}
3329
3330// This helper takes a nested struct and extracts a part of it (which is again a
3331// struct) into a new value. For example, given the struct:
3332// { a, { b, { c, d }, e } }
3333// and the indices "1, 1" this returns
3334// { c, d }.
3335//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003336// It does this by inserting an insertvalue for each element in the resulting
3337// struct, as opposed to just inserting a single struct. This will only work if
3338// each of the elements of the substruct are known (ie, inserted into From by an
3339// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003340//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003341// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003342static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003343 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003344 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003345 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003346 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003347 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003348 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003349 unsigned IdxSkip = Idxs.size();
3350
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003351 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003352}
3353
Vedant Kumard3196742018-02-28 19:08:52 +00003354/// Given an aggregate and a sequence of indices, see if the scalar value
3355/// indexed is already around as a register, for example if it was inserted
3356/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003357///
3358/// If InsertBefore is not null, this function will duplicate (modified)
3359/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003360Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3361 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003362 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003363 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003364 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003365 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003366 // We have indices, so V should have an indexable type.
3367 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3368 "Not looking at a struct or array?");
3369 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3370 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003371
Chris Lattner67058832012-01-25 06:48:06 +00003372 if (Constant *C = dyn_cast<Constant>(V)) {
3373 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003374 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003375 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3376 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003377
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003378 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003379 // Loop the indices for the insertvalue instruction in parallel with the
3380 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003381 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003382 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3383 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003384 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003385 // We can't handle this without inserting insertvalues
3386 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003387 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003388
3389 // The requested index identifies a part of a nested aggregate. Handle
3390 // this specially. For example,
3391 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3392 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3393 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3394 // This can be changed into
3395 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3396 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3397 // which allows the unused 0,0 element from the nested struct to be
3398 // removed.
3399 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3400 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003401 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003402
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003403 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003404 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003405 // looking for, then.
3406 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003407 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003408 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003409 }
3410 // If we end up here, the indices of the insertvalue match with those
3411 // requested (though possibly only partially). Now we recursively look at
3412 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003413 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003414 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003415 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003416 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003417
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003418 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003419 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003420 // something else, we can extract from that something else directly instead.
3421 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003422
3423 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003424 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003425 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003426 SmallVector<unsigned, 5> Idxs;
3427 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003428 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003429 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003430
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003431 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003432 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003433
Craig Topper1bef2c82012-12-22 19:15:35 +00003434 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003435 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003436
Jay Foad57aa6362011-07-13 10:26:04 +00003437 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003438 }
3439 // Otherwise, we don't know (such as, extracting from a function return value
3440 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003441 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003442}
Evan Chengda3db112008-06-30 07:31:25 +00003443
Matthias Braun50ec0b52017-05-19 22:37:09 +00003444bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3445 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003446 // Make sure the GEP has exactly three arguments.
3447 if (GEP->getNumOperands() != 3)
3448 return false;
3449
Matthias Braun50ec0b52017-05-19 22:37:09 +00003450 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3451 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003452 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003453 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003454 return false;
3455
3456 // Check to make sure that the first operand of the GEP is an integer and
3457 // has value 0 so that we are sure we're indexing into the initializer.
3458 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3459 if (!FirstIdx || !FirstIdx->isZero())
3460 return false;
3461
3462 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003463}
Chris Lattnere28618d2010-11-30 22:25:26 +00003464
Matthias Braun50ec0b52017-05-19 22:37:09 +00003465bool llvm::getConstantDataArrayInfo(const Value *V,
3466 ConstantDataArraySlice &Slice,
3467 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003468 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003469
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003470 // Look through bitcast instructions and geps.
3471 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003472
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003473 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003474 // offset.
3475 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003476 // The GEP operator should be based on a pointer to string constant, and is
3477 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003478 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003479 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003480
Evan Chengda3db112008-06-30 07:31:25 +00003481 // If the second index isn't a ConstantInt, then this is a variable index
3482 // into the array. If this occurs, we can't say anything meaningful about
3483 // the string.
3484 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003485 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003486 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003487 else
3488 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003489 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3490 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003491 }
Nick Lewycky46209882011-10-20 00:34:35 +00003492
Evan Chengda3db112008-06-30 07:31:25 +00003493 // The GEP instruction, constant or instruction, must reference a global
3494 // variable that is a constant and is initialized. The referenced constant
3495 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003496 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003497 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003498 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003499
Matthias Braun50ec0b52017-05-19 22:37:09 +00003500 const ConstantDataArray *Array;
3501 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003502 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003503 Type *GVTy = GV->getValueType();
3504 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003505 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003506 Array = nullptr;
3507 } else {
3508 const DataLayout &DL = GV->getParent()->getDataLayout();
3509 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3510 uint64_t Length = SizeInBytes / (ElementSize / 8);
3511 if (Length <= Offset)
3512 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003513
Matthias Braun50ec0b52017-05-19 22:37:09 +00003514 Slice.Array = nullptr;
3515 Slice.Offset = 0;
3516 Slice.Length = Length - Offset;
3517 return true;
3518 }
3519 } else {
3520 // This must be a ConstantDataArray.
3521 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3522 if (!Array)
3523 return false;
3524 ArrayTy = Array->getType();
3525 }
3526 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003527 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003528
Matthias Braun50ec0b52017-05-19 22:37:09 +00003529 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003530 if (Offset > NumElts)
3531 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003532
Matthias Braun50ec0b52017-05-19 22:37:09 +00003533 Slice.Array = Array;
3534 Slice.Offset = Offset;
3535 Slice.Length = NumElts - Offset;
3536 return true;
3537}
3538
3539/// This function computes the length of a null-terminated C string pointed to
3540/// by V. If successful, it returns true and returns the string in Str.
3541/// If unsuccessful, it returns false.
3542bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3543 uint64_t Offset, bool TrimAtNul) {
3544 ConstantDataArraySlice Slice;
3545 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3546 return false;
3547
3548 if (Slice.Array == nullptr) {
3549 if (TrimAtNul) {
3550 Str = StringRef();
3551 return true;
3552 }
3553 if (Slice.Length == 1) {
3554 Str = StringRef("", 1);
3555 return true;
3556 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003557 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003558 // of 0s at hand.
3559 return false;
3560 }
3561
3562 // Start out with the entire array in the StringRef.
3563 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003564 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003565 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003566
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003567 if (TrimAtNul) {
3568 // Trim off the \0 and anything after it. If the array is not nul
3569 // terminated, we just return the whole end of string. The client may know
3570 // some other way that the string is length-bound.
3571 Str = Str.substr(0, Str.find('\0'));
3572 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003573 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003574}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003575
3576// These next two are very similar to the above, but also look through PHI
3577// nodes.
3578// TODO: See if we can integrate these two together.
3579
Sanjay Patelaee84212014-11-04 16:27:42 +00003580/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003581/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003582static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003583 SmallPtrSetImpl<const PHINode*> &PHIs,
3584 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003585 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003586 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003587
3588 // If this is a PHI node, there are two cases: either we have already seen it
3589 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003590 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003591 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003592 return ~0ULL; // already in the set.
3593
3594 // If it was new, see if all the input strings are the same length.
3595 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003596 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003597 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003598 if (Len == 0) return 0; // Unknown length -> unknown.
3599
3600 if (Len == ~0ULL) continue;
3601
3602 if (Len != LenSoFar && LenSoFar != ~0ULL)
3603 return 0; // Disagree -> unknown.
3604 LenSoFar = Len;
3605 }
3606
3607 // Success, all agree.
3608 return LenSoFar;
3609 }
3610
3611 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003612 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003613 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003614 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003615 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003616 if (Len2 == 0) return 0;
3617 if (Len1 == ~0ULL) return Len2;
3618 if (Len2 == ~0ULL) return Len1;
3619 if (Len1 != Len2) return 0;
3620 return Len1;
3621 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003622
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003623 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003624 ConstantDataArraySlice Slice;
3625 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003626 return 0;
3627
Matthias Braun50ec0b52017-05-19 22:37:09 +00003628 if (Slice.Array == nullptr)
3629 return 1;
3630
3631 // Search for nul characters
3632 unsigned NullIndex = 0;
3633 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3634 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3635 break;
3636 }
3637
3638 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003639}
3640
Sanjay Patelaee84212014-11-04 16:27:42 +00003641/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003642/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003643uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003644 if (!V->getType()->isPointerTy())
3645 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003646
Pete Cooper35b00d52016-08-13 01:05:32 +00003647 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003648 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003649 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3650 // an empty string as a length.
3651 return Len == ~0ULL ? 1 : Len;
3652}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003653
Chandler Carruth363ac682019-01-07 05:42:51 +00003654const Value *llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call) {
3655 assert(Call &&
3656 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
3657 if (const Value *RV = Call->getReturnedArgOperand())
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003658 return RV;
3659 // This can be used only as a aliasing property.
Chandler Carruth363ac682019-01-07 05:42:51 +00003660 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call))
3661 return Call->getArgOperand(0);
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003662 return nullptr;
3663}
3664
3665bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Chandler Carruth363ac682019-01-07 05:42:51 +00003666 const CallBase *Call) {
3667 return Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
Evgeniy Stepanov50dc28b2019-07-03 20:19:14 +00003668 Call->getIntrinsicID() == Intrinsic::strip_invariant_group ||
3669 Call->getIntrinsicID() == Intrinsic::aarch64_irg;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003670}
3671
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003672/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003673/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003674static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3675 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003676 // Find the loop-defined value.
3677 Loop *L = LI->getLoopFor(PN->getParent());
3678 if (PN->getNumIncomingValues() != 2)
3679 return true;
3680
3681 // Find the value from previous iteration.
3682 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3683 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3684 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3685 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3686 return true;
3687
3688 // If a new pointer is loaded in the loop, the pointer references a different
3689 // object in every iteration. E.g.:
3690 // for (i)
3691 // int *p = a[i];
3692 // ...
3693 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3694 if (!L->isLoopInvariant(Load->getPointerOperand()))
3695 return false;
3696 return true;
3697}
3698
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003699Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3700 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003701 if (!V->getType()->isPointerTy())
3702 return V;
3703 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3704 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3705 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003706 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3707 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003708 V = cast<Operator>(V)->getOperand(0);
3709 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003710 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003711 return V;
3712 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003713 } else if (isa<AllocaInst>(V)) {
3714 // An alloca can't be further simplified.
3715 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003716 } else {
Chandler Carruth363ac682019-01-07 05:42:51 +00003717 if (auto *Call = dyn_cast<CallBase>(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003718 // CaptureTracking can know about special capturing properties of some
3719 // intrinsics like launder.invariant.group, that can't be expressed with
3720 // the attributes, but have properties like returning aliasing pointer.
3721 // Because some analysis may assume that nocaptured pointer is not
3722 // returned from some special intrinsic (because function would have to
3723 // be marked with returns attribute), it is crucial to use this function
3724 // because it should be in sync with CaptureTracking. Not using it may
3725 // cause weird miscompilations where 2 aliasing pointers are assumed to
3726 // noalias.
Chandler Carruth363ac682019-01-07 05:42:51 +00003727 if (auto *RP = getArgumentAliasingToReturnedPointer(Call)) {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003728 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003729 continue;
3730 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003731 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003732
Dan Gohman05b18f12010-12-15 20:49:55 +00003733 // See if InstructionSimplify knows any relevant tricks.
3734 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003735 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003736 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003737 V = Simplified;
3738 continue;
3739 }
3740
Dan Gohmana4fcd242010-12-15 20:02:24 +00003741 return V;
3742 }
3743 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3744 }
3745 return V;
3746}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003747
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003748void llvm::GetUnderlyingObjects(const Value *V,
3749 SmallVectorImpl<const Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003750 const DataLayout &DL, LoopInfo *LI,
3751 unsigned MaxLookup) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003752 SmallPtrSet<const Value *, 4> Visited;
3753 SmallVector<const Value *, 4> Worklist;
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003754 Worklist.push_back(V);
3755 do {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003756 const Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003757 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003758
David Blaikie70573dc2014-11-19 07:49:26 +00003759 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003760 continue;
3761
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003762 if (auto *SI = dyn_cast<SelectInst>(P)) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003763 Worklist.push_back(SI->getTrueValue());
3764 Worklist.push_back(SI->getFalseValue());
3765 continue;
3766 }
3767
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003768 if (auto *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003769 // If this PHI changes the underlying object in every iteration of the
3770 // loop, don't look through it. Consider:
3771 // int **A;
3772 // for (i) {
3773 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3774 // Curr = A[i];
3775 // *Prev, *Curr;
3776 //
3777 // Prev is tracking Curr one iteration behind so they refer to different
3778 // underlying objects.
3779 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3780 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003781 for (Value *IncValue : PN->incoming_values())
3782 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003783 continue;
3784 }
3785
3786 Objects.push_back(P);
3787 } while (!Worklist.empty());
3788}
3789
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003790/// This is the function that does the work of looking through basic
3791/// ptrtoint+arithmetic+inttoptr sequences.
3792static const Value *getUnderlyingObjectFromInt(const Value *V) {
3793 do {
3794 if (const Operator *U = dyn_cast<Operator>(V)) {
3795 // If we find a ptrtoint, we can transfer control back to the
3796 // regular getUnderlyingObjectFromInt.
3797 if (U->getOpcode() == Instruction::PtrToInt)
3798 return U->getOperand(0);
3799 // If we find an add of a constant, a multiplied value, or a phi, it's
3800 // likely that the other operand will lead us to the base
3801 // object. We don't have to worry about the case where the
3802 // object address is somehow being computed by the multiply,
3803 // because our callers only care when the result is an
3804 // identifiable object.
3805 if (U->getOpcode() != Instruction::Add ||
3806 (!isa<ConstantInt>(U->getOperand(1)) &&
3807 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3808 !isa<PHINode>(U->getOperand(1))))
3809 return V;
3810 V = U->getOperand(0);
3811 } else {
3812 return V;
3813 }
3814 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3815 } while (true);
3816}
3817
3818/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3819/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003820/// It returns false if unidentified object is found in GetUnderlyingObjects.
3821bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003822 SmallVectorImpl<Value *> &Objects,
3823 const DataLayout &DL) {
3824 SmallPtrSet<const Value *, 16> Visited;
3825 SmallVector<const Value *, 4> Working(1, V);
3826 do {
3827 V = Working.pop_back_val();
3828
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003829 SmallVector<const Value *, 4> Objs;
3830 GetUnderlyingObjects(V, Objs, DL);
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003831
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003832 for (const Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003833 if (!Visited.insert(V).second)
3834 continue;
3835 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3836 const Value *O =
3837 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3838 if (O->getType()->isPointerTy()) {
3839 Working.push_back(O);
3840 continue;
3841 }
3842 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003843 // If GetUnderlyingObjects fails to find an identifiable object,
3844 // getUnderlyingObjectsForCodeGen also fails for safety.
3845 if (!isIdentifiedObject(V)) {
3846 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003847 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003848 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003849 Objects.push_back(const_cast<Value *>(V));
3850 }
3851 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003852 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003853}
3854
Sanjay Patelaee84212014-11-04 16:27:42 +00003855/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003856bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003857 for (const User *U : V->users()) {
3858 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003859 if (!II) return false;
3860
Vedant Kumarb264d692018-12-21 21:49:40 +00003861 if (!II->isLifetimeStartOrEnd())
Nick Lewycky3e334a42011-06-27 04:20:45 +00003862 return false;
3863 }
3864 return true;
3865}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003866
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003867bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3868 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003869 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003870 const Operator *Inst = dyn_cast<Operator>(V);
3871 if (!Inst)
3872 return false;
3873
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003874 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3875 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3876 if (C->canTrap())
3877 return false;
3878
3879 switch (Inst->getOpcode()) {
3880 default:
3881 return true;
3882 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003883 case Instruction::URem: {
3884 // x / y is undefined if y == 0.
3885 const APInt *V;
3886 if (match(Inst->getOperand(1), m_APInt(V)))
3887 return *V != 0;
3888 return false;
3889 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003890 case Instruction::SDiv:
3891 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003892 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003893 const APInt *Numerator, *Denominator;
3894 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3895 return false;
3896 // We cannot hoist this division if the denominator is 0.
3897 if (*Denominator == 0)
3898 return false;
3899 // It's safe to hoist if the denominator is not 0 or -1.
3900 if (*Denominator != -1)
3901 return true;
3902 // At this point we know that the denominator is -1. It is safe to hoist as
3903 // long we know that the numerator is not INT_MIN.
3904 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3905 return !Numerator->isMinSignedValue();
3906 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003907 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003908 }
3909 case Instruction::Load: {
3910 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003911 if (!LI->isUnordered() ||
3912 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003913 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003914 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003915 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3916 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003917 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003918 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003919 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
Tim Northover60afa492019-07-09 11:35:35 +00003920 LI->getType(), LI->getAlignment(),
3921 DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003922 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003923 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003924 auto *CI = cast<const CallInst>(Inst);
3925 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003926
Matt Arsenault6a288c12017-05-03 02:26:10 +00003927 // The called function could have undefined behavior or side-effects, even
3928 // if marked readnone nounwind.
3929 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003930 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003931 case Instruction::VAArg:
3932 case Instruction::Alloca:
3933 case Instruction::Invoke:
Craig Topper784929d2019-02-08 20:48:56 +00003934 case Instruction::CallBr:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003935 case Instruction::PHI:
3936 case Instruction::Store:
3937 case Instruction::Ret:
3938 case Instruction::Br:
3939 case Instruction::IndirectBr:
3940 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003941 case Instruction::Unreachable:
3942 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003943 case Instruction::AtomicRMW:
3944 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003945 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003946 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003947 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003948 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003949 case Instruction::CatchRet:
3950 case Instruction::CleanupPad:
3951 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003952 return false; // Misc instructions which have effects
3953 }
3954}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003955
Quentin Colombet6443cce2015-08-06 18:44:34 +00003956bool llvm::mayBeMemoryDependent(const Instruction &I) {
3957 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3958}
3959
Nikita Popovd0f13e62019-05-26 13:22:01 +00003960/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
3961static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
3962 switch (OR) {
3963 case ConstantRange::OverflowResult::MayOverflow:
3964 return OverflowResult::MayOverflow;
Nikita Popov332c1002019-05-28 18:08:31 +00003965 case ConstantRange::OverflowResult::AlwaysOverflowsLow:
3966 return OverflowResult::AlwaysOverflowsLow;
3967 case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
3968 return OverflowResult::AlwaysOverflowsHigh;
Nikita Popovd0f13e62019-05-26 13:22:01 +00003969 case ConstantRange::OverflowResult::NeverOverflows:
3970 return OverflowResult::NeverOverflows;
3971 }
3972 llvm_unreachable("Unknown OverflowResult");
3973}
3974
3975/// Combine constant ranges from computeConstantRange() and computeKnownBits().
3976static ConstantRange computeConstantRangeIncludingKnownBits(
3977 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
3978 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3979 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
3980 KnownBits Known = computeKnownBits(
3981 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
3982 ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
3983 ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
3984 ConstantRange::PreferredRangeType RangeType =
3985 ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
3986 return CR1.intersectWith(CR2, RangeType);
3987}
3988
Florian Hahn19f9e322018-08-17 14:39:04 +00003989OverflowResult llvm::computeOverflowForUnsignedMul(
3990 const Value *LHS, const Value *RHS, const DataLayout &DL,
3991 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
3992 bool UseInstrInfo) {
Nikita Popovd0f13e62019-05-26 13:22:01 +00003993 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
3994 nullptr, UseInstrInfo);
3995 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
3996 nullptr, UseInstrInfo);
3997 ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
3998 ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
3999 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
David Majnemer491331a2015-01-02 07:29:43 +00004000}
David Majnemer5310c1e2015-01-07 00:39:50 +00004001
Florian Hahn19f9e322018-08-17 14:39:04 +00004002OverflowResult
4003llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4004 const DataLayout &DL, AssumptionCache *AC,
4005 const Instruction *CxtI,
4006 const DominatorTree *DT, bool UseInstrInfo) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004007 // Multiplying n * m significant bits yields a result of n + m significant
4008 // bits. If the total number of significant bits does not exceed the
4009 // result bit width (minus 1), there is no overflow.
4010 // This means if we have enough leading sign bits in the operands
4011 // we can guarantee that the result does not overflow.
4012 // Ref: "Hacker's Delight" by Henry Warren
4013 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4014
4015 // Note that underestimating the number of sign bits gives a more
4016 // conservative answer.
4017 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4018 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4019
4020 // First handle the easy case: if we have enough sign bits there's
4021 // definitely no overflow.
4022 if (SignBits > BitWidth + 1)
4023 return OverflowResult::NeverOverflows;
4024
4025 // There are two ambiguous cases where there can be no overflow:
4026 // SignBits == BitWidth + 1 and
4027 // SignBits == BitWidth
4028 // The second case is difficult to check, therefore we only handle the
4029 // first case.
4030 if (SignBits == BitWidth + 1) {
4031 // It overflows only when both arguments are negative and the true
4032 // product is exactly the minimum negative number.
4033 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4034 // For simplicity we just check if at least one side is not negative.
Florian Hahn19f9e322018-08-17 14:39:04 +00004035 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4036 nullptr, UseInstrInfo);
4037 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4038 nullptr, UseInstrInfo);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004039 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4040 return OverflowResult::NeverOverflows;
4041 }
4042 return OverflowResult::MayOverflow;
4043}
4044
Florian Hahn19f9e322018-08-17 14:39:04 +00004045OverflowResult llvm::computeOverflowForUnsignedAdd(
4046 const Value *LHS, const Value *RHS, const DataLayout &DL,
4047 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4048 bool UseInstrInfo) {
Nikita Popov20838192019-03-19 17:53:56 +00004049 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4050 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4051 nullptr, UseInstrInfo);
4052 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4053 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4054 nullptr, UseInstrInfo);
Nikita Popov614b1be2019-03-15 18:37:45 +00004055 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
David Majnemer5310c1e2015-01-07 00:39:50 +00004056}
James Molloy71b91c22015-05-11 14:42:20 +00004057
Pete Cooper35b00d52016-08-13 01:05:32 +00004058static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4059 const Value *RHS,
4060 const AddOperator *Add,
4061 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004062 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00004063 const Instruction *CxtI,
4064 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004065 if (Add && Add->hasNoSignedWrap()) {
4066 return OverflowResult::NeverOverflows;
4067 }
4068
Craig Topperbb973722017-05-15 02:44:08 +00004069 // If LHS and RHS each have at least two sign bits, the addition will look
4070 // like
4071 //
4072 // XX..... +
4073 // YY.....
4074 //
4075 // If the carry into the most significant position is 0, X and Y can't both
4076 // be 1 and therefore the carry out of the addition is also 0.
4077 //
4078 // If the carry into the most significant position is 1, X and Y can't both
4079 // be 0 and therefore the carry out of the addition is also 1.
4080 //
4081 // Since the carry into the most significant position is always equal to
4082 // the carry out of the addition, there is no signed overflow.
4083 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4084 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4085 return OverflowResult::NeverOverflows;
4086
Nikita Popov10edd2b2019-04-09 16:12:59 +00004087 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4088 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4089 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4090 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov322e2db2019-03-17 21:25:26 +00004091 OverflowResult OR =
4092 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4093 if (OR != OverflowResult::MayOverflow)
4094 return OR;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004095
4096 // The remaining code needs Add to be available. Early returns if not so.
4097 if (!Add)
4098 return OverflowResult::MayOverflow;
4099
4100 // If the sign of Add is the same as at least one of the operands, this add
Nikita Popov280a6b02019-03-22 17:51:40 +00004101 // CANNOT overflow. If this can be determined from the known bits of the
4102 // operands the above signedAddMayOverflow() check will have already done so.
4103 // The only other way to improve on the known bits is from an assumption, so
4104 // call computeKnownBitsFromAssume() directly.
Jingyue Wu10fcea52015-08-20 18:27:04 +00004105 bool LHSOrRHSKnownNonNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004106 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
Fangrui Songf78650a2018-07-30 19:41:25 +00004107 bool LHSOrRHSKnownNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004108 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00004109 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Nikita Popov6e9157d2019-04-09 07:13:09 +00004110 KnownBits AddKnown(LHSRange.getBitWidth());
Nikita Popov280a6b02019-03-22 17:51:40 +00004111 computeKnownBitsFromAssume(
4112 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
Craig Topper6e11a052017-05-08 16:22:48 +00004113 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
Nikita Popov280a6b02019-03-22 17:51:40 +00004114 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
Jingyue Wu10fcea52015-08-20 18:27:04 +00004115 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004116 }
4117
4118 return OverflowResult::MayOverflow;
4119}
4120
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004121OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4122 const Value *RHS,
4123 const DataLayout &DL,
4124 AssumptionCache *AC,
4125 const Instruction *CxtI,
4126 const DominatorTree *DT) {
Nikita Popov20838192019-03-19 17:53:56 +00004127 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4128 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4129 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4130 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov614b1be2019-03-15 18:37:45 +00004131 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004132}
4133
4134OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4135 const Value *RHS,
4136 const DataLayout &DL,
4137 AssumptionCache *AC,
4138 const Instruction *CxtI,
4139 const DominatorTree *DT) {
4140 // If LHS and RHS each have at least two sign bits, the subtraction
4141 // cannot overflow.
4142 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4143 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4144 return OverflowResult::NeverOverflows;
4145
Nikita Popov4b2323d2019-04-09 17:01:49 +00004146 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4147 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4148 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4149 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov3af5b282019-03-21 17:23:51 +00004150 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004151}
4152
Nikita Popov79dffc62019-04-16 18:55:16 +00004153bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
Pete Cooper35b00d52016-08-13 01:05:32 +00004154 const DominatorTree &DT) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004155 SmallVector<const BranchInst *, 2> GuardingBranches;
4156 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004157
Nikita Popov79dffc62019-04-16 18:55:16 +00004158 for (const User *U : WO->users()) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004159 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004160 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4161
4162 if (EVI->getIndices()[0] == 0)
4163 Results.push_back(EVI);
4164 else {
4165 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4166
Pete Cooper35b00d52016-08-13 01:05:32 +00004167 for (const auto *U : EVI->users())
4168 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004169 assert(B->isConditional() && "How else is it using an i1?");
4170 GuardingBranches.push_back(B);
4171 }
4172 }
4173 } else {
4174 // We are using the aggregate directly in a way we don't want to analyze
4175 // here (storing it to a global, say).
4176 return false;
4177 }
4178 }
4179
Pete Cooper35b00d52016-08-13 01:05:32 +00004180 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004181 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4182 if (!NoWrapEdge.isSingleEdge())
4183 return false;
4184
4185 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004186 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004187 // If the extractvalue itself is not executed on overflow, the we don't
4188 // need to check each use separately, since domination is transitive.
4189 if (DT.dominates(NoWrapEdge, Result->getParent()))
4190 continue;
4191
4192 for (auto &RU : Result->uses())
4193 if (!DT.dominates(NoWrapEdge, RU))
4194 return false;
4195 }
4196
4197 return true;
4198 };
4199
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004200 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004201}
4202
4203
Pete Cooper35b00d52016-08-13 01:05:32 +00004204OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004205 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004206 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004207 const Instruction *CxtI,
4208 const DominatorTree *DT) {
4209 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004210 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004211}
4212
Pete Cooper35b00d52016-08-13 01:05:32 +00004213OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4214 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004215 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004216 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004217 const Instruction *CxtI,
4218 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004219 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004220}
4221
Jingyue Wu42f1d672015-07-28 18:22:40 +00004222bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004223 // A memory operation returns normally if it isn't volatile. A volatile
4224 // operation is allowed to trap.
4225 //
4226 // An atomic operation isn't guaranteed to return in a reasonable amount of
4227 // time because it's possible for another thread to interfere with it for an
4228 // arbitrary length of time, but programs aren't allowed to rely on that.
4229 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4230 return !LI->isVolatile();
4231 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4232 return !SI->isVolatile();
4233 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4234 return !CXI->isVolatile();
4235 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4236 return !RMWI->isVolatile();
4237 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4238 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004239
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004240 // If there is no successor, then execution can't transfer to it.
4241 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4242 return !CRI->unwindsToCaller();
4243 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4244 return !CatchSwitch->unwindsToCaller();
4245 if (isa<ResumeInst>(I))
4246 return false;
4247 if (isa<ReturnInst>(I))
4248 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004249 if (isa<UnreachableInst>(I))
4250 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004251
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004252 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004253 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004254 // Call sites that throw have implicit non-local control flow.
4255 if (!CS.doesNotThrow())
4256 return false;
4257
Johannes Doerfert6ed459f2019-06-27 19:29:48 +00004258 // A function which doens't throw and has "willreturn" attribute will
4259 // always return.
4260 if (CS.hasFnAttr(Attribute::WillReturn))
4261 return true;
4262
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004263 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4264 // etc. and thus not return. However, LLVM already assumes that
4265 //
4266 // - Thread exiting actions are modeled as writes to memory invisible to
4267 // the program.
4268 //
4269 // - Loops that don't have side effects (side effects are volatile/atomic
4270 // stores and IO) always terminate (see http://llvm.org/PR965).
4271 // Furthermore IO itself is also modeled as writes to memory invisible to
4272 // the program.
4273 //
4274 // We rely on those assumptions here, and use the memory effects of the call
4275 // target as a proxy for checking that it always returns.
4276
4277 // FIXME: This isn't aggressive enough; a call which only writes to a global
4278 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00004279 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00004280 match(I, m_Intrinsic<Intrinsic::assume>()) ||
Max Kazantsevb3168a42019-02-14 11:10:21 +00004281 match(I, m_Intrinsic<Intrinsic::sideeffect>()) ||
4282 match(I, m_Intrinsic<Intrinsic::experimental_widenable_condition>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004283 }
4284
4285 // Other instructions return normally.
4286 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004287}
4288
Philip Reamesfbffd122018-03-08 21:25:30 +00004289bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
Hiroshi Inouec437f312019-01-30 05:26:31 +00004290 // TODO: This is slightly conservative for invoke instruction since exiting
Philip Reamesfbffd122018-03-08 21:25:30 +00004291 // via an exception *is* normal control for them.
4292 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4293 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4294 return false;
4295 return true;
4296}
4297
Jingyue Wu42f1d672015-07-28 18:22:40 +00004298bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4299 const Loop *L) {
4300 // The loop header is guaranteed to be executed for every iteration.
4301 //
4302 // FIXME: Relax this constraint to cover all basic blocks that are
4303 // guaranteed to be executed at every iteration.
4304 if (I->getParent() != L->getHeader()) return false;
4305
4306 for (const Instruction &LI : *L->getHeader()) {
4307 if (&LI == I) return true;
4308 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4309 }
4310 llvm_unreachable("Instruction not contained in its own parent basic block.");
4311}
4312
4313bool llvm::propagatesFullPoison(const Instruction *I) {
Nikita Popovad81d422019-06-13 19:45:36 +00004314 // TODO: This should include all instructions apart from phis, selects and
4315 // call-like instructions.
Jingyue Wu42f1d672015-07-28 18:22:40 +00004316 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004317 case Instruction::Add:
4318 case Instruction::Sub:
4319 case Instruction::Xor:
4320 case Instruction::Trunc:
4321 case Instruction::BitCast:
4322 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004323 case Instruction::Mul:
4324 case Instruction::Shl:
4325 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004326 // These operations all propagate poison unconditionally. Note that poison
4327 // is not any particular value, so xor or subtraction of poison with
4328 // itself still yields poison, not zero.
4329 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004330
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004331 case Instruction::AShr:
4332 case Instruction::SExt:
4333 // For these operations, one bit of the input is replicated across
4334 // multiple output bits. A replicated poison bit is still poison.
4335 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004336
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004337 case Instruction::ICmp:
4338 // Comparing poison with any value yields poison. This is why, for
4339 // instance, x s< (x +nsw 1) can be folded to true.
4340 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004341
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004342 default:
4343 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004344 }
4345}
4346
4347const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4348 switch (I->getOpcode()) {
4349 case Instruction::Store:
4350 return cast<StoreInst>(I)->getPointerOperand();
4351
4352 case Instruction::Load:
4353 return cast<LoadInst>(I)->getPointerOperand();
4354
4355 case Instruction::AtomicCmpXchg:
4356 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4357
4358 case Instruction::AtomicRMW:
4359 return cast<AtomicRMWInst>(I)->getPointerOperand();
4360
4361 case Instruction::UDiv:
4362 case Instruction::SDiv:
4363 case Instruction::URem:
4364 case Instruction::SRem:
4365 return I->getOperand(1);
4366
4367 default:
Philip Reames038e01d2019-06-13 19:27:56 +00004368 // Note: It's really tempting to think that a conditional branch or
4369 // switch should be listed here, but that's incorrect. It's not
4370 // branching off of poison which is UB, it is executing a side effecting
Johannes Doerfert3ed286a2019-07-11 01:14:48 +00004371 // instruction which follows the branch.
Jingyue Wu42f1d672015-07-28 18:22:40 +00004372 return nullptr;
4373 }
4374}
4375
Philip Reames4bf1c232019-06-10 20:41:27 +00004376bool llvm::mustTriggerUB(const Instruction *I,
4377 const SmallSet<const Value *, 16>& KnownPoison) {
4378 auto *NotPoison = getGuaranteedNonFullPoisonOp(I);
4379 return (NotPoison && KnownPoison.count(NotPoison));
4380}
4381
4382
Sanjoy Das08989c72017-04-30 19:41:19 +00004383bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004384 // We currently only look for uses of poison values within the same basic
4385 // block, as that makes it easier to guarantee that the uses will be
4386 // executed given that PoisonI is executed.
4387 //
4388 // FIXME: Expand this to consider uses beyond the same basic block. To do
4389 // this, look out for the distinction between post-dominance and strong
4390 // post-dominance.
4391 const BasicBlock *BB = PoisonI->getParent();
4392
4393 // Set of instructions that we have proved will yield poison if PoisonI
4394 // does.
4395 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004396 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004397 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004398 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004399
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004400 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004401
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004402 unsigned Iter = 0;
4403 while (Iter++ < MaxDepth) {
4404 for (auto &I : make_range(Begin, End)) {
4405 if (&I != PoisonI) {
Philip Reames4bf1c232019-06-10 20:41:27 +00004406 if (mustTriggerUB(&I, YieldsPoison))
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004407 return true;
4408 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4409 return false;
4410 }
4411
4412 // Mark poison that propagates from I through uses of I.
4413 if (YieldsPoison.count(&I)) {
4414 for (const User *User : I.users()) {
4415 const Instruction *UserI = cast<Instruction>(User);
4416 if (propagatesFullPoison(UserI))
4417 YieldsPoison.insert(User);
4418 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004419 }
4420 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004421
4422 if (auto *NextBB = BB->getSingleSuccessor()) {
4423 if (Visited.insert(NextBB).second) {
4424 BB = NextBB;
4425 Begin = BB->getFirstNonPHI()->getIterator();
4426 End = BB->end();
4427 continue;
4428 }
4429 }
4430
4431 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004432 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004433 return false;
4434}
4435
Pete Cooper35b00d52016-08-13 01:05:32 +00004436static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004437 if (FMF.noNaNs())
4438 return true;
4439
4440 if (auto *C = dyn_cast<ConstantFP>(V))
4441 return !C->isNaN();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004442
4443 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4444 if (!C->getElementType()->isFloatingPointTy())
4445 return false;
4446 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4447 if (C->getElementAsAPFloat(I).isNaN())
4448 return false;
4449 }
4450 return true;
4451 }
4452
James Molloy134bec22015-08-11 09:12:57 +00004453 return false;
4454}
4455
Pete Cooper35b00d52016-08-13 01:05:32 +00004456static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004457 if (auto *C = dyn_cast<ConstantFP>(V))
4458 return !C->isZero();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004459
4460 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4461 if (!C->getElementType()->isFloatingPointTy())
4462 return false;
4463 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4464 if (C->getElementAsAPFloat(I).isZero())
4465 return false;
4466 }
4467 return true;
4468 }
4469
James Molloy134bec22015-08-11 09:12:57 +00004470 return false;
4471}
4472
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004473/// Match clamp pattern for float types without care about NaNs or signed zeros.
4474/// Given non-min/max outer cmp/select from the clamp pattern this
4475/// function recognizes if it can be substitued by a "canonical" min/max
4476/// pattern.
4477static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4478 Value *CmpLHS, Value *CmpRHS,
4479 Value *TrueVal, Value *FalseVal,
4480 Value *&LHS, Value *&RHS) {
4481 // Try to match
4482 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4483 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4484 // and return description of the outer Max/Min.
4485
4486 // First, check if select has inverse order:
4487 if (CmpRHS == FalseVal) {
4488 std::swap(TrueVal, FalseVal);
4489 Pred = CmpInst::getInversePredicate(Pred);
4490 }
4491
4492 // Assume success now. If there's no match, callers should not use these anyway.
4493 LHS = TrueVal;
4494 RHS = FalseVal;
4495
4496 const APFloat *FC1;
4497 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4498 return {SPF_UNKNOWN, SPNB_NA, false};
4499
4500 const APFloat *FC2;
4501 switch (Pred) {
4502 case CmpInst::FCMP_OLT:
4503 case CmpInst::FCMP_OLE:
4504 case CmpInst::FCMP_ULT:
4505 case CmpInst::FCMP_ULE:
4506 if (match(FalseVal,
4507 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4508 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4509 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4510 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4511 break;
4512 case CmpInst::FCMP_OGT:
4513 case CmpInst::FCMP_OGE:
4514 case CmpInst::FCMP_UGT:
4515 case CmpInst::FCMP_UGE:
4516 if (match(FalseVal,
4517 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4518 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4519 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4520 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4521 break;
4522 default:
4523 break;
4524 }
4525
4526 return {SPF_UNKNOWN, SPNB_NA, false};
4527}
4528
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004529/// Recognize variations of:
4530/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4531static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4532 Value *CmpLHS, Value *CmpRHS,
4533 Value *TrueVal, Value *FalseVal) {
4534 // Swap the select operands and predicate to match the patterns below.
4535 if (CmpRHS != TrueVal) {
4536 Pred = ICmpInst::getSwappedPredicate(Pred);
4537 std::swap(TrueVal, FalseVal);
4538 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004539 const APInt *C1;
4540 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4541 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004542 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4543 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004544 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004545 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004546
4547 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4548 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004549 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004550 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004551
4552 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4553 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004554 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004555 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004556
4557 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4558 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004559 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004560 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004561 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004562 return {SPF_UNKNOWN, SPNB_NA, false};
4563}
4564
Sanjay Patel78114302018-01-02 20:56:45 +00004565/// Recognize variations of:
4566/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4567static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4568 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004569 Value *TVal, Value *FVal,
4570 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004571 // TODO: Allow FP min/max with nnan/nsz.
4572 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4573
4574 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004575 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004576 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4577 return {SPF_UNKNOWN, SPNB_NA, false};
4578
4579 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004580 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004581 if (L.Flavor != R.Flavor)
4582 return {SPF_UNKNOWN, SPNB_NA, false};
4583
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004584 // We have something like: x Pred y ? min(a, b) : min(c, d).
4585 // Try to match the compare to the min/max operations of the select operands.
4586 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004587 switch (L.Flavor) {
4588 case SPF_SMIN:
4589 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4590 Pred = ICmpInst::getSwappedPredicate(Pred);
4591 std::swap(CmpLHS, CmpRHS);
4592 }
4593 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4594 break;
4595 return {SPF_UNKNOWN, SPNB_NA, false};
4596 case SPF_SMAX:
4597 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4598 Pred = ICmpInst::getSwappedPredicate(Pred);
4599 std::swap(CmpLHS, CmpRHS);
4600 }
4601 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4602 break;
4603 return {SPF_UNKNOWN, SPNB_NA, false};
4604 case SPF_UMIN:
4605 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4606 Pred = ICmpInst::getSwappedPredicate(Pred);
4607 std::swap(CmpLHS, CmpRHS);
4608 }
4609 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4610 break;
4611 return {SPF_UNKNOWN, SPNB_NA, false};
4612 case SPF_UMAX:
4613 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4614 Pred = ICmpInst::getSwappedPredicate(Pred);
4615 std::swap(CmpLHS, CmpRHS);
4616 }
4617 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4618 break;
4619 return {SPF_UNKNOWN, SPNB_NA, false};
4620 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004621 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004622 }
4623
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004624 // If there is a common operand in the already matched min/max and the other
4625 // min/max operands match the compare operands (either directly or inverted),
4626 // then this is min/max of the same flavor.
4627
Sanjay Patel78114302018-01-02 20:56:45 +00004628 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004629 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4630 if (D == B) {
4631 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4632 match(A, m_Not(m_Specific(CmpRHS)))))
4633 return {L.Flavor, SPNB_NA, false};
4634 }
Sanjay Patel78114302018-01-02 20:56:45 +00004635 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004636 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4637 if (C == B) {
4638 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4639 match(A, m_Not(m_Specific(CmpRHS)))))
4640 return {L.Flavor, SPNB_NA, false};
4641 }
Sanjay Patel78114302018-01-02 20:56:45 +00004642 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004643 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4644 if (D == A) {
4645 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4646 match(B, m_Not(m_Specific(CmpRHS)))))
4647 return {L.Flavor, SPNB_NA, false};
4648 }
Sanjay Patel78114302018-01-02 20:56:45 +00004649 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004650 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4651 if (C == A) {
4652 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4653 match(B, m_Not(m_Specific(CmpRHS)))))
4654 return {L.Flavor, SPNB_NA, false};
4655 }
Sanjay Patel78114302018-01-02 20:56:45 +00004656
4657 return {SPF_UNKNOWN, SPNB_NA, false};
4658}
4659
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004660/// Match non-obvious integer minimum and maximum sequences.
4661static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4662 Value *CmpLHS, Value *CmpRHS,
4663 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004664 Value *&LHS, Value *&RHS,
4665 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004666 // Assume success. If there's no match, callers should not use these anyway.
4667 LHS = TrueVal;
4668 RHS = FalseVal;
4669
4670 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4671 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4672 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004673
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004674 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004675 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4676 return SPR;
Fangrui Songf78650a2018-07-30 19:41:25 +00004677
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004678 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004679 return {SPF_UNKNOWN, SPNB_NA, false};
4680
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004681 // Z = X -nsw Y
4682 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4683 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4684 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004685 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004686 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004687
4688 // Z = X -nsw Y
4689 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4690 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4691 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004692 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004693 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004694
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004695 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004696 if (!match(CmpRHS, m_APInt(C1)))
4697 return {SPF_UNKNOWN, SPNB_NA, false};
4698
4699 // An unsigned min/max can be written with a signed compare.
4700 const APInt *C2;
4701 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4702 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4703 // Is the sign bit set?
4704 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4705 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004706 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4707 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004708 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004709
4710 // Is the sign bit clear?
4711 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4712 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004713 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4714 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004715 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004716 }
4717
4718 // Look through 'not' ops to find disguised signed min/max.
4719 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4720 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4721 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004722 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004723 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004724
4725 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4726 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4727 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004728 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004729 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004730
4731 return {SPF_UNKNOWN, SPNB_NA, false};
4732}
4733
Chen Zheng69bb0642018-07-21 12:27:54 +00004734bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004735 assert(X && Y && "Invalid operand");
4736
Chen Zheng69bb0642018-07-21 12:27:54 +00004737 // X = sub (0, Y) || X = sub nsw (0, Y)
4738 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4739 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004740 return true;
4741
Chen Zheng69bb0642018-07-21 12:27:54 +00004742 // Y = sub (0, X) || Y = sub nsw (0, X)
4743 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4744 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004745 return true;
4746
Chen Zheng69bb0642018-07-21 12:27:54 +00004747 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004748 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004749 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4750 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4751 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4752 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004753}
4754
James Molloy134bec22015-08-11 09:12:57 +00004755static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4756 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004757 Value *CmpLHS, Value *CmpRHS,
4758 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004759 Value *&LHS, Value *&RHS,
4760 unsigned Depth) {
Sanjay Patele7c94ef2018-11-04 14:28:48 +00004761 if (CmpInst::isFPPredicate(Pred)) {
4762 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4763 // 0.0 operand, set the compare's 0.0 operands to that same value for the
4764 // purpose of identifying min/max. Disregard vector constants with undefined
4765 // elements because those can not be back-propagated for analysis.
4766 Value *OutputZeroVal = nullptr;
4767 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4768 !cast<Constant>(TrueVal)->containsUndefElement())
4769 OutputZeroVal = TrueVal;
4770 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4771 !cast<Constant>(FalseVal)->containsUndefElement())
4772 OutputZeroVal = FalseVal;
4773
4774 if (OutputZeroVal) {
4775 if (match(CmpLHS, m_AnyZeroFP()))
4776 CmpLHS = OutputZeroVal;
4777 if (match(CmpRHS, m_AnyZeroFP()))
4778 CmpRHS = OutputZeroVal;
4779 }
4780 }
4781
James Molloy71b91c22015-05-11 14:42:20 +00004782 LHS = CmpLHS;
4783 RHS = CmpRHS;
4784
Sanjay Patel9a399792017-12-26 15:09:19 +00004785 // Signed zero may return inconsistent results between implementations.
4786 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4787 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4788 // Therefore, we behave conservatively and only proceed if at least one of the
4789 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004790 switch (Pred) {
4791 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004792 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004793 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4794 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4795 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4796 !isKnownNonZero(CmpRHS))
4797 return {SPF_UNKNOWN, SPNB_NA, false};
4798 }
4799
4800 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4801 bool Ordered = false;
4802
4803 // When given one NaN and one non-NaN input:
4804 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4805 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4806 // ordered comparison fails), which could be NaN or non-NaN.
4807 // so here we discover exactly what NaN behavior is required/accepted.
4808 if (CmpInst::isFPPredicate(Pred)) {
4809 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4810 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4811
4812 if (LHSSafe && RHSSafe) {
4813 // Both operands are known non-NaN.
4814 NaNBehavior = SPNB_RETURNS_ANY;
4815 } else if (CmpInst::isOrdered(Pred)) {
4816 // An ordered comparison will return false when given a NaN, so it
4817 // returns the RHS.
4818 Ordered = true;
4819 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004820 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004821 NaNBehavior = SPNB_RETURNS_NAN;
4822 else if (RHSSafe)
4823 NaNBehavior = SPNB_RETURNS_OTHER;
4824 else
4825 // Completely unsafe.
4826 return {SPF_UNKNOWN, SPNB_NA, false};
4827 } else {
4828 Ordered = false;
4829 // An unordered comparison will return true when given a NaN, so it
4830 // returns the LHS.
4831 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004832 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004833 NaNBehavior = SPNB_RETURNS_OTHER;
4834 else if (RHSSafe)
4835 NaNBehavior = SPNB_RETURNS_NAN;
4836 else
4837 // Completely unsafe.
4838 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004839 }
4840 }
4841
James Molloy71b91c22015-05-11 14:42:20 +00004842 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004843 std::swap(CmpLHS, CmpRHS);
4844 Pred = CmpInst::getSwappedPredicate(Pred);
4845 if (NaNBehavior == SPNB_RETURNS_NAN)
4846 NaNBehavior = SPNB_RETURNS_OTHER;
4847 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4848 NaNBehavior = SPNB_RETURNS_NAN;
4849 Ordered = !Ordered;
4850 }
4851
4852 // ([if]cmp X, Y) ? X : Y
4853 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004854 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004855 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004856 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004857 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004858 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004859 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004860 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004861 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004862 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004863 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4864 case FCmpInst::FCMP_UGT:
4865 case FCmpInst::FCMP_UGE:
4866 case FCmpInst::FCMP_OGT:
4867 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4868 case FCmpInst::FCMP_ULT:
4869 case FCmpInst::FCMP_ULE:
4870 case FCmpInst::FCMP_OLT:
4871 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004872 }
4873 }
Fangrui Songf78650a2018-07-30 19:41:25 +00004874
Chen Zhengccc84222018-07-16 02:23:00 +00004875 if (isKnownNegation(TrueVal, FalseVal)) {
4876 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4877 // match against either LHS or sext(LHS).
4878 auto MaybeSExtCmpLHS =
4879 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4880 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4881 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4882 if (match(TrueVal, MaybeSExtCmpLHS)) {
4883 // Set the return values. If the compare uses the negated value (-X >s 0),
4884 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004885 LHS = TrueVal;
4886 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004887 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4888 std::swap(LHS, RHS);
4889
4890 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4891 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4892 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4893 return {SPF_ABS, SPNB_NA, false};
4894
Simon Pilgrima56f2822019-03-19 16:24:55 +00004895 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
4896 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
4897 return {SPF_ABS, SPNB_NA, false};
4898
Chen Zhengccc84222018-07-16 02:23:00 +00004899 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4900 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4901 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4902 return {SPF_NABS, SPNB_NA, false};
4903 }
4904 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4905 // Set the return values. If the compare uses the negated value (-X >s 0),
4906 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004907 LHS = FalseVal;
4908 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004909 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4910 std::swap(LHS, RHS);
4911
4912 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4913 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4914 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4915 return {SPF_NABS, SPNB_NA, false};
4916
4917 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4918 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4919 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4920 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004921 }
James Molloy71b91c22015-05-11 14:42:20 +00004922 }
4923
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004924 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004925 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004926
4927 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4928 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4929 // semantics than minNum. Be conservative in such case.
4930 if (NaNBehavior != SPNB_RETURNS_ANY ||
4931 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4932 !isKnownNonZero(CmpRHS)))
4933 return {SPF_UNKNOWN, SPNB_NA, false};
4934
4935 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004936}
James Molloy270ef8c2015-05-15 16:04:50 +00004937
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004938/// Helps to match a select pattern in case of a type mismatch.
4939///
4940/// The function processes the case when type of true and false values of a
4941/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004942/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004943/// operation after "select". If yes, it returns the new second value of
4944/// "select" (with the assumption that cast is moved):
4945/// 1. As operand of cast instruction when both values of "select" are same cast
4946/// instructions.
4947/// 2. As restored constant (by applying reverse cast operation) when the first
4948/// value of the "select" is a cast operation and the second value is a
4949/// constant.
4950/// NOTE: We return only the new second value because the first value could be
4951/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004952static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4953 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004954 auto *Cast1 = dyn_cast<CastInst>(V1);
4955 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004956 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004957
Sanjay Patel14a4b812017-01-29 16:34:57 +00004958 *CastOp = Cast1->getOpcode();
4959 Type *SrcTy = Cast1->getSrcTy();
4960 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4961 // If V1 and V2 are both the same cast from the same type, look through V1.
4962 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4963 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004964 return nullptr;
4965 }
4966
Sanjay Patel14a4b812017-01-29 16:34:57 +00004967 auto *C = dyn_cast<Constant>(V2);
4968 if (!C)
4969 return nullptr;
4970
David Majnemerd2a074b2016-04-29 18:40:34 +00004971 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004972 switch (*CastOp) {
4973 case Instruction::ZExt:
4974 if (CmpI->isUnsigned())
4975 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4976 break;
4977 case Instruction::SExt:
4978 if (CmpI->isSigned())
4979 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4980 break;
4981 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004982 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004983 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4984 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004985 // Here we have the following case:
4986 //
4987 // %cond = cmp iN %x, CmpConst
4988 // %tr = trunc iN %x to iK
4989 // %narrowsel = select i1 %cond, iK %t, iK C
4990 //
4991 // We can always move trunc after select operation:
4992 //
4993 // %cond = cmp iN %x, CmpConst
4994 // %widesel = select i1 %cond, iN %x, iN CmpConst
4995 // %tr = trunc iN %widesel to iK
4996 //
4997 // Note that C could be extended in any way because we don't care about
4998 // upper bits after truncation. It can't be abs pattern, because it would
4999 // look like:
5000 //
5001 // select i1 %cond, x, -x.
5002 //
5003 // So only min/max pattern could be matched. Such match requires widened C
5004 // == CmpConst. That is why set widened C = CmpConst, condition trunc
5005 // CmpConst == C is checked below.
5006 CastedTo = CmpConst;
5007 } else {
5008 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
5009 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00005010 break;
5011 case Instruction::FPTrunc:
5012 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
5013 break;
5014 case Instruction::FPExt:
5015 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5016 break;
5017 case Instruction::FPToUI:
5018 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5019 break;
5020 case Instruction::FPToSI:
5021 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5022 break;
5023 case Instruction::UIToFP:
5024 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5025 break;
5026 case Instruction::SIToFP:
5027 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5028 break;
5029 default:
5030 break;
5031 }
David Majnemerd2a074b2016-04-29 18:40:34 +00005032
5033 if (!CastedTo)
5034 return nullptr;
5035
David Majnemerd2a074b2016-04-29 18:40:34 +00005036 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00005037 Constant *CastedBack =
5038 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00005039 if (CastedBack != C)
5040 return nullptr;
5041
5042 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00005043}
5044
Sanjay Patele8dc0902016-05-23 17:57:54 +00005045SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005046 Instruction::CastOps *CastOp,
5047 unsigned Depth) {
5048 if (Depth >= MaxDepth)
5049 return {SPF_UNKNOWN, SPNB_NA, false};
5050
James Molloy270ef8c2015-05-15 16:04:50 +00005051 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00005052 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005053
James Molloy134bec22015-08-11 09:12:57 +00005054 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5055 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005056
Joseph Tremoulet3bc6e2a2019-06-13 15:24:11 +00005057 Value *TrueVal = SI->getTrueValue();
5058 Value *FalseVal = SI->getFalseValue();
5059
5060 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
5061 CastOp, Depth);
5062}
5063
5064SelectPatternResult llvm::matchDecomposedSelectPattern(
5065 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
5066 Instruction::CastOps *CastOp, unsigned Depth) {
James Molloy134bec22015-08-11 09:12:57 +00005067 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00005068 Value *CmpLHS = CmpI->getOperand(0);
5069 Value *CmpRHS = CmpI->getOperand(1);
James Molloy134bec22015-08-11 09:12:57 +00005070 FastMathFlags FMF;
5071 if (isa<FPMathOperator>(CmpI))
5072 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00005073
5074 // Bail out early.
5075 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00005076 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005077
5078 // Deal with type mismatches.
5079 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00005080 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5081 // If this is a potential fmin/fmax with a cast to integer, then ignore
5082 // -0.0 because there is no corresponding integer value.
5083 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5084 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005085 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005086 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005087 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005088 }
5089 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5090 // If this is a potential fmin/fmax with a cast to integer, then ignore
5091 // -0.0 because there is no corresponding integer value.
5092 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5093 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005094 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005095 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005096 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005097 }
James Molloy270ef8c2015-05-15 16:04:50 +00005098 }
James Molloy134bec22015-08-11 09:12:57 +00005099 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005100 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00005101}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00005102
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00005103CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5104 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5105 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5106 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5107 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5108 if (SPF == SPF_FMINNUM)
5109 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5110 if (SPF == SPF_FMAXNUM)
5111 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5112 llvm_unreachable("unhandled!");
5113}
5114
5115SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5116 if (SPF == SPF_SMIN) return SPF_SMAX;
5117 if (SPF == SPF_UMIN) return SPF_UMAX;
5118 if (SPF == SPF_SMAX) return SPF_SMIN;
5119 if (SPF == SPF_UMAX) return SPF_UMIN;
5120 llvm_unreachable("unhandled!");
5121}
5122
5123CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5124 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5125}
5126
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005127/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00005128static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5129 const Value *RHS, const DataLayout &DL,
5130 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005131 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005132 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5133 return true;
5134
5135 switch (Pred) {
5136 default:
5137 return false;
5138
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005139 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005140 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005141
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005142 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005143 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005144 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005145 return false;
5146 }
5147
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005148 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005149 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005150
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005151 // LHS u<= LHS +_{nuw} C for any C
5152 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00005153 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00005154
5155 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00005156 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5157 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00005158 const APInt *&CA, const APInt *&CB) {
5159 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5160 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5161 return true;
5162
5163 // If X & C == 0 then (X | C) == X +_{nuw} C
5164 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5165 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00005166 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00005167 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5168 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00005169 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00005170 return true;
5171 }
5172
5173 return false;
5174 };
5175
Pete Cooper35b00d52016-08-13 01:05:32 +00005176 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00005177 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005178 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5179 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00005180
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005181 return false;
5182 }
5183 }
5184}
5185
5186/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00005187/// ALHS ARHS" is true. Otherwise, return None.
5188static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005189isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00005190 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5191 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005192 switch (Pred) {
5193 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00005194 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005195
5196 case CmpInst::ICMP_SLT:
5197 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005198 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5199 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005200 return true;
5201 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005202
5203 case CmpInst::ICMP_ULT:
5204 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005205 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5206 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005207 return true;
5208 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005209 }
5210}
5211
Chad Rosier226a7342016-05-05 17:41:19 +00005212/// Return true if the operands of the two compares match. IsSwappedOps is true
5213/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00005214static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5215 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005216 bool &IsSwappedOps) {
5217
5218 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5219 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5220 return IsMatchingOps || IsSwappedOps;
5221}
5222
Sanjay Patel798c5982018-12-19 16:49:18 +00005223/// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
5224/// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
5225/// Otherwise, return None if we can't infer anything.
Chad Rosier41dd31f2016-04-20 19:15:26 +00005226static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Chad Rosier41dd31f2016-04-20 19:15:26 +00005227 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005228 bool AreSwappedOps) {
5229 // Canonicalize the predicate as if the operands were not commuted.
5230 if (AreSwappedOps)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005231 BPred = ICmpInst::getSwappedPredicate(BPred);
Sanjay Patel798c5982018-12-19 16:49:18 +00005232
Chad Rosier99bc4802016-04-21 16:18:02 +00005233 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005234 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00005235 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005236 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005237
Chad Rosier41dd31f2016-04-20 19:15:26 +00005238 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005239}
5240
Sanjay Patel798c5982018-12-19 16:49:18 +00005241/// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
5242/// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
5243/// Otherwise, return None if we can't infer anything.
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005244static Optional<bool>
Sanjay Patel798c5982018-12-19 16:49:18 +00005245isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005246 const ConstantInt *C1,
5247 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005248 const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005249 ConstantRange DomCR =
5250 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5251 ConstantRange CR =
5252 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5253 ConstantRange Intersection = DomCR.intersectWith(CR);
5254 ConstantRange Difference = DomCR.difference(CR);
5255 if (Intersection.isEmptySet())
5256 return false;
5257 if (Difference.isEmptySet())
5258 return true;
5259 return None;
5260}
5261
Chad Rosier2f498032017-07-28 18:47:43 +00005262/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5263/// false. Otherwise, return None if we can't infer anything.
5264static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5265 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005266 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005267 unsigned Depth) {
5268 Value *ALHS = LHS->getOperand(0);
5269 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005270 // The rest of the logic assumes the LHS condition is true. If that's not the
5271 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005272 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005273 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005274
5275 Value *BLHS = RHS->getOperand(0);
5276 Value *BRHS = RHS->getOperand(1);
5277 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005278
Chad Rosier226a7342016-05-05 17:41:19 +00005279 // Can we infer anything when the two compares have matching operands?
Sanjay Patel798c5982018-12-19 16:49:18 +00005280 bool AreSwappedOps;
5281 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
Chad Rosier226a7342016-05-05 17:41:19 +00005282 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005283 APred, BPred, AreSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005284 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005285 // No amount of additional analysis will infer the second condition, so
5286 // early exit.
5287 return None;
5288 }
5289
5290 // Can we infer anything when the LHS operands match and the RHS operands are
5291 // constants (not necessarily matching)?
5292 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5293 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005294 APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
Chad Rosier226a7342016-05-05 17:41:19 +00005295 return Implication;
5296 // No amount of additional analysis will infer the second condition, so
5297 // early exit.
5298 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005299 }
5300
Chad Rosier41dd31f2016-04-20 19:15:26 +00005301 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005302 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005303 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005304}
Chad Rosier2f498032017-07-28 18:47:43 +00005305
Chad Rosierf73a10d2017-08-01 19:22:36 +00005306/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5307/// false. Otherwise, return None if we can't infer anything. We expect the
5308/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5309static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5310 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005311 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005312 unsigned Depth) {
5313 // The LHS must be an 'or' or an 'and' instruction.
5314 assert((LHS->getOpcode() == Instruction::And ||
5315 LHS->getOpcode() == Instruction::Or) &&
5316 "Expected LHS to be 'and' or 'or'.");
5317
Davide Italiano1a943a92017-08-09 16:06:54 +00005318 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005319
5320 // If the result of an 'or' is false, then we know both legs of the 'or' are
5321 // false. Similarly, if the result of an 'and' is true, then we know both
5322 // legs of the 'and' are true.
5323 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005324 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5325 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005326 // FIXME: Make this non-recursion.
5327 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005328 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005329 return Implication;
5330 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005331 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005332 return Implication;
5333 return None;
5334 }
5335 return None;
5336}
5337
Chad Rosier2f498032017-07-28 18:47:43 +00005338Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005339 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005340 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005341 // Bail out when we hit the limit.
5342 if (Depth == MaxDepth)
5343 return None;
5344
Chad Rosierf73a10d2017-08-01 19:22:36 +00005345 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5346 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005347 if (LHS->getType() != RHS->getType())
5348 return None;
5349
5350 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005351 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005352
5353 // LHS ==> RHS by definition
5354 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005355 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005356
Chad Rosierf73a10d2017-08-01 19:22:36 +00005357 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005358 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005359 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005360
Chad Rosier2f498032017-07-28 18:47:43 +00005361 assert(OpTy->isIntegerTy(1) && "implied by above");
5362
Chad Rosier2f498032017-07-28 18:47:43 +00005363 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005364 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5365 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5366 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005367 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005368
Chad Rosierf73a10d2017-08-01 19:22:36 +00005369 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5370 // an icmp. FIXME: Add support for and/or on the RHS.
5371 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5372 if (LHSBO && RHSCmp) {
5373 if ((LHSBO->getOpcode() == Instruction::And ||
5374 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005375 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005376 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005377 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005378}
Sanjay Patel7d82d372018-12-02 13:26:03 +00005379
5380Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
5381 const Instruction *ContextI,
5382 const DataLayout &DL) {
5383 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
5384 if (!ContextI || !ContextI->getParent())
5385 return None;
5386
5387 // TODO: This is a poor/cheap way to determine dominance. Should we use a
5388 // dominator tree (eg, from a SimplifyQuery) instead?
5389 const BasicBlock *ContextBB = ContextI->getParent();
5390 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
5391 if (!PredBB)
5392 return None;
5393
5394 // We need a conditional branch in the predecessor.
5395 Value *PredCond;
5396 BasicBlock *TrueBB, *FalseBB;
5397 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
5398 return None;
5399
5400 // The branch should get simplified. Don't bother simplifying this condition.
5401 if (TrueBB == FalseBB)
5402 return None;
5403
5404 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
5405 "Predecessor block does not point to successor?");
5406
5407 // Is this condition implied by the predecessor condition?
5408 bool CondIsTrue = TrueBB == ContextBB;
5409 return isImpliedCondition(PredCond, Cond, DL, CondIsTrue);
5410}
Nikita Popov49097592019-03-09 21:17:42 +00005411
5412static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
5413 APInt &Upper, const InstrInfoQuery &IIQ) {
5414 unsigned Width = Lower.getBitWidth();
5415 const APInt *C;
5416 switch (BO.getOpcode()) {
5417 case Instruction::Add:
5418 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5419 // FIXME: If we have both nuw and nsw, we should reduce the range further.
5420 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5421 // 'add nuw x, C' produces [C, UINT_MAX].
5422 Lower = *C;
5423 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5424 if (C->isNegative()) {
5425 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
5426 Lower = APInt::getSignedMinValue(Width);
5427 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5428 } else {
5429 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
5430 Lower = APInt::getSignedMinValue(Width) + *C;
5431 Upper = APInt::getSignedMaxValue(Width) + 1;
5432 }
5433 }
5434 }
5435 break;
5436
5437 case Instruction::And:
5438 if (match(BO.getOperand(1), m_APInt(C)))
5439 // 'and x, C' produces [0, C].
5440 Upper = *C + 1;
5441 break;
5442
5443 case Instruction::Or:
5444 if (match(BO.getOperand(1), m_APInt(C)))
5445 // 'or x, C' produces [C, UINT_MAX].
5446 Lower = *C;
5447 break;
5448
5449 case Instruction::AShr:
5450 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5451 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
5452 Lower = APInt::getSignedMinValue(Width).ashr(*C);
5453 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
5454 } else if (match(BO.getOperand(0), m_APInt(C))) {
5455 unsigned ShiftAmount = Width - 1;
5456 if (!C->isNullValue() && IIQ.isExact(&BO))
5457 ShiftAmount = C->countTrailingZeros();
5458 if (C->isNegative()) {
5459 // 'ashr C, x' produces [C, C >> (Width-1)]
5460 Lower = *C;
5461 Upper = C->ashr(ShiftAmount) + 1;
5462 } else {
5463 // 'ashr C, x' produces [C >> (Width-1), C]
5464 Lower = C->ashr(ShiftAmount);
5465 Upper = *C + 1;
5466 }
5467 }
5468 break;
5469
5470 case Instruction::LShr:
5471 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5472 // 'lshr x, C' produces [0, UINT_MAX >> C].
5473 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
5474 } else if (match(BO.getOperand(0), m_APInt(C))) {
5475 // 'lshr C, x' produces [C >> (Width-1), C].
5476 unsigned ShiftAmount = Width - 1;
5477 if (!C->isNullValue() && IIQ.isExact(&BO))
5478 ShiftAmount = C->countTrailingZeros();
5479 Lower = C->lshr(ShiftAmount);
5480 Upper = *C + 1;
5481 }
5482 break;
5483
5484 case Instruction::Shl:
5485 if (match(BO.getOperand(0), m_APInt(C))) {
5486 if (IIQ.hasNoUnsignedWrap(&BO)) {
5487 // 'shl nuw C, x' produces [C, C << CLZ(C)]
5488 Lower = *C;
5489 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
5490 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
5491 if (C->isNegative()) {
5492 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
5493 unsigned ShiftAmount = C->countLeadingOnes() - 1;
5494 Lower = C->shl(ShiftAmount);
5495 Upper = *C + 1;
5496 } else {
5497 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
5498 unsigned ShiftAmount = C->countLeadingZeros() - 1;
5499 Lower = *C;
5500 Upper = C->shl(ShiftAmount) + 1;
5501 }
5502 }
5503 }
5504 break;
5505
5506 case Instruction::SDiv:
5507 if (match(BO.getOperand(1), m_APInt(C))) {
5508 APInt IntMin = APInt::getSignedMinValue(Width);
5509 APInt IntMax = APInt::getSignedMaxValue(Width);
5510 if (C->isAllOnesValue()) {
5511 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
5512 // where C != -1 and C != 0 and C != 1
5513 Lower = IntMin + 1;
5514 Upper = IntMax + 1;
5515 } else if (C->countLeadingZeros() < Width - 1) {
5516 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
5517 // where C != -1 and C != 0 and C != 1
5518 Lower = IntMin.sdiv(*C);
5519 Upper = IntMax.sdiv(*C);
5520 if (Lower.sgt(Upper))
5521 std::swap(Lower, Upper);
5522 Upper = Upper + 1;
5523 assert(Upper != Lower && "Upper part of range has wrapped!");
5524 }
5525 } else if (match(BO.getOperand(0), m_APInt(C))) {
5526 if (C->isMinSignedValue()) {
5527 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
5528 Lower = *C;
5529 Upper = Lower.lshr(1) + 1;
5530 } else {
5531 // 'sdiv C, x' produces [-|C|, |C|].
5532 Upper = C->abs() + 1;
5533 Lower = (-Upper) + 1;
5534 }
5535 }
5536 break;
5537
5538 case Instruction::UDiv:
5539 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5540 // 'udiv x, C' produces [0, UINT_MAX / C].
5541 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
5542 } else if (match(BO.getOperand(0), m_APInt(C))) {
5543 // 'udiv C, x' produces [0, C].
5544 Upper = *C + 1;
5545 }
5546 break;
5547
5548 case Instruction::SRem:
5549 if (match(BO.getOperand(1), m_APInt(C))) {
5550 // 'srem x, C' produces (-|C|, |C|).
5551 Upper = C->abs();
5552 Lower = (-Upper) + 1;
5553 }
5554 break;
5555
5556 case Instruction::URem:
5557 if (match(BO.getOperand(1), m_APInt(C)))
5558 // 'urem x, C' produces [0, C).
5559 Upper = *C;
5560 break;
5561
5562 default:
5563 break;
5564 }
5565}
5566
5567static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
5568 APInt &Upper) {
5569 unsigned Width = Lower.getBitWidth();
5570 const APInt *C;
5571 switch (II.getIntrinsicID()) {
5572 case Intrinsic::uadd_sat:
5573 // uadd.sat(x, C) produces [C, UINT_MAX].
5574 if (match(II.getOperand(0), m_APInt(C)) ||
5575 match(II.getOperand(1), m_APInt(C)))
5576 Lower = *C;
5577 break;
5578 case Intrinsic::sadd_sat:
5579 if (match(II.getOperand(0), m_APInt(C)) ||
5580 match(II.getOperand(1), m_APInt(C))) {
5581 if (C->isNegative()) {
5582 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
5583 Lower = APInt::getSignedMinValue(Width);
5584 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5585 } else {
5586 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
5587 Lower = APInt::getSignedMinValue(Width) + *C;
5588 Upper = APInt::getSignedMaxValue(Width) + 1;
5589 }
5590 }
5591 break;
5592 case Intrinsic::usub_sat:
5593 // usub.sat(C, x) produces [0, C].
5594 if (match(II.getOperand(0), m_APInt(C)))
5595 Upper = *C + 1;
5596 // usub.sat(x, C) produces [0, UINT_MAX - C].
5597 else if (match(II.getOperand(1), m_APInt(C)))
5598 Upper = APInt::getMaxValue(Width) - *C + 1;
5599 break;
5600 case Intrinsic::ssub_sat:
5601 if (match(II.getOperand(0), m_APInt(C))) {
5602 if (C->isNegative()) {
5603 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
5604 Lower = APInt::getSignedMinValue(Width);
5605 Upper = *C - APInt::getSignedMinValue(Width) + 1;
5606 } else {
5607 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
5608 Lower = *C - APInt::getSignedMaxValue(Width);
5609 Upper = APInt::getSignedMaxValue(Width) + 1;
5610 }
5611 } else if (match(II.getOperand(1), m_APInt(C))) {
5612 if (C->isNegative()) {
5613 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
5614 Lower = APInt::getSignedMinValue(Width) - *C;
5615 Upper = APInt::getSignedMaxValue(Width) + 1;
5616 } else {
5617 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
5618 Lower = APInt::getSignedMinValue(Width);
5619 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
5620 }
5621 }
5622 break;
5623 default:
5624 break;
5625 }
5626}
5627
Nikita Popovf89343b2019-03-18 21:20:03 +00005628static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
5629 APInt &Upper) {
5630 const Value *LHS, *RHS;
5631 SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
5632 if (R.Flavor == SPF_UNKNOWN)
5633 return;
5634
5635 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5636
Nikita Popov00b5eca2019-03-20 18:16:02 +00005637 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
5638 // If the negation part of the abs (in RHS) has the NSW flag,
5639 // then the result of abs(X) is [0..SIGNED_MAX],
5640 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
Nikita Popovf89343b2019-03-18 21:20:03 +00005641 Lower = APInt::getNullValue(BitWidth);
Nikita Popov00b5eca2019-03-20 18:16:02 +00005642 if (cast<Instruction>(RHS)->hasNoSignedWrap())
5643 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5644 else
5645 Upper = APInt::getSignedMinValue(BitWidth) + 1;
Nikita Popovf89343b2019-03-18 21:20:03 +00005646 return;
5647 }
5648
5649 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
5650 // The result of -abs(X) is <= 0.
5651 Lower = APInt::getSignedMinValue(BitWidth);
5652 Upper = APInt(BitWidth, 1);
5653 return;
5654 }
5655
Nikita Popov3db93ac2019-04-07 17:22:16 +00005656 const APInt *C;
5657 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
5658 return;
5659
5660 switch (R.Flavor) {
5661 case SPF_UMIN:
5662 Upper = *C + 1;
5663 break;
5664 case SPF_UMAX:
5665 Lower = *C;
5666 break;
5667 case SPF_SMIN:
5668 Lower = APInt::getSignedMinValue(BitWidth);
5669 Upper = *C + 1;
5670 break;
5671 case SPF_SMAX:
5672 Lower = *C;
5673 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5674 break;
5675 default:
5676 break;
5677 }
Nikita Popovf89343b2019-03-18 21:20:03 +00005678}
5679
Nikita Popov49097592019-03-09 21:17:42 +00005680ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo) {
5681 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
5682
Nikita Popov20838192019-03-19 17:53:56 +00005683 const APInt *C;
5684 if (match(V, m_APInt(C)))
5685 return ConstantRange(*C);
5686
Nikita Popov49097592019-03-09 21:17:42 +00005687 InstrInfoQuery IIQ(UseInstrInfo);
5688 unsigned BitWidth = V->getType()->getScalarSizeInBits();
5689 APInt Lower = APInt(BitWidth, 0);
5690 APInt Upper = APInt(BitWidth, 0);
5691 if (auto *BO = dyn_cast<BinaryOperator>(V))
5692 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
5693 else if (auto *II = dyn_cast<IntrinsicInst>(V))
5694 setLimitsForIntrinsic(*II, Lower, Upper);
Nikita Popovf89343b2019-03-18 21:20:03 +00005695 else if (auto *SI = dyn_cast<SelectInst>(V))
5696 setLimitsForSelectPattern(*SI, Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005697
Nikita Popovdbc3fba2019-04-21 15:22:54 +00005698 ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005699
5700 if (auto *I = dyn_cast<Instruction>(V))
5701 if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
5702 CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
5703
5704 return CR;
5705}