blob: e1326548f851e7e3781006e067e2ebb0525fb4e4 [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"
41#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000042#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000046#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/Type.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000067#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000068#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000069#include <algorithm>
70#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000071#include <cassert>
72#include <cstdint>
73#include <iterator>
Fangrui Songf78650a2018-07-30 19:41:25 +000074#include <utility>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000075
Chris Lattner965c7692008-06-02 01:18:21 +000076using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000077using namespace llvm::PatternMatch;
78
79const unsigned MaxDepth = 6;
80
Philip Reames1c292272015-03-10 22:43:20 +000081// Controls the number of uses of the value searched for possible
82// dominating comparisons.
83static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000084 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000085
Craig Topper6b3940a2017-05-03 22:25:19 +000086/// Returns the bitwidth of the given scalar or pointer type. For vector types,
87/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000089 if (unsigned BitWidth = Ty->getScalarSizeInBits())
90 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000091
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000092 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000093}
Chris Lattner965c7692008-06-02 01:18:21 +000094
Benjamin Kramercfd8d902014-09-12 08:56:53 +000095namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000096
Hal Finkel60db0582014-09-07 18:57:58 +000097// Simplifying using an assume can only be done in a particular control-flow
98// context (the context instruction provides that context). If an assume and
99// the context instruction are not in the same block then the DT helps in
100// figuring out if we can use it.
101struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000102 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000103 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000104 const Instruction *CxtI;
105 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000106
Sanjay Patel54656ca2017-02-06 18:26:06 +0000107 // Unlike the other analyses, this may be a nullptr because not all clients
108 // provide it currently.
109 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000110
Matthias Braun37e5d792016-01-28 06:29:33 +0000111 /// Set of assumptions that should be excluded from further queries.
112 /// This is because of the potential for mutual recursion to cause
113 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
114 /// classic case of this is assume(x = y), which will attempt to determine
115 /// bits in x from bits in y, which will attempt to determine bits in y from
116 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000117 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
118 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000119 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000120
Florian Hahn19f9e322018-08-17 14:39:04 +0000121 /// If true, it is safe to use metadata during simplification.
122 InstrInfoQuery IIQ;
123
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000124 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000125
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000126 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000127 const DominatorTree *DT, bool UseInstrInfo,
128 OptimizationRemarkEmitter *ORE = nullptr)
129 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000130
131 Query(const Query &Q, const Value *NewExcl)
Florian Hahn19f9e322018-08-17 14:39:04 +0000132 : 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 +0000133 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000134 Excluded = Q.Excluded;
135 Excluded[NumExcluded++] = NewExcl;
136 assert(NumExcluded <= Excluded.size());
137 }
138
139 bool isExcluded(const Value *Value) const {
140 if (NumExcluded == 0)
141 return false;
142 auto End = Excluded.begin() + NumExcluded;
143 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000144 }
145};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000146
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000147} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000148
Sanjay Patel547e9752014-11-04 16:09:50 +0000149// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000150// the preferred context instruction (if any).
151static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
152 // If we've been provided with a context instruction, then use that (provided
153 // it has been inserted).
154 if (CxtI && CxtI->getParent())
155 return CxtI;
156
157 // If the value is really an already-inserted instruction, then use that.
158 CxtI = dyn_cast<Instruction>(V);
159 if (CxtI && CxtI->getParent())
160 return CxtI;
161
162 return nullptr;
163}
164
Craig Topperb45eabc2017-04-26 16:39:58 +0000165static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000166 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000167
Craig Topperb45eabc2017-04-26 16:39:58 +0000168void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000169 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000171 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000172 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000173 ::computeKnownBits(V, Known, Depth,
Florian Hahn19f9e322018-08-17 14:39:04 +0000174 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000175}
176
Craig Topper6e11a052017-05-08 16:22:48 +0000177static KnownBits computeKnownBits(const Value *V, unsigned Depth,
178 const Query &Q);
179
180KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
181 unsigned Depth, AssumptionCache *AC,
182 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000183 const DominatorTree *DT,
Florian Hahn19f9e322018-08-17 14:39:04 +0000184 OptimizationRemarkEmitter *ORE,
185 bool UseInstrInfo) {
186 return ::computeKnownBits(
187 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000188}
189
Pete Cooper35b00d52016-08-13 01:05:32 +0000190bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
Florian Hahn19f9e322018-08-17 14:39:04 +0000191 const DataLayout &DL, AssumptionCache *AC,
192 const Instruction *CxtI, const DominatorTree *DT,
193 bool UseInstrInfo) {
Jingyue Wuca321902015-05-14 23:53:19 +0000194 assert(LHS->getType() == RHS->getType() &&
195 "LHS and RHS should have the same type");
196 assert(LHS->getType()->isIntOrIntVectorTy() &&
197 "LHS and RHS should be integers");
Roman Lebedev620b3da2018-04-15 18:59:33 +0000198 // Look for an inverted mask: (X & ~M) op (Y & M).
199 Value *M;
200 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
201 match(RHS, m_c_And(m_Specific(M), m_Value())))
202 return true;
203 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
204 match(LHS, m_c_And(m_Specific(M), m_Value())))
205 return true;
Jingyue Wuca321902015-05-14 23:53:19 +0000206 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000207 KnownBits LHSKnown(IT->getBitWidth());
208 KnownBits RHSKnown(IT->getBitWidth());
Florian Hahn19f9e322018-08-17 14:39:04 +0000209 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
210 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topperb45eabc2017-04-26 16:39:58 +0000211 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000212}
213
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000214bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
215 for (const User *U : CxtI->users()) {
216 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
217 if (IC->isEquality())
218 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
219 if (C->isNullValue())
220 continue;
221 return false;
222 }
223 return true;
224}
225
Pete Cooper35b00d52016-08-13 01:05:32 +0000226static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000227 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000228
Pete Cooper35b00d52016-08-13 01:05:32 +0000229bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000230 bool OrZero, unsigned Depth,
231 AssumptionCache *AC, const Instruction *CxtI,
232 const DominatorTree *DT, bool UseInstrInfo) {
233 return ::isKnownToBeAPowerOfTwo(
234 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235}
236
Pete Cooper35b00d52016-08-13 01:05:32 +0000237static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238
Pete Cooper35b00d52016-08-13 01:05:32 +0000239bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000240 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000241 const DominatorTree *DT, bool UseInstrInfo) {
242 return ::isKnownNonZero(V, Depth,
243 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000244}
245
Pete Cooper35b00d52016-08-13 01:05:32 +0000246bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Florian Hahn19f9e322018-08-17 14:39:04 +0000247 unsigned Depth, AssumptionCache *AC,
248 const Instruction *CxtI, const DominatorTree *DT,
249 bool UseInstrInfo) {
250 KnownBits Known =
251 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000252 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000253}
254
Pete Cooper35b00d52016-08-13 01:05:32 +0000255bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000256 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000257 const DominatorTree *DT, bool UseInstrInfo) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000258 if (auto *CI = dyn_cast<ConstantInt>(V))
259 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000260
Philip Reames8f12eba2016-03-09 21:31:47 +0000261 // TODO: We'd doing two recursive queries here. We should factor this such
262 // that only a single query is needed.
Florian Hahn19f9e322018-08-17 14:39:04 +0000263 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
264 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
Philip Reames8f12eba2016-03-09 21:31:47 +0000265}
266
Pete Cooper35b00d52016-08-13 01:05:32 +0000267bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000268 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000269 const DominatorTree *DT, bool UseInstrInfo) {
270 KnownBits Known =
271 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
Craig Topper6e11a052017-05-08 16:22:48 +0000272 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000273}
274
Pete Cooper35b00d52016-08-13 01:05:32 +0000275static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000276
Pete Cooper35b00d52016-08-13 01:05:32 +0000277bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Florian Hahn19f9e322018-08-17 14:39:04 +0000278 const DataLayout &DL, AssumptionCache *AC,
279 const Instruction *CxtI, const DominatorTree *DT,
280 bool UseInstrInfo) {
281 return ::isKnownNonEqual(V1, V2,
282 Query(DL, AC, safeCxtI(V1, safeCxtI(V2, CxtI)), DT,
283 UseInstrInfo, /*ORE=*/nullptr));
James Molloy1d88d6f2015-10-22 13:18:42 +0000284}
285
Pete Cooper35b00d52016-08-13 01:05:32 +0000286static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000287 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288
Pete Cooper35b00d52016-08-13 01:05:32 +0000289bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
Florian Hahn19f9e322018-08-17 14:39:04 +0000290 const DataLayout &DL, unsigned Depth,
291 AssumptionCache *AC, const Instruction *CxtI,
292 const DominatorTree *DT, bool UseInstrInfo) {
293 return ::MaskedValueIsZero(
294 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295}
296
Pete Cooper35b00d52016-08-13 01:05:32 +0000297static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
298 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000299
Pete Cooper35b00d52016-08-13 01:05:32 +0000300unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000301 unsigned Depth, AssumptionCache *AC,
302 const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +0000303 const DominatorTree *DT, bool UseInstrInfo) {
304 return ::ComputeNumSignBits(
305 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
Hal Finkel60db0582014-09-07 18:57:58 +0000306}
307
Craig Topper8fbb74b2017-03-24 22:12:10 +0000308static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
309 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000310 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000311 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000312 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000313
314 // If an initial sequence of bits in the result is not needed, the
315 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000316 KnownBits LHSKnown(BitWidth);
317 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
318 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000319
Craig Topperb498a232017-08-08 16:29:35 +0000320 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000321}
322
Pete Cooper35b00d52016-08-13 01:05:32 +0000323static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000324 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000325 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000326 unsigned BitWidth = Known.getBitWidth();
327 computeKnownBits(Op1, Known, Depth + 1, Q);
328 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000329
330 bool isKnownNegative = false;
331 bool isKnownNonNegative = false;
332 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000333 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000334 if (Op0 == Op1) {
335 // The product of a number with itself is non-negative.
336 isKnownNonNegative = true;
337 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000338 bool isKnownNonNegativeOp1 = Known.isNonNegative();
339 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
340 bool isKnownNegativeOp1 = Known.isNegative();
341 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000342 // The product of two numbers with the same sign is non-negative.
343 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
344 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
345 // The product of a negative number and a non-negative number is either
346 // negative or zero.
347 if (!isKnownNonNegative)
348 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000349 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000350 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000351 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000352 }
353 }
354
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000355 assert(!Known.hasConflict() && !Known2.hasConflict());
356 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000357 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
358 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000359 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000360 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000361
362 // The result of the bottom bits of an integer multiply can be
363 // inferred by looking at the bottom bits of both operands and
364 // multiplying them together.
365 // We can infer at least the minimum number of known trailing bits
366 // of both operands. Depending on number of trailing zeros, we can
367 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
368 // a and b are divisible by m and n respectively.
369 // We then calculate how many of those bits are inferrable and set
370 // the output. For example, the i8 mul:
371 // a = XXXX1100 (12)
372 // b = XXXX1110 (14)
373 // We know the bottom 3 bits are zero since the first can be divided by
374 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
375 // Applying the multiplication to the trimmed arguments gets:
376 // XX11 (3)
377 // X111 (7)
378 // -------
379 // XX11
380 // XX11
381 // XX11
382 // XX11
383 // -------
384 // XXXXX01
385 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
386 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
387 // The proof for this can be described as:
388 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
389 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
390 // umin(countTrailingZeros(C2), C6) +
391 // umin(C5 - umin(countTrailingZeros(C1), C5),
392 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
393 // %aa = shl i8 %a, C5
394 // %bb = shl i8 %b, C6
395 // %aaa = or i8 %aa, C1
396 // %bbb = or i8 %bb, C2
397 // %mul = mul i8 %aaa, %bbb
398 // %mask = and i8 %mul, C7
399 // =>
400 // %mask = i8 ((C1*C2)&C7)
401 // Where C5, C6 describe the known bits of %a, %b
402 // C1, C2 describe the known bottom bits of %a, %b.
403 // C7 describes the mask of the known bits of the result.
404 APInt Bottom0 = Known.One;
405 APInt Bottom1 = Known2.One;
406
407 // How many times we'd be able to divide each argument by 2 (shr by 1).
408 // This gives us the number of trailing zeros on the multiplication result.
409 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
410 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
411 unsigned TrailZero0 = Known.countMinTrailingZeros();
412 unsigned TrailZero1 = Known2.countMinTrailingZeros();
413 unsigned TrailZ = TrailZero0 + TrailZero1;
414
415 // Figure out the fewest known-bits operand.
416 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
417 TrailBitsKnown1 - TrailZero1);
418 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
419
420 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
421 Bottom1.getLoBits(TrailBitsKnown1);
422
Craig Topperf0aeee02017-05-05 17:36:09 +0000423 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000424 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000425 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
426 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000427
428 // Only make use of no-wrap flags if we failed to compute the sign bit
429 // directly. This matters if the multiplication always overflows, in
430 // which case we prefer to follow the result of the direct computation,
431 // though as the program is invoking undefined behaviour we can choose
432 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000433 if (isKnownNonNegative && !Known.isNegative())
434 Known.makeNonNegative();
435 else if (isKnownNegative && !Known.isNonNegative())
436 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000437}
438
Jingyue Wu37fcb592014-06-19 16:50:16 +0000439void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000440 KnownBits &Known) {
441 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000442 unsigned NumRanges = Ranges.getNumOperands() / 2;
443 assert(NumRanges >= 1);
444
Craig Topperf42b23f2017-04-28 06:28:56 +0000445 Known.Zero.setAllBits();
446 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000447
Rafael Espindola53190532012-03-30 15:52:11 +0000448 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000449 ConstantInt *Lower =
450 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
451 ConstantInt *Upper =
452 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000453 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000454
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000455 // The first CommonPrefixBits of all values in Range are equal.
456 unsigned CommonPrefixBits =
457 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
458
459 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000460 Known.One &= Range.getUnsignedMax() & Mask;
461 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000462 }
Rafael Espindola53190532012-03-30 15:52:11 +0000463}
Jay Foad5a29c362014-05-15 12:12:55 +0000464
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000465static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000466 SmallVector<const Value *, 16> WorkSet(1, I);
467 SmallPtrSet<const Value *, 32> Visited;
468 SmallPtrSet<const Value *, 16> EphValues;
469
Hal Finkelf2199b22015-10-23 20:37:08 +0000470 // The instruction defining an assumption's condition itself is always
471 // considered ephemeral to that assumption (even if it has other
472 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000473 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000474 return true;
475
Hal Finkel60db0582014-09-07 18:57:58 +0000476 while (!WorkSet.empty()) {
477 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000478 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000479 continue;
480
481 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000482 if (llvm::all_of(V->users(), [&](const User *U) {
483 return EphValues.count(U);
484 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000485 if (V == E)
486 return true;
487
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000488 if (V == I || isSafeToSpeculativelyExecute(V)) {
489 EphValues.insert(V);
490 if (const User *U = dyn_cast<User>(V))
491 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
492 J != JE; ++J)
493 WorkSet.push_back(*J);
494 }
Hal Finkel60db0582014-09-07 18:57:58 +0000495 }
496 }
497
498 return false;
499}
500
501// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000502bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000503 if (const CallInst *CI = dyn_cast<CallInst>(I))
504 if (Function *F = CI->getCalledFunction())
505 switch (F->getIntrinsicID()) {
506 default: break;
507 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
508 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000509 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000510 case Intrinsic::dbg_declare:
511 case Intrinsic::dbg_value:
Shiva Chen2c864552018-05-09 02:40:45 +0000512 case Intrinsic::dbg_label:
Hal Finkel60db0582014-09-07 18:57:58 +0000513 case Intrinsic::invariant_start:
514 case Intrinsic::invariant_end:
515 case Intrinsic::lifetime_start:
516 case Intrinsic::lifetime_end:
517 case Intrinsic::objectsize:
518 case Intrinsic::ptr_annotation:
519 case Intrinsic::var_annotation:
520 return true;
521 }
522
523 return false;
524}
525
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000526bool llvm::isValidAssumeForContext(const Instruction *Inv,
527 const Instruction *CxtI,
528 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000529 // There are two restrictions on the use of an assume:
530 // 1. The assume must dominate the context (or the control flow must
531 // reach the assume whenever it reaches the context).
532 // 2. The context must not be in the assume's set of ephemeral values
533 // (otherwise we will use the assume to prove that the condition
534 // feeding the assume is trivially true, thus causing the removal of
535 // the assume).
536
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000537 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000538 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000539 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000540 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
541 // We don't have a DT, but this trivially dominates.
542 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000543 }
544
Pete Cooper54a02552016-08-12 01:00:15 +0000545 // With or without a DT, the only remaining case we will check is if the
546 // instructions are in the same BB. Give up if that is not the case.
547 if (Inv->getParent() != CxtI->getParent())
548 return false;
549
Vedant Kumard3196742018-02-28 19:08:52 +0000550 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000551 // the other instruction. If we don't have a dom tree then we can check if
552 // the assume is first in the BB.
553 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000554 // Search forward from the assume until we reach the context (or the end
555 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000556 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000557 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000558 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000559 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000560 }
561
Pete Cooper54a02552016-08-12 01:00:15 +0000562 // The context comes first, but they're both in the same block. Make sure
563 // there is nothing in between that might interrupt the control flow.
564 for (BasicBlock::const_iterator I =
565 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
566 I != IE; ++I)
567 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
568 return false;
569
570 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000571}
572
Craig Topperb45eabc2017-04-26 16:39:58 +0000573static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
574 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000575 // Use of assumptions is context-sensitive. If we don't have a context, we
576 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000578 return;
579
Craig Topperb45eabc2017-04-26 16:39:58 +0000580 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000581
Hal Finkel8a9a7832017-01-11 13:24:24 +0000582 // Note that the patterns below need to be kept in sync with the code
583 // in AssumptionCache::updateAffectedValues.
584
585 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000586 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000587 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000588 CallInst *I = cast<CallInst>(AssumeVH);
589 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
590 "Got assumption for the wrong function!");
591 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000592 continue;
593
Vedant Kumard3196742018-02-28 19:08:52 +0000594 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000595 // We're running this loop for once for each value queried resulting in a
596 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000597
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000598 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
599 "must be an assume intrinsic");
600
601 Value *Arg = I->getArgOperand(0);
602
603 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000604 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000605 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000606 return;
607 }
Sanjay Patel96669962017-01-17 18:15:49 +0000608 if (match(Arg, m_Not(m_Specific(V))) &&
609 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
610 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000611 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000612 return;
613 }
Hal Finkel60db0582014-09-07 18:57:58 +0000614
David Majnemer9b609752014-12-12 23:59:29 +0000615 // The remaining tests are all recursive, so bail out if we hit the limit.
616 if (Depth == MaxDepth)
617 continue;
618
Sander de Smalen0e66db52019-04-10 16:24:48 +0000619 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
620 if (!Cmp)
621 continue;
622
Hal Finkel60db0582014-09-07 18:57:58 +0000623 Value *A, *B;
Sanjay Patel2a707032019-03-03 18:59:33 +0000624 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
Hal Finkel60db0582014-09-07 18:57:58 +0000625
626 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000627 uint64_t C;
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000628 switch (Cmp->getPredicate()) {
629 default:
630 break;
631 case ICmpInst::ICMP_EQ:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000632 // assume(v = a)
633 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
634 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
635 KnownBits RHSKnown(BitWidth);
636 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
637 Known.Zero |= RHSKnown.Zero;
638 Known.One |= RHSKnown.One;
639 // assume(v & b = a)
640 } else if (match(Cmp,
641 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
642 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
643 KnownBits RHSKnown(BitWidth);
644 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
645 KnownBits MaskKnown(BitWidth);
646 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000647
Sander de Smalen0e66db52019-04-10 16:24:48 +0000648 // For those bits in the mask that are known to be one, we can propagate
649 // known bits from the RHS to V.
650 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
651 Known.One |= RHSKnown.One & MaskKnown.One;
652 // assume(~(v & b) = a)
653 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
654 m_Value(A))) &&
655 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
656 KnownBits RHSKnown(BitWidth);
657 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
658 KnownBits MaskKnown(BitWidth);
659 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000660
Sander de Smalen0e66db52019-04-10 16:24:48 +0000661 // For those bits in the mask that are known to be one, we can propagate
662 // inverted known bits from the RHS to V.
663 Known.Zero |= RHSKnown.One & MaskKnown.One;
664 Known.One |= RHSKnown.Zero & MaskKnown.One;
665 // assume(v | b = a)
666 } else if (match(Cmp,
667 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
668 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
669 KnownBits RHSKnown(BitWidth);
670 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
671 KnownBits BKnown(BitWidth);
672 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000673
Sander de Smalen0e66db52019-04-10 16:24:48 +0000674 // For those bits in B that are known to be zero, we can propagate known
675 // bits from the RHS to V.
676 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
677 Known.One |= RHSKnown.One & BKnown.Zero;
678 // assume(~(v | b) = a)
679 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
680 m_Value(A))) &&
681 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
682 KnownBits RHSKnown(BitWidth);
683 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
684 KnownBits BKnown(BitWidth);
685 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000686
Sander de Smalen0e66db52019-04-10 16:24:48 +0000687 // For those bits in B that are known to be zero, we can propagate
688 // inverted known bits from the RHS to V.
689 Known.Zero |= RHSKnown.One & BKnown.Zero;
690 Known.One |= RHSKnown.Zero & BKnown.Zero;
691 // assume(v ^ b = a)
692 } else if (match(Cmp,
693 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
694 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
695 KnownBits RHSKnown(BitWidth);
696 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
697 KnownBits BKnown(BitWidth);
698 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000699
Sander de Smalen0e66db52019-04-10 16:24:48 +0000700 // For those bits in B that are known to be zero, we can propagate known
701 // bits from the RHS to V. For those bits in B that are known to be one,
702 // we can propagate inverted known bits from the RHS to V.
703 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
704 Known.One |= RHSKnown.One & BKnown.Zero;
705 Known.Zero |= RHSKnown.One & BKnown.One;
706 Known.One |= RHSKnown.Zero & BKnown.One;
707 // assume(~(v ^ b) = a)
708 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
709 m_Value(A))) &&
710 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
711 KnownBits RHSKnown(BitWidth);
712 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
713 KnownBits BKnown(BitWidth);
714 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000715
Sander de Smalen0e66db52019-04-10 16:24:48 +0000716 // For those bits in B that are known to be zero, we can propagate
717 // inverted known bits from the RHS to V. For those bits in B that are
718 // known to be one, we can propagate known bits from the RHS to V.
719 Known.Zero |= RHSKnown.One & BKnown.Zero;
720 Known.One |= RHSKnown.Zero & BKnown.Zero;
721 Known.Zero |= RHSKnown.Zero & BKnown.One;
722 Known.One |= RHSKnown.One & BKnown.One;
723 // assume(v << c = a)
724 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
725 m_Value(A))) &&
726 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
727 KnownBits RHSKnown(BitWidth);
728 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
729 // For those bits in RHS that are known, we can propagate them to known
730 // bits in V shifted to the right by C.
731 RHSKnown.Zero.lshrInPlace(C);
732 Known.Zero |= RHSKnown.Zero;
733 RHSKnown.One.lshrInPlace(C);
734 Known.One |= RHSKnown.One;
735 // assume(~(v << c) = a)
736 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
737 m_Value(A))) &&
738 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
739 KnownBits RHSKnown(BitWidth);
740 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
741 // For those bits in RHS that are known, we can propagate them inverted
742 // to known bits in V shifted to the right by C.
743 RHSKnown.One.lshrInPlace(C);
744 Known.Zero |= RHSKnown.One;
745 RHSKnown.Zero.lshrInPlace(C);
746 Known.One |= RHSKnown.Zero;
747 // assume(v >> c = a)
748 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
749 m_Value(A))) &&
750 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
751 KnownBits RHSKnown(BitWidth);
752 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
753 // For those bits in RHS that are known, we can propagate them to known
754 // bits in V shifted to the right by C.
755 Known.Zero |= RHSKnown.Zero << C;
756 Known.One |= RHSKnown.One << C;
757 // assume(~(v >> c) = a)
758 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
759 m_Value(A))) &&
760 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
761 KnownBits RHSKnown(BitWidth);
762 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
763 // For those bits in RHS that are known, we can propagate them inverted
764 // to known bits in V shifted to the right by C.
765 Known.Zero |= RHSKnown.One << C;
766 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000767 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000768 break;
769 case ICmpInst::ICMP_SGE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000770 // assume(v >=_s c) where c is non-negative
771 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
772 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
773 KnownBits RHSKnown(BitWidth);
774 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000775
Sander de Smalen0e66db52019-04-10 16:24:48 +0000776 if (RHSKnown.isNonNegative()) {
777 // We know that the sign bit is zero.
778 Known.makeNonNegative();
779 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000780 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000781 break;
782 case ICmpInst::ICMP_SGT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000783 // assume(v >_s c) where c is at least -1.
784 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
785 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
786 KnownBits RHSKnown(BitWidth);
787 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000788
Sander de Smalen0e66db52019-04-10 16:24:48 +0000789 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
790 // We know that the sign bit is zero.
791 Known.makeNonNegative();
792 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000793 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000794 break;
795 case ICmpInst::ICMP_SLE:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000796 // assume(v <=_s c) where c is negative
797 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
798 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
799 KnownBits RHSKnown(BitWidth);
800 computeKnownBits(A, RHSKnown, Depth + 1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000801
Sander de Smalen0e66db52019-04-10 16:24:48 +0000802 if (RHSKnown.isNegative()) {
803 // We know that the sign bit is one.
804 Known.makeNegative();
805 }
806 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000807 break;
808 case ICmpInst::ICMP_SLT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000809 // assume(v <_s c) where c is non-positive
810 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
811 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
812 KnownBits RHSKnown(BitWidth);
813 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
814
815 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
816 // We know that the sign bit is one.
817 Known.makeNegative();
818 }
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000819 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000820 break;
821 case ICmpInst::ICMP_ULE:
822 // assume(v <=_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000823 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
824 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
825 KnownBits RHSKnown(BitWidth);
826 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000827
Sander de Smalen0e66db52019-04-10 16:24:48 +0000828 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000829 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Sander de Smalen0e66db52019-04-10 16:24:48 +0000830 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000831 break;
832 case ICmpInst::ICMP_ULT:
Sander de Smalen0e66db52019-04-10 16:24:48 +0000833 // assume(v <_u c)
Sander de Smalen0e66db52019-04-10 16:24:48 +0000834 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
835 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
836 KnownBits RHSKnown(BitWidth);
837 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
838
839 // If the RHS is known zero, then this assumption must be wrong (nothing
840 // is unsigned less than zero). Signal a conflict and get out of here.
841 if (RHSKnown.isZero()) {
842 Known.Zero.setAllBits();
843 Known.One.setAllBits();
844 break;
845 }
846
847 // Whatever high bits in c are zero are known to be zero (if c is a power
848 // of 2, then one more).
849 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
850 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
851 else
852 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
853 }
Sander de Smalen4f5d2df2019-04-11 13:02:19 +0000854 break;
Hal Finkel60db0582014-09-07 18:57:58 +0000855 }
856 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000857
858 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000859 // have a logical fallacy. It's possible that the assumption is not reachable,
860 // so this isn't a real bug. On the other hand, the program may have undefined
861 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
862 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000863 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000864 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000865
Vivek Pandya95906582017-10-11 17:12:59 +0000866 if (Q.ORE)
867 Q.ORE->emit([&]() {
868 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
869 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
870 CxtI)
871 << "Detected conflicting code assumptions. Program may "
872 "have undefined behavior, or compiler may have "
873 "internal error.";
874 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000875 }
Hal Finkel60db0582014-09-07 18:57:58 +0000876}
877
Sanjay Patelb7d12382017-10-16 14:46:37 +0000878/// Compute known bits from a shift operator, including those with a
879/// non-constant shift amount. Known is the output of this function. Known2 is a
880/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000881/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000882/// respectively, and a shift amount, compute the implied known-zero or
883/// known-one bits of the shift operator's result respectively for that shift
884/// amount. The results from calling KZF and KOF are conservatively combined for
885/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000886static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000887 const Operator *I, KnownBits &Known, KnownBits &Known2,
888 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000889 function_ref<APInt(const APInt &, unsigned)> KZF,
890 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000891 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000892
893 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
894 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
895
Craig Topperb45eabc2017-04-26 16:39:58 +0000896 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000897 Known.Zero = KZF(Known.Zero, ShiftAmt);
898 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000899 // If the known bits conflict, this must be an overflowing left shift, so
900 // the shift result is poison. We can return anything we want. Choose 0 for
901 // the best folding opportunity.
902 if (Known.hasConflict())
903 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000904
Hal Finkelf2199b22015-10-23 20:37:08 +0000905 return;
906 }
907
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000909
Sanjay Patele272be72017-10-12 17:31:46 +0000910 // If the shift amount could be greater than or equal to the bit-width of the
911 // LHS, the value could be poison, but bail out because the check below is
912 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000913 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000914 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000915 return;
916 }
917
Craig Topperb45eabc2017-04-26 16:39:58 +0000918 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000919 // BitWidth > 64 and any upper bits are known, we'll end up returning the
920 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000921 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
922 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000923
924 // It would be more-clearly correct to use the two temporaries for this
925 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000926 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000927
James Molloy493e57d2015-10-26 14:10:46 +0000928 // If we know the shifter operand is nonzero, we can sometimes infer more
929 // known bits. However this is expensive to compute, so be lazy about it and
930 // only compute it when absolutely necessary.
931 Optional<bool> ShifterOperandIsNonZero;
932
Hal Finkelf2199b22015-10-23 20:37:08 +0000933 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000934 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
935 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000936 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000937 if (!*ShifterOperandIsNonZero)
938 return;
939 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000940
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000942
Craig Topperb45eabc2017-04-26 16:39:58 +0000943 Known.Zero.setAllBits();
944 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000945 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
946 // Combine the shifted known input bits only for those shift amounts
947 // compatible with its known constraints.
948 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
949 continue;
950 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
951 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000952 // If we know the shifter is nonzero, we may be able to infer more known
953 // bits. This check is sunk down as far as possible to avoid the expensive
954 // call to isKnownNonZero if the cheaper checks above fail.
955 if (ShiftAmt == 0) {
956 if (!ShifterOperandIsNonZero.hasValue())
957 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000958 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000959 if (*ShifterOperandIsNonZero)
960 continue;
961 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000962
Sam McCalld0d43e62017-12-04 12:51:49 +0000963 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
964 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000965 }
966
Sanjay Patele272be72017-10-12 17:31:46 +0000967 // If the known bits conflict, the result is poison. Return a 0 and hope the
968 // caller can further optimize that.
969 if (Known.hasConflict())
970 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000971}
972
Craig Topperb45eabc2017-04-26 16:39:58 +0000973static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
974 unsigned Depth, const Query &Q) {
975 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000976
Craig Topperb45eabc2017-04-26 16:39:58 +0000977 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000978 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000979 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000980 case Instruction::Load:
Florian Hahn19f9e322018-08-17 14:39:04 +0000981 if (MDNode *MD =
982 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000983 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000984 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000985 case Instruction::And: {
986 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000987 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
988 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000989
Chris Lattner965c7692008-06-02 01:18:21 +0000990 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000991 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000992 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000993 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000994
995 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
996 // here we handle the more general case of adding any odd number by
997 // matching the form add(x, add(x, y)) where y is odd.
998 // TODO: This could be generalized to clearing any bit set in y where the
999 // following bit is known to be unset in y.
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001000 Value *X = nullptr, *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +00001001 if (!Known.Zero[0] && !Known.One[0] &&
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001002 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001003 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001004 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001005 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001006 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +00001007 }
Jay Foad5a29c362014-05-15 12:12:55 +00001008 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001009 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001010 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +00001011 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1012 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001013
Chris Lattner965c7692008-06-02 01:18:21 +00001014 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001015 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +00001016 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001017 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +00001018 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001019 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1021 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001022
Chris Lattner965c7692008-06-02 01:18:21 +00001023 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001024 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001025 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001026 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1027 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001028 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001029 }
1030 case Instruction::Mul: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001031 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Craig Topperb45eabc2017-04-26 16:39:58 +00001032 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1033 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001034 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001035 }
1036 case Instruction::UDiv: {
1037 // For the purposes of computing leading zeros we can conservatively
1038 // treat a udiv as a logical right shift by the power of 2 known to
1039 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001040 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001041 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001042
Craig Topperf0aeee02017-05-05 17:36:09 +00001043 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001044 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001045 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1046 if (RHSMaxLeadingZeros != BitWidth)
1047 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001048
Craig Topperb45eabc2017-04-26 16:39:58 +00001049 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001050 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001051 }
David Majnemera19d0f22016-08-06 08:16:00 +00001052 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001053 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001054 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1055 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001056 computeKnownBits(RHS, Known, Depth + 1, Q);
1057 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001058 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001059 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1060 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001061 }
1062
1063 unsigned MaxHighOnes = 0;
1064 unsigned MaxHighZeros = 0;
1065 if (SPF == SPF_SMAX) {
1066 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001067 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001068 // We can derive a lower bound on the result by taking the max of the
1069 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001070 MaxHighOnes =
1071 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001072 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001073 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001074 MaxHighZeros = 1;
1075 } else if (SPF == SPF_SMIN) {
1076 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001077 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001078 // We can derive an upper bound on the result by taking the max of the
1079 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001080 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1081 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001082 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001083 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001084 MaxHighOnes = 1;
1085 } else if (SPF == SPF_UMAX) {
1086 // We can derive a lower bound on the result by taking the max of the
1087 // leading one bits.
1088 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001089 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001090 } else if (SPF == SPF_UMIN) {
1091 // We can derive an upper bound on the result by taking the max of the
1092 // leading zero bits.
1093 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001094 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topper8f77dca2018-05-25 19:18:09 +00001095 } else if (SPF == SPF_ABS) {
1096 // RHS from matchSelectPattern returns the negation part of abs pattern.
1097 // If the negate has an NSW flag we can assume the sign bit of the result
1098 // will be 0 because that makes abs(INT_MIN) undefined.
Florian Hahn19f9e322018-08-17 14:39:04 +00001099 if (Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
Craig Topper8f77dca2018-05-25 19:18:09 +00001100 MaxHighZeros = 1;
David Majnemera19d0f22016-08-06 08:16:00 +00001101 }
1102
Chris Lattner965c7692008-06-02 01:18:21 +00001103 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001104 Known.One &= Known2.One;
1105 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001106 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001107 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001108 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001109 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001110 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001111 }
Chris Lattner965c7692008-06-02 01:18:21 +00001112 case Instruction::FPTrunc:
1113 case Instruction::FPExt:
1114 case Instruction::FPToUI:
1115 case Instruction::FPToSI:
1116 case Instruction::SIToFP:
1117 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001118 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001119 case Instruction::PtrToInt:
1120 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001121 // Fall through and handle them the same as zext/trunc.
1122 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001123 case Instruction::ZExt:
1124 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001125 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001126
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001127 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001128 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1129 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001130 Type *ScalarTy = SrcTy->getScalarType();
1131 SrcBitWidth = ScalarTy->isPointerTy() ?
1132 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1133 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001134
1135 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001136 Known = Known.zextOrTrunc(SrcBitWidth, false);
Craig Topperb45eabc2017-04-26 16:39:58 +00001137 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Petterssond30f3082019-02-28 15:45:29 +00001138 Known = Known.zextOrTrunc(BitWidth, true /* ExtendedBitsAreKnownZero */);
Jay Foad5a29c362014-05-15 12:12:55 +00001139 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001140 }
1141 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001142 Type *SrcTy = I->getOperand(0)->getType();
Vedant Kumarb3091da2018-07-06 20:17:42 +00001143 if (SrcTy->isIntOrPtrTy() &&
Chris Lattneredb84072009-07-02 16:04:08 +00001144 // TODO: For now, not handling conversions like:
1145 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001146 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001147 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001148 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001149 }
1150 break;
1151 }
1152 case Instruction::SExt: {
1153 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001154 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001155
Craig Topperd938fd12017-05-03 22:07:25 +00001156 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001157 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001158 // If the sign bit of the input is known set or clear, then we know the
1159 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001160 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001161 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001162 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001163 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001164 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001165 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Sam McCalld0d43e62017-12-04 12:51:49 +00001166 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1167 APInt KZResult = KnownZero << ShiftAmt;
1168 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001169 // If this shift has "nsw" keyword, then the result is either a poison
1170 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001171 if (NSW && KnownZero.isSignBitSet())
1172 KZResult.setSignBit();
1173 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001174 };
1175
Sam McCalld0d43e62017-12-04 12:51:49 +00001176 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1177 APInt KOResult = KnownOne << ShiftAmt;
1178 if (NSW && KnownOne.isSignBitSet())
1179 KOResult.setSignBit();
1180 return KOResult;
1181 };
1182
1183 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001184 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001185 }
1186 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001187 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001188 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1189 APInt KZResult = KnownZero.lshr(ShiftAmt);
1190 // High bits known zero.
1191 KZResult.setHighBits(ShiftAmt);
1192 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001193 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001194
Sam McCalld0d43e62017-12-04 12:51:49 +00001195 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1196 return KnownOne.lshr(ShiftAmt);
1197 };
1198
1199 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001200 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001201 }
1202 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001203 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001204 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1205 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001206 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001207
Sam McCalld0d43e62017-12-04 12:51:49 +00001208 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1209 return KnownOne.ashr(ShiftAmt);
1210 };
1211
1212 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001213 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001214 }
Chris Lattner965c7692008-06-02 01:18:21 +00001215 case Instruction::Sub: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001216 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001217 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001218 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001219 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001220 }
Chris Lattner965c7692008-06-02 01:18:21 +00001221 case Instruction::Add: {
Florian Hahn19f9e322018-08-17 14:39:04 +00001222 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
Jay Foada0653a32014-05-14 21:14:37 +00001223 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001224 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001225 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001226 }
1227 case Instruction::SRem:
1228 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001229 APInt RA = Rem->getValue().abs();
1230 if (RA.isPowerOf2()) {
1231 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001232 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001233
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001234 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001235 Known.Zero = Known2.Zero & LowBits;
1236 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001237
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001238 // If the first operand is non-negative or has all low bits zero, then
1239 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001240 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001241 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001242
1243 // If the first operand is negative and not all low bits are zero, then
1244 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001245 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001246 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001247
Craig Topperb45eabc2017-04-26 16:39:58 +00001248 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001249 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001250 }
1251 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001252
1253 // The sign bit is the LHS's sign bit, except when the result of the
1254 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001255 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001256 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001257 if (Known2.isNonNegative())
1258 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001259
Chris Lattner965c7692008-06-02 01:18:21 +00001260 break;
1261 case Instruction::URem: {
1262 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001263 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001264 if (RA.isPowerOf2()) {
1265 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001266 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1267 Known.Zero |= ~LowBits;
1268 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001269 break;
1270 }
1271 }
1272
1273 // Since the result is less than or equal to either operand, any leading
1274 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001275 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1276 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001277
Craig Topper8df66c62017-05-12 17:20:30 +00001278 unsigned Leaders =
1279 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001280 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001281 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001282 break;
1283 }
1284
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001285 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001286 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001287 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001288 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001289 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001290
Chris Lattner965c7692008-06-02 01:18:21 +00001291 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001292 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001293 break;
1294 }
1295 case Instruction::GetElementPtr: {
1296 // Analyze all of the subscripts of this getelementptr instruction
1297 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001298 KnownBits LocalKnown(BitWidth);
1299 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001300 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001301
1302 gep_type_iterator GTI = gep_type_begin(I);
1303 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1304 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001305 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001306 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001307
1308 // Handle case when index is vector zeroinitializer
1309 Constant *CIndex = cast<Constant>(Index);
1310 if (CIndex->isZeroValue())
1311 continue;
1312
1313 if (CIndex->getType()->isVectorTy())
1314 Index = CIndex->getSplatValue();
1315
Chris Lattner965c7692008-06-02 01:18:21 +00001316 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001317 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001318 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001319 TrailZ = std::min<unsigned>(TrailZ,
1320 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001321 } else {
1322 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001323 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001324 if (!IndexedTy->isSized()) {
1325 TrailZ = 0;
1326 break;
1327 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001328 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001329 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001330 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1331 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001332 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001333 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001334 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001335 }
1336 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001337
Craig Topperb45eabc2017-04-26 16:39:58 +00001338 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001339 break;
1340 }
1341 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001342 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001343 // Handle the case of a simple two-predecessor recurrence PHI.
1344 // There's a lot more that could theoretically be done here, but
1345 // this is sufficient to catch some interesting cases.
1346 if (P->getNumIncomingValues() == 2) {
1347 for (unsigned i = 0; i != 2; ++i) {
1348 Value *L = P->getIncomingValue(i);
1349 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001350 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001351 if (!LU)
1352 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001353 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001354 // Check for operations that have the property that if
1355 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001356 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001357 if (Opcode == Instruction::Add ||
1358 Opcode == Instruction::Sub ||
1359 Opcode == Instruction::And ||
1360 Opcode == Instruction::Or ||
1361 Opcode == Instruction::Mul) {
1362 Value *LL = LU->getOperand(0);
1363 Value *LR = LU->getOperand(1);
1364 // Find a recurrence.
1365 if (LL == I)
1366 L = LR;
1367 else if (LR == I)
1368 L = LL;
1369 else
1370 break;
1371 // Ok, we have a PHI of the form L op= R. Check for low
1372 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001373 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001374
1375 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001376 KnownBits Known3(Known);
1377 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001378
Craig Topper8df66c62017-05-12 17:20:30 +00001379 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1380 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001381
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001382 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
Florian Hahn19f9e322018-08-17 14:39:04 +00001383 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001384 // If initial value of recurrence is nonnegative, and we are adding
1385 // a nonnegative number with nsw, the result can only be nonnegative
1386 // or poison value regardless of the number of times we execute the
1387 // add in phi recurrence. If initial value is negative and we are
1388 // adding a negative number with nsw, the result can only be
1389 // negative or poison value. Similar arguments apply to sub and mul.
1390 //
1391 // (add non-negative, non-negative) --> non-negative
1392 // (add negative, negative) --> negative
1393 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001394 if (Known2.isNonNegative() && Known3.isNonNegative())
1395 Known.makeNonNegative();
1396 else if (Known2.isNegative() && Known3.isNegative())
1397 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001398 }
1399
1400 // (sub nsw non-negative, negative) --> non-negative
1401 // (sub nsw negative, non-negative) --> negative
1402 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001403 if (Known2.isNonNegative() && Known3.isNegative())
1404 Known.makeNonNegative();
1405 else if (Known2.isNegative() && Known3.isNonNegative())
1406 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001407 }
1408
1409 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001410 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1411 Known3.isNonNegative())
1412 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001413 }
1414
Chris Lattner965c7692008-06-02 01:18:21 +00001415 break;
1416 }
1417 }
1418 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001419
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001420 // Unreachable blocks may have zero-operand PHI nodes.
1421 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001422 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001423
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001424 // Otherwise take the unions of the known bit sets of the operands,
1425 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001426 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001427 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001428 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001429 break;
1430
Craig Topperb45eabc2017-04-26 16:39:58 +00001431 Known.Zero.setAllBits();
1432 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001433 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001434 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001435 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001436
Craig Topperb45eabc2017-04-26 16:39:58 +00001437 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001438 // Recurse, but cap the recursion to one level, because we don't
1439 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001440 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1441 Known.Zero &= Known2.Zero;
1442 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001443 // If all bits have been ruled out, there's no need to check
1444 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001445 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001446 break;
1447 }
1448 }
Chris Lattner965c7692008-06-02 01:18:21 +00001449 break;
1450 }
1451 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001452 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001453 // If range metadata is attached to this call, set known bits from that,
1454 // and then intersect with known bits based on other properties of the
1455 // function.
Florian Hahn19f9e322018-08-17 14:39:04 +00001456 if (MDNode *MD =
1457 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001458 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001459 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001460 computeKnownBits(RV, Known2, Depth + 1, Q);
1461 Known.Zero |= Known2.Zero;
1462 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001463 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001464 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001465 switch (II->getIntrinsicID()) {
1466 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001467 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001468 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1469 Known.Zero |= Known2.Zero.reverseBits();
1470 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001471 break;
Philip Reames675418e2015-10-06 20:20:45 +00001472 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001473 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1474 Known.Zero |= Known2.Zero.byteSwap();
1475 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001476 break;
Craig Topper868813f2017-05-08 17:22:34 +00001477 case Intrinsic::ctlz: {
1478 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1479 // If we have a known 1, its position is our upper bound.
1480 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001481 // If this call is undefined for 0, the result will be less than 2^n.
1482 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001483 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1484 unsigned LowBits = Log2_32(PossibleLZ)+1;
1485 Known.Zero.setBitsFrom(LowBits);
1486 break;
1487 }
1488 case Intrinsic::cttz: {
1489 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1490 // If we have a known 1, its position is our upper bound.
1491 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1492 // If this call is undefined for 0, the result will be less than 2^n.
1493 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1494 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1495 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001496 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001497 break;
1498 }
1499 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001500 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001501 // We can bound the space the count needs. Also, bits known to be zero
1502 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001503 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001504 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001505 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001506 // TODO: we could bound KnownOne using the lower bound on the number
1507 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001508 break;
1509 }
Nikita Popov687b92c2018-12-02 14:14:11 +00001510 case Intrinsic::fshr:
1511 case Intrinsic::fshl: {
1512 const APInt *SA;
1513 if (!match(I->getOperand(2), m_APInt(SA)))
1514 break;
1515
1516 // Normalize to funnel shift left.
1517 uint64_t ShiftAmt = SA->urem(BitWidth);
1518 if (II->getIntrinsicID() == Intrinsic::fshr)
1519 ShiftAmt = BitWidth - ShiftAmt;
1520
1521 KnownBits Known3(Known);
1522 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1523 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1524
1525 Known.Zero =
1526 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1527 Known.One =
1528 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1529 break;
1530 }
Nikita Popoved3ca922019-03-01 20:07:04 +00001531 case Intrinsic::uadd_sat:
1532 case Intrinsic::usub_sat: {
1533 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1534 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1535 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1536
1537 // Add: Leading ones of either operand are preserved.
1538 // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1539 // as leading zeros in the result.
1540 unsigned LeadingKnown;
1541 if (IsAdd)
1542 LeadingKnown = std::max(Known.countMinLeadingOnes(),
1543 Known2.countMinLeadingOnes());
1544 else
1545 LeadingKnown = std::max(Known.countMinLeadingZeros(),
1546 Known2.countMinLeadingOnes());
1547
1548 Known = KnownBits::computeForAddSub(
1549 IsAdd, /* NSW */ false, Known, Known2);
1550
1551 // We select between the operation result and all-ones/zero
1552 // respectively, so we can preserve known ones/zeros.
1553 if (IsAdd) {
1554 Known.One.setHighBits(LeadingKnown);
1555 Known.Zero.clearAllBits();
1556 } else {
1557 Known.Zero.setHighBits(LeadingKnown);
1558 Known.One.clearAllBits();
1559 }
1560 break;
1561 }
Chad Rosierb3628842011-05-26 23:13:19 +00001562 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001563 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001564 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001565 }
1566 }
1567 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001568 case Instruction::ExtractElement:
1569 // Look through extract element. At the moment we keep this simple and skip
1570 // tracking the specific element. But at least we might find information
1571 // valid for all elements of the vector (for example if vector is sign
1572 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001573 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001574 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001575 case Instruction::ExtractValue:
1576 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001577 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001578 if (EVI->getNumIndices() != 1) break;
1579 if (EVI->getIndices()[0] == 0) {
1580 switch (II->getIntrinsicID()) {
1581 default: break;
1582 case Intrinsic::uadd_with_overflow:
1583 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001584 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001585 II->getArgOperand(1), false, Known, Known2,
1586 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001587 break;
1588 case Intrinsic::usub_with_overflow:
1589 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001590 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001591 II->getArgOperand(1), false, Known, Known2,
1592 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001593 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001594 case Intrinsic::umul_with_overflow:
1595 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001596 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001597 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001598 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001599 }
1600 }
1601 }
Chris Lattner965c7692008-06-02 01:18:21 +00001602 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001603}
1604
1605/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001606/// them.
1607KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1608 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1609 computeKnownBits(V, Known, Depth, Q);
1610 return Known;
1611}
1612
1613/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001614/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001615///
1616/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1617/// we cannot optimize based on the assumption that it is zero without changing
1618/// it to be an explicit zero. If we don't change it to zero, other code could
1619/// optimized based on the contradictory assumption that it is non-zero.
1620/// Because instcombine aggressively folds operations with undef args anyway,
1621/// this won't lose us code quality.
1622///
1623/// This function is defined on values with integer type, values with pointer
1624/// type, and vectors of integers. In the case
1625/// where V is a vector, known zero, and known one values are the
1626/// same width as the vector element, and the bit is set only if it is true
1627/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001628void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1629 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001630 assert(V && "No Value?");
1631 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001632 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001633
Craig Topperfde47232017-07-09 07:04:03 +00001634 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001635 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001636 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001637
1638 Type *ScalarTy = V->getType()->getScalarType();
1639 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1640 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1641 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001642 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001643 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001644
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001645 const APInt *C;
1646 if (match(V, m_APInt(C))) {
1647 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001648 Known.One = *C;
1649 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001650 return;
1651 }
1652 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001653 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001654 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001655 return;
1656 }
1657 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001658 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001659 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001660 // We know that CDS must be a vector of integers. Take the intersection of
1661 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001662 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001663 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001664 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001665 Known.Zero &= ~Elt;
1666 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001667 }
1668 return;
1669 }
1670
Pete Cooper35b00d52016-08-13 01:05:32 +00001671 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001672 // We know that CV must be a vector of integers. Take the intersection of
1673 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001674 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001675 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1676 Constant *Element = CV->getAggregateElement(i);
1677 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1678 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001679 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001680 return;
1681 }
Craig Topperb98ee582017-10-21 16:35:39 +00001682 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001683 Known.Zero &= ~Elt;
1684 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001685 }
1686 return;
1687 }
1688
Jingyue Wu12b0c282015-06-15 05:46:29 +00001689 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001690 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001691
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001692 // We can't imply anything about undefs.
1693 if (isa<UndefValue>(V))
1694 return;
1695
1696 // There's no point in looking through other users of ConstantData for
1697 // assumptions. Confirm that we've handled them all.
1698 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1699
Jingyue Wu12b0c282015-06-15 05:46:29 +00001700 // Limit search depth.
1701 // All recursive calls that increase depth must come after this.
1702 if (Depth == MaxDepth)
1703 return;
1704
1705 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1706 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001707 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001708 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001709 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001710 return;
1711 }
1712
Pete Cooper35b00d52016-08-13 01:05:32 +00001713 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001714 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001715
Craig Topperb45eabc2017-04-26 16:39:58 +00001716 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001717 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001718 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001719 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001720 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001721 }
1722
Craig Topperb45eabc2017-04-26 16:39:58 +00001723 // computeKnownBitsFromAssume strictly refines Known.
1724 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001725
1726 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001727 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001728
Craig Topperb45eabc2017-04-26 16:39:58 +00001729 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001730}
1731
Sanjay Patelaee84212014-11-04 16:27:42 +00001732/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001733/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001734/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001735/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001736bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001737 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001738 assert(Depth <= MaxDepth && "Limit Search Depth");
1739
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001740 // Attempt to match against constants.
1741 if (OrZero && match(V, m_Power2OrZero()))
1742 return true;
1743 if (match(V, m_Power2()))
1744 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001745
1746 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1747 // it is shifted off the end then the result is undefined.
1748 if (match(V, m_Shl(m_One(), m_Value())))
1749 return true;
1750
Craig Topperbcfd2d12017-04-20 16:56:25 +00001751 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1752 // the bottom. If it is shifted off the bottom then the result is undefined.
1753 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001754 return true;
1755
1756 // The remaining tests are all recursive, so bail out if we hit the limit.
1757 if (Depth++ == MaxDepth)
1758 return false;
1759
Craig Topper9f008862014-04-15 04:59:12 +00001760 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001761 // A shift left or a logical shift right of a power of two is a power of two
1762 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001763 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001764 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001765 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001766
Pete Cooper35b00d52016-08-13 01:05:32 +00001767 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001768 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001769
Pete Cooper35b00d52016-08-13 01:05:32 +00001770 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001771 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1772 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001773
Duncan Sandsba286d72011-10-26 20:55:21 +00001774 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1775 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001776 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1777 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001778 return true;
1779 // X & (-X) is always a power of two or zero.
1780 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1781 return true;
1782 return false;
1783 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001784
David Majnemerb7d54092013-07-30 21:01:36 +00001785 // Adding a power-of-two or zero to the same power-of-two or zero yields
1786 // either the original power-of-two, a larger power-of-two or zero.
1787 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001788 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00001789 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
1790 Q.IIQ.hasNoSignedWrap(VOBO)) {
David Majnemerb7d54092013-07-30 21:01:36 +00001791 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1792 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001793 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001794 return true;
1795 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1796 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001797 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001798 return true;
1799
1800 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001801 KnownBits LHSBits(BitWidth);
1802 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001803
Craig Topperb45eabc2017-04-26 16:39:58 +00001804 KnownBits RHSBits(BitWidth);
1805 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001806 // If i8 V is a power of two or zero:
1807 // ZeroBits: 1 1 1 0 1 1 1 1
1808 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001809 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001810 // If OrZero isn't set, we cannot give back a zero result.
1811 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001812 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001813 return true;
1814 }
1815 }
David Majnemerbeab5672013-05-18 19:30:37 +00001816
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001817 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001818 // is a power of two only if the first operand is a power of two and not
1819 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001820 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1821 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001822 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001823 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001824 }
1825
Duncan Sandsd3951082011-01-25 09:38:29 +00001826 return false;
1827}
1828
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001829/// Test whether a GEP's result is known to be non-null.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001830///
1831/// Uses properties inherent in a GEP to try to determine whether it is known
1832/// to be non-null.
1833///
1834/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001835static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001836 const Query &Q) {
Manoj Gupta77eeac32018-07-09 22:27:23 +00001837 const Function *F = nullptr;
1838 if (const Instruction *I = dyn_cast<Instruction>(GEP))
1839 F = I->getFunction();
1840
1841 if (!GEP->isInBounds() ||
1842 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001843 return false;
1844
1845 // FIXME: Support vector-GEPs.
1846 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1847
1848 // If the base pointer is non-null, we cannot walk to a null address with an
1849 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001850 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001851 return true;
1852
Chandler Carruth80d3e562012-12-07 02:08:58 +00001853 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1854 // If so, then the GEP cannot produce a null pointer, as doing so would
1855 // inherently violate the inbounds contract within address space zero.
1856 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1857 GTI != GTE; ++GTI) {
1858 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001859 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001860 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1861 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001862 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001863 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1864 if (ElementOffset > 0)
1865 return true;
1866 continue;
1867 }
1868
1869 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001870 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001871 continue;
1872
1873 // Fast path the constant operand case both for efficiency and so we don't
1874 // increment Depth when just zipping down an all-constant GEP.
1875 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1876 if (!OpC->isZero())
1877 return true;
1878 continue;
1879 }
1880
1881 // We post-increment Depth here because while isKnownNonZero increments it
1882 // as well, when we pop back up that increment won't persist. We don't want
1883 // to recurse 10k times just because we have 10k GEP operands. We don't
1884 // bail completely out because we want to handle constant GEPs regardless
1885 // of depth.
1886 if (Depth++ >= MaxDepth)
1887 continue;
1888
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001889 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001890 return true;
1891 }
1892
1893 return false;
1894}
1895
Nikita Popov9fd02a72019-05-08 14:50:01 +00001896static bool isKnownNonNullFromDominatingCondition(const Value *V,
Nuno Lopes404f1062017-09-09 18:23:11 +00001897 const Instruction *CtxI,
1898 const DominatorTree *DT) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00001899 assert(V->getType()->isPointerTy() && "V must be pointer type");
Nuno Lopes404f1062017-09-09 18:23:11 +00001900 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1901
1902 if (!CtxI || !DT)
1903 return false;
1904
1905 unsigned NumUsesExplored = 0;
1906 for (auto *U : V->users()) {
1907 // Avoid massive lists
1908 if (NumUsesExplored >= DomConditionsMaxUses)
1909 break;
1910 NumUsesExplored++;
1911
Nikita Popov9fd02a72019-05-08 14:50:01 +00001912 // If the value is used as an argument to a call or invoke, then argument
1913 // attributes may provide an answer about null-ness.
1914 if (auto CS = ImmutableCallSite(U))
1915 if (auto *CalledFunc = CS.getCalledFunction())
1916 for (const Argument &Arg : CalledFunc->args())
1917 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1918 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1919 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001920
1921 // Consider only compare instructions uniquely controlling a branch
1922 CmpInst::Predicate Pred;
1923 if (!match(const_cast<User *>(U),
1924 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1925 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1926 continue;
1927
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001928 SmallVector<const User *, 4> WorkList;
1929 SmallPtrSet<const User *, 4> Visited;
Nuno Lopes404f1062017-09-09 18:23:11 +00001930 for (auto *CmpU : U->users()) {
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001931 assert(WorkList.empty() && "Should be!");
1932 if (Visited.insert(CmpU).second)
1933 WorkList.push_back(CmpU);
Nuno Lopes404f1062017-09-09 18:23:11 +00001934
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001935 while (!WorkList.empty()) {
1936 auto *Curr = WorkList.pop_back_val();
1937
1938 // If a user is an AND, add all its users to the work list. We only
1939 // propagate "pred != null" condition through AND because it is only
1940 // correct to assume that all conditions of AND are met in true branch.
1941 // TODO: Support similar logic of OR and EQ predicate?
1942 if (Pred == ICmpInst::ICMP_NE)
1943 if (auto *BO = dyn_cast<BinaryOperator>(Curr))
1944 if (BO->getOpcode() == Instruction::And) {
1945 for (auto *BOU : BO->users())
1946 if (Visited.insert(BOU).second)
1947 WorkList.push_back(BOU);
1948 continue;
1949 }
1950
1951 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
1952 assert(BI->isConditional() && "uses a comparison!");
1953
1954 BasicBlock *NonNullSuccessor =
1955 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1956 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1957 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1958 return true;
Max Kazantsev3c284bd2018-08-30 03:39:16 +00001959 } else if (Pred == ICmpInst::ICMP_NE && isGuard(Curr) &&
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001960 DT->dominates(cast<Instruction>(Curr), CtxI)) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001961 return true;
Max Kazantsev2dbbd642018-08-06 11:14:18 +00001962 }
Nuno Lopes404f1062017-09-09 18:23:11 +00001963 }
1964 }
1965 }
1966
1967 return false;
1968}
1969
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001970/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1971/// ensure that the value it's attached to is never Value? 'RangeType' is
1972/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001973static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001974 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1975 assert(NumRanges >= 1);
1976 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001977 ConstantInt *Lower =
1978 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1979 ConstantInt *Upper =
1980 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001981 ConstantRange Range(Lower->getValue(), Upper->getValue());
1982 if (Range.contains(Value))
1983 return false;
1984 }
1985 return true;
1986}
1987
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001988/// Return true if the given value is known to be non-zero when defined. For
1989/// vectors, return true if every element is known to be non-zero when
1990/// defined. For pointers, if the context instruction and dominator tree are
1991/// specified, perform context-sensitive analysis and return true if the
1992/// pointer couldn't possibly be null at the specified instruction.
1993/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001994bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001995 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001996 if (C->isNullValue())
1997 return false;
1998 if (isa<ConstantInt>(C))
1999 // Must be non-zero due to null test above.
2000 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00002001
2002 // For constant vectors, check that all elements are undefined or known
2003 // non-zero to determine that the whole vector is known non-zero.
2004 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
2005 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2006 Constant *Elt = C->getAggregateElement(i);
2007 if (!Elt || Elt->isNullValue())
2008 return false;
2009 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2010 return false;
2011 }
2012 return true;
2013 }
2014
Nuno Lopes404f1062017-09-09 18:23:11 +00002015 // A global variable in address space 0 is non null unless extern weak
2016 // or an absolute symbol reference. Other address spaces may have null as a
2017 // valid address for a global, so we can't assume anything.
2018 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2019 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2020 GV->getType()->getAddressSpace() == 0)
2021 return true;
2022 } else
2023 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00002024 }
2025
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002026 if (auto *I = dyn_cast<Instruction>(V)) {
Florian Hahn19f9e322018-08-17 14:39:04 +00002027 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002028 // If the possible ranges don't contain zero, then the value is
2029 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00002030 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00002031 const APInt ZeroValue(Ty->getBitWidth(), 0);
2032 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2033 return true;
2034 }
2035 }
2036 }
2037
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002038 // Some of the tests below are recursive, so bail out if we hit the limit.
2039 if (Depth++ >= MaxDepth)
2040 return false;
2041
Nuno Lopes404f1062017-09-09 18:23:11 +00002042 // Check for pointer simplifications.
2043 if (V->getType()->isPointerTy()) {
2044 // Alloca never returns null, malloc might.
2045 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2046 return true;
2047
2048 // A byval, inalloca, or nonnull argument is never null.
2049 if (const Argument *A = dyn_cast<Argument>(V))
2050 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
2051 return true;
2052
2053 // A Load tagged with nonnull metadata is never null.
2054 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Florian Hahn19f9e322018-08-17 14:39:04 +00002055 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
Nuno Lopes404f1062017-09-09 18:23:11 +00002056 return true;
2057
Chandler Carruth363ac682019-01-07 05:42:51 +00002058 if (const auto *Call = dyn_cast<CallBase>(V)) {
2059 if (Call->isReturnNonNull())
Nuno Lopes404f1062017-09-09 18:23:11 +00002060 return true;
Chandler Carruth363ac682019-01-07 05:42:51 +00002061 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call))
Karl-Johan Karlssonebaaa2d2018-05-30 15:56:46 +00002062 return isKnownNonZero(RP, Depth, Q);
Piotr Padlewski5642a422018-05-18 23:54:33 +00002063 }
Nuno Lopes404f1062017-09-09 18:23:11 +00002064 }
2065
Duncan Sandsd3951082011-01-25 09:38:29 +00002066
Nuno Lopes404f1062017-09-09 18:23:11 +00002067 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00002068 if (V->getType()->isPointerTy()) {
Nikita Popov9fd02a72019-05-08 14:50:01 +00002069 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2070 return true;
2071
Johannes Doerfert00102c72019-01-26 23:40:35 +00002072 // Look through bitcast operations, GEPs, and int2ptr instructions as they
2073 // do not alter the value, or at least not the nullness property of the
2074 // value, e.g., int2ptr is allowed to zero/sign extend the value.
2075 //
2076 // Note that we have to take special care to avoid looking through
2077 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2078 // as casts that can alter the value, e.g., AddrSpaceCasts.
Pete Cooper35b00d52016-08-13 01:05:32 +00002079 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002080 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00002081 return true;
Johannes Doerfert00102c72019-01-26 23:40:35 +00002082
2083 if (auto *BCO = dyn_cast<BitCastOperator>(V))
2084 return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2085
2086 if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2087 if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()) <=
2088 Q.DL.getTypeSizeInBits(I2P->getDestTy()))
2089 return isKnownNonZero(I2P->getOperand(0), Depth, Q);
Chandler Carruth80d3e562012-12-07 02:08:58 +00002090 }
2091
Johannes Doerfert00102c72019-01-26 23:40:35 +00002092 // Similar to int2ptr above, we can look through ptr2int here if the cast
2093 // is a no-op or an extend and not a truncate.
2094 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2095 if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()) <=
2096 Q.DL.getTypeSizeInBits(P2I->getDestTy()))
2097 return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2098
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002099 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00002100
2101 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00002102 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00002103 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002104 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002105
2106 // ext X != 0 if X != 0.
2107 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002108 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002109
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002110 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00002111 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00002112 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002113 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002114 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Florian Hahn19f9e322018-08-17 14:39:04 +00002115 if (Q.IIQ.hasNoUnsignedWrap(BO))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002116 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002117
Craig Topperb45eabc2017-04-26 16:39:58 +00002118 KnownBits Known(BitWidth);
2119 computeKnownBits(X, Known, Depth, Q);
2120 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00002121 return true;
2122 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00002123 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00002124 // defined if the sign bit is shifted off the end.
2125 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002126 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002127 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002128 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002129 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002130
Craig Topper6e11a052017-05-08 16:22:48 +00002131 KnownBits Known = computeKnownBits(X, Depth, Q);
2132 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002133 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002134
2135 // If the shifter operand is a constant, and all of the bits shifted
2136 // out are known to be zero, and X is known non-zero then at least one
2137 // non-zero bit must remain.
2138 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002139 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2140 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002141 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002142 return true;
2143 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002144 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002145 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002146 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002147 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002148 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002149 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002150 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002151 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002152 // X + Y.
2153 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002154 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2155 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002156
2157 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002158 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002159 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002160 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002161 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002162
2163 // If X and Y are both negative (as signed values) then their sum is not
2164 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002165 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002166 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2167 // The sign bit of X is set. If some other bit is set then X is not equal
2168 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002169 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002170 return true;
2171 // The sign bit of Y is set. If some other bit is set then Y is not equal
2172 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002173 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002174 return true;
2175 }
2176
2177 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002178 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002179 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002180 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002181 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002182 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002183 return true;
2184 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002185 // X * Y.
2186 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002187 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002188 // If X and Y are non-zero then so is X * Y as long as the multiplication
2189 // does not overflow.
Florian Hahn19f9e322018-08-17 14:39:04 +00002190 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002191 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002192 return true;
2193 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002194 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002195 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002196 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2197 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002198 return true;
2199 }
James Molloy897048b2015-09-29 14:08:45 +00002200 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002201 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002202 // Try and detect a recurrence that monotonically increases from a
2203 // starting value, as these are common as induction variables.
2204 if (PN->getNumIncomingValues() == 2) {
2205 Value *Start = PN->getIncomingValue(0);
2206 Value *Induction = PN->getIncomingValue(1);
2207 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2208 std::swap(Start, Induction);
2209 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2210 if (!C->isZero() && !C->isNegative()) {
2211 ConstantInt *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00002212 if (Q.IIQ.UseInstrInfo &&
2213 (match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
James Molloy897048b2015-09-29 14:08:45 +00002214 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2215 !X->isNegative())
2216 return true;
2217 }
2218 }
2219 }
Jun Bum Limca832662016-02-01 17:03:07 +00002220 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002221 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002222 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002223 });
2224 if (AllNonZeroConstants)
2225 return true;
James Molloy897048b2015-09-29 14:08:45 +00002226 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002227
Craig Topperb45eabc2017-04-26 16:39:58 +00002228 KnownBits Known(BitWidth);
2229 computeKnownBits(V, Known, Depth, Q);
2230 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002231}
2232
James Molloy1d88d6f2015-10-22 13:18:42 +00002233/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002234static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2235 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002236 if (!BO || BO->getOpcode() != Instruction::Add)
2237 return false;
2238 Value *Op = nullptr;
2239 if (V2 == BO->getOperand(0))
2240 Op = BO->getOperand(1);
2241 else if (V2 == BO->getOperand(1))
2242 Op = BO->getOperand(0);
2243 else
2244 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002245 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002246}
2247
2248/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002249static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002250 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002251 return false;
2252 if (V1->getType() != V2->getType())
2253 // We can't look through casts yet.
2254 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002255 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002256 return true;
2257
Craig Topper3002d5b2017-06-06 07:13:15 +00002258 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002259 // Are any known bits in V1 contradictory to known bits in V2? If V1
2260 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002261 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2262 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002263
Craig Topper8365df82017-06-06 07:13:09 +00002264 if (Known1.Zero.intersects(Known2.One) ||
2265 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002266 return true;
2267 }
2268 return false;
2269}
2270
Sanjay Patelaee84212014-11-04 16:27:42 +00002271/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2272/// simplify operations downstream. Mask is known to be zero for bits that V
2273/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002274///
2275/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002276/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002277/// where V is a vector, the mask, known zero, and known one values are the
2278/// same width as the vector element, and the bit is set only if it is true
2279/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002280bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002281 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002282 KnownBits Known(Mask.getBitWidth());
2283 computeKnownBits(V, Known, Depth, Q);
2284 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002285}
2286
Craig Topperbec15b62018-08-22 23:27:50 +00002287// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2288// Returns the input and lower/upper bounds.
2289static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2290 const APInt *&CLow, const APInt *&CHigh) {
Craig Topper15f86922018-08-23 17:15:02 +00002291 assert(isa<Operator>(Select) &&
2292 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
Craig Topperdfa176e2018-08-23 17:45:53 +00002293 "Input should be a Select!");
Craig Topperbec15b62018-08-22 23:27:50 +00002294
2295 const Value *LHS, *RHS, *LHS2, *RHS2;
2296 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2297 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2298 return false;
2299
2300 if (!match(RHS, m_APInt(CLow)))
2301 return false;
2302
2303 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2304 if (getInverseMinMaxFlavor(SPF) != SPF2)
2305 return false;
2306
2307 if (!match(RHS2, m_APInt(CHigh)))
2308 return false;
2309
2310 if (SPF == SPF_SMIN)
2311 std::swap(CLow, CHigh);
2312
2313 In = LHS2;
2314 return CLow->sle(*CHigh);
2315}
2316
Sanjay Patela06d9892016-06-22 19:20:59 +00002317/// For vector constants, loop over the elements and find the constant with the
2318/// minimum number of sign bits. Return 0 if the value is not a vector constant
2319/// or if any element was not analyzed; otherwise, return the count for the
2320/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002321static unsigned computeNumSignBitsVectorConstant(const Value *V,
2322 unsigned TyBits) {
2323 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002324 if (!CV || !CV->getType()->isVectorTy())
2325 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002326
Sanjay Patela06d9892016-06-22 19:20:59 +00002327 unsigned MinSignBits = TyBits;
2328 unsigned NumElts = CV->getType()->getVectorNumElements();
2329 for (unsigned i = 0; i != NumElts; ++i) {
2330 // If we find a non-ConstantInt, bail out.
2331 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2332 if (!Elt)
2333 return 0;
2334
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002335 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002336 }
2337
2338 return MinSignBits;
2339}
Chris Lattner965c7692008-06-02 01:18:21 +00002340
Sanjoy Das39a684d2017-02-25 20:30:45 +00002341static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2342 const Query &Q);
2343
2344static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2345 const Query &Q) {
2346 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2347 assert(Result > 0 && "At least one sign bit needs to be present!");
2348 return Result;
2349}
2350
Sanjay Patelaee84212014-11-04 16:27:42 +00002351/// Return the number of times the sign bit of the register is replicated into
2352/// the other bits. We know that at least 1 bit is always equal to the sign bit
2353/// (itself), but other cases can give us information. For example, immediately
2354/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002355/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002356/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002357static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2358 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002359 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002360
2361 // We return the minimum number of sign bits that are guaranteed to be present
2362 // in V, so for undef we have to conservatively return 1. We don't have the
2363 // same behavior for poison though -- that's a FIXME today.
2364
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002365 Type *ScalarTy = V->getType()->getScalarType();
2366 unsigned TyBits = ScalarTy->isPointerTy() ?
2367 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2368 Q.DL.getTypeSizeInBits(ScalarTy);
2369
Chris Lattner965c7692008-06-02 01:18:21 +00002370 unsigned Tmp, Tmp2;
2371 unsigned FirstAnswer = 1;
2372
Jay Foada0653a32014-05-14 21:14:37 +00002373 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002374 // below.
2375
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002376 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002377 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002378
Pete Cooper35b00d52016-08-13 01:05:32 +00002379 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002380 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002381 default: break;
2382 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002383 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002384 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002385
Nadav Rotemc99a3872015-03-06 00:23:58 +00002386 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002387 const APInt *Denominator;
2388 // sdiv X, C -> adds log(C) sign bits.
2389 if (match(U->getOperand(1), m_APInt(Denominator))) {
2390
2391 // Ignore non-positive denominator.
2392 if (!Denominator->isStrictlyPositive())
2393 break;
2394
2395 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002396 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002397
2398 // Add floor(log(C)) bits to the numerator bits.
2399 return std::min(TyBits, NumBits + Denominator->logBase2());
2400 }
2401 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002402 }
2403
2404 case Instruction::SRem: {
2405 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002406 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2407 // positive constant. This let us put a lower bound on the number of sign
2408 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002409 if (match(U->getOperand(1), m_APInt(Denominator))) {
2410
2411 // Ignore non-positive denominator.
2412 if (!Denominator->isStrictlyPositive())
2413 break;
2414
2415 // Calculate the incoming numerator bits. SRem by a positive constant
2416 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002417 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002418 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002419
2420 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002421 // denominator. Given that the denominator is positive, there are two
2422 // cases:
2423 //
2424 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2425 // (1 << ceilLogBase2(C)).
2426 //
2427 // 2. the numerator is negative. Then the result range is (-C,0] and
2428 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2429 //
2430 // Thus a lower bound on the number of sign bits is `TyBits -
2431 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002432
Sanjoy Dase561fee2015-03-25 22:33:53 +00002433 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002434 return std::max(NumrBits, ResBits);
2435 }
2436 break;
2437 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002438
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002439 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002440 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002441 // ashr X, C -> adds C sign bits. Vectors too.
2442 const APInt *ShAmt;
2443 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002444 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002445 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002446 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002447 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002448 if (Tmp > TyBits) Tmp = TyBits;
2449 }
2450 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002451 }
2452 case Instruction::Shl: {
2453 const APInt *ShAmt;
2454 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002455 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002456 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002457 if (ShAmt->uge(TyBits) || // Bad shift.
2458 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002459 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002460 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002461 }
2462 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002463 }
Chris Lattner965c7692008-06-02 01:18:21 +00002464 case Instruction::And:
2465 case Instruction::Or:
2466 case Instruction::Xor: // NOT is handled here.
2467 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002468 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002469 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002470 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002471 FirstAnswer = std::min(Tmp, Tmp2);
2472 // We computed what we know about the sign bits as our first
2473 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002474 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002475 }
2476 break;
2477
Craig Topperbec15b62018-08-22 23:27:50 +00002478 case Instruction::Select: {
2479 // If we have a clamp pattern, we know that the number of sign bits will be
2480 // the minimum of the clamp min/max range.
2481 const Value *X;
2482 const APInt *CLow, *CHigh;
2483 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
2484 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
2485
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002486 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002487 if (Tmp == 1) break;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002488 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002489 return std::min(Tmp, Tmp2);
Craig Topperbec15b62018-08-22 23:27:50 +00002490 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002491
Chris Lattner965c7692008-06-02 01:18:21 +00002492 case Instruction::Add:
2493 // Add can have at most one carry bit. Thus we know that the output
2494 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002495 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002496 if (Tmp == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002497
Chris Lattner965c7692008-06-02 01:18:21 +00002498 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002499 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002500 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002501 KnownBits Known(TyBits);
2502 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002503
Chris Lattner965c7692008-06-02 01:18:21 +00002504 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2505 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002506 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002507 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002508
Chris Lattner965c7692008-06-02 01:18:21 +00002509 // If we are subtracting one from a positive number, there is no carry
2510 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002511 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002512 return Tmp;
2513 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002514
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002515 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002516 if (Tmp2 == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002517 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002518
Chris Lattner965c7692008-06-02 01:18:21 +00002519 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002520 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002521 if (Tmp2 == 1) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002522
Chris Lattner965c7692008-06-02 01:18:21 +00002523 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002524 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002525 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002526 KnownBits Known(TyBits);
2527 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002528 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2529 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002530 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002531 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002532
Chris Lattner965c7692008-06-02 01:18:21 +00002533 // If the input is known to be positive (the sign bit is known clear),
2534 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002535 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002536 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002537
Chris Lattner965c7692008-06-02 01:18:21 +00002538 // Otherwise, we treat this like a SUB.
2539 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002540
Chris Lattner965c7692008-06-02 01:18:21 +00002541 // Sub can have at most one carry bit. Thus we know that the output
2542 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002543 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002544 if (Tmp == 1) break;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002545 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002546
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002547 case Instruction::Mul: {
2548 // The output of the Mul can be at most twice the valid bits in the inputs.
2549 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002550 if (SignBitsOp0 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002551 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Stanislav Mekhanoshinb8269a92018-07-25 16:39:24 +00002552 if (SignBitsOp1 == 1) break;
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002553 unsigned OutValidBits =
2554 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2555 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2556 }
2557
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002558 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002559 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002560 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002561 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002562 if (NumIncomingValues > 4) break;
2563 // Unreachable blocks may have zero-operand PHI nodes.
2564 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002565
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002566 // Take the minimum of all incoming values. This can't infinitely loop
2567 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002568 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002569 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002570 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002571 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002572 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002573 }
2574 return Tmp;
2575 }
2576
Chris Lattner965c7692008-06-02 01:18:21 +00002577 case Instruction::Trunc:
2578 // FIXME: it's tricky to do anything useful for this, but it is an important
2579 // case for targets like X86.
2580 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002581
2582 case Instruction::ExtractElement:
2583 // Look through extract element. At the moment we keep this simple and skip
2584 // tracking the specific element. But at least we might find information
2585 // valid for all elements of the vector (for example if vector is sign
2586 // extended, shifted, etc).
2587 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002588
Sanjay Patela68096c2018-11-02 15:51:47 +00002589 case Instruction::ShuffleVector: {
Sanjay Patelcac28b42018-11-03 13:18:55 +00002590 // TODO: This is copied almost directly from the SelectionDAG version of
2591 // ComputeNumSignBits. It would be better if we could share common
2592 // code. If not, make sure that changes are translated to the DAG.
2593
2594 // Collect the minimum number of sign bits that are shared by every vector
2595 // element referenced by the shuffle.
2596 auto *Shuf = cast<ShuffleVectorInst>(U);
2597 int NumElts = Shuf->getOperand(0)->getType()->getVectorNumElements();
2598 int NumMaskElts = Shuf->getMask()->getType()->getVectorNumElements();
2599 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2600 for (int i = 0; i != NumMaskElts; ++i) {
2601 int M = Shuf->getMaskValue(i);
2602 assert(M < NumElts * 2 && "Invalid shuffle mask constant");
2603 // For undef elements, we don't know anything about the common state of
2604 // the shuffle result.
2605 if (M == -1)
2606 return 1;
2607 if (M < NumElts)
2608 DemandedLHS.setBit(M % NumElts);
2609 else
2610 DemandedRHS.setBit(M % NumElts);
2611 }
2612 Tmp = std::numeric_limits<unsigned>::max();
2613 if (!!DemandedLHS)
2614 Tmp = ComputeNumSignBits(Shuf->getOperand(0), Depth + 1, Q);
2615 if (!!DemandedRHS) {
2616 Tmp2 = ComputeNumSignBits(Shuf->getOperand(1), Depth + 1, Q);
2617 Tmp = std::min(Tmp, Tmp2);
2618 }
2619 // If we don't know anything, early out and try computeKnownBits fall-back.
2620 if (Tmp == 1)
Sanjay Patelcc9e4012018-10-26 21:05:14 +00002621 break;
Sanjay Patelcac28b42018-11-03 13:18:55 +00002622 assert(Tmp <= V->getType()->getScalarSizeInBits() &&
2623 "Failed to determine minimum sign bits");
2624 return Tmp;
Chris Lattner965c7692008-06-02 01:18:21 +00002625 }
Sanjay Patela68096c2018-11-02 15:51:47 +00002626 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002627
Chris Lattner965c7692008-06-02 01:18:21 +00002628 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2629 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002630
2631 // If we can examine all elements of a vector constant successfully, we're
2632 // done (we can't do any better than that). If not, keep trying.
2633 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2634 return VecSignBits;
2635
Craig Topperb45eabc2017-04-26 16:39:58 +00002636 KnownBits Known(TyBits);
2637 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002638
Sanjay Patele0536212016-06-23 17:41:59 +00002639 // If we know that the sign bit is either zero or one, determine the number of
2640 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002641 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002642}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002643
Sanjay Patelaee84212014-11-04 16:27:42 +00002644/// This function computes the integer multiple of Base that equals V.
2645/// If successful, it returns true and returns the multiple in
2646/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002647/// through SExt instructions only if LookThroughSExt is true.
2648bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002649 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002650 const unsigned MaxDepth = 6;
2651
Dan Gohman6a976bb2009-11-18 00:58:27 +00002652 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002653 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002654 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002655
Chris Lattner229907c2011-07-18 04:54:35 +00002656 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002657
Dan Gohman6a976bb2009-11-18 00:58:27 +00002658 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002659
2660 if (Base == 0)
2661 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002662
Victor Hernandez47444882009-11-10 08:28:35 +00002663 if (Base == 1) {
2664 Multiple = V;
2665 return true;
2666 }
2667
2668 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2669 Constant *BaseVal = ConstantInt::get(T, Base);
2670 if (CO && CO == BaseVal) {
2671 // Multiple is 1.
2672 Multiple = ConstantInt::get(T, 1);
2673 return true;
2674 }
2675
2676 if (CI && CI->getZExtValue() % Base == 0) {
2677 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002678 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002679 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002680
Victor Hernandez47444882009-11-10 08:28:35 +00002681 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002682
Victor Hernandez47444882009-11-10 08:28:35 +00002683 Operator *I = dyn_cast<Operator>(V);
2684 if (!I) return false;
2685
2686 switch (I->getOpcode()) {
2687 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002688 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002689 if (!LookThroughSExt) return false;
2690 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002691 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002692 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002693 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2694 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002695 case Instruction::Shl:
2696 case Instruction::Mul: {
2697 Value *Op0 = I->getOperand(0);
2698 Value *Op1 = I->getOperand(1);
2699
2700 if (I->getOpcode() == Instruction::Shl) {
2701 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2702 if (!Op1CI) return false;
2703 // Turn Op0 << Op1 into Op0 * 2^Op1
2704 APInt Op1Int = Op1CI->getValue();
2705 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002706 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002707 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002708 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002709 }
2710
Craig Topper9f008862014-04-15 04:59:12 +00002711 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002712 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2713 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2714 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002715 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002716 MulC->getType()->getPrimitiveSizeInBits())
2717 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002718 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002719 MulC->getType()->getPrimitiveSizeInBits())
2720 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002721
Chris Lattner72d283c2010-09-05 17:20:46 +00002722 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2723 Multiple = ConstantExpr::getMul(MulC, Op1C);
2724 return true;
2725 }
Victor Hernandez47444882009-11-10 08:28:35 +00002726
2727 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2728 if (Mul0CI->getValue() == 1) {
2729 // V == Base * Op1, so return Op1
2730 Multiple = Op1;
2731 return true;
2732 }
2733 }
2734
Craig Topper9f008862014-04-15 04:59:12 +00002735 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002736 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2737 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2738 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002739 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002740 MulC->getType()->getPrimitiveSizeInBits())
2741 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002742 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002743 MulC->getType()->getPrimitiveSizeInBits())
2744 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002745
Chris Lattner72d283c2010-09-05 17:20:46 +00002746 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2747 Multiple = ConstantExpr::getMul(MulC, Op0C);
2748 return true;
2749 }
Victor Hernandez47444882009-11-10 08:28:35 +00002750
2751 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2752 if (Mul1CI->getValue() == 1) {
2753 // V == Base * Op0, so return Op0
2754 Multiple = Op0;
2755 return true;
2756 }
2757 }
Victor Hernandez47444882009-11-10 08:28:35 +00002758 }
2759 }
2760
2761 // We could not determine if V is a multiple of Base.
2762 return false;
2763}
2764
David Majnemerb4b27232016-04-19 19:10:21 +00002765Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2766 const TargetLibraryInfo *TLI) {
2767 const Function *F = ICS.getCalledFunction();
2768 if (!F)
2769 return Intrinsic::not_intrinsic;
2770
2771 if (F->isIntrinsic())
2772 return F->getIntrinsicID();
2773
2774 if (!TLI)
2775 return Intrinsic::not_intrinsic;
2776
David L. Jonesd21529f2017-01-23 23:16:46 +00002777 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002778 // We're going to make assumptions on the semantics of the functions, check
2779 // that the target knows that it's available in this environment and it does
2780 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002781 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2782 return Intrinsic::not_intrinsic;
2783
2784 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002785 return Intrinsic::not_intrinsic;
2786
2787 // Otherwise check if we have a call to a function that can be turned into a
2788 // vector intrinsic.
2789 switch (Func) {
2790 default:
2791 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002792 case LibFunc_sin:
2793 case LibFunc_sinf:
2794 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002795 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002796 case LibFunc_cos:
2797 case LibFunc_cosf:
2798 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002799 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002800 case LibFunc_exp:
2801 case LibFunc_expf:
2802 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002803 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002804 case LibFunc_exp2:
2805 case LibFunc_exp2f:
2806 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002807 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002808 case LibFunc_log:
2809 case LibFunc_logf:
2810 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002811 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002812 case LibFunc_log10:
2813 case LibFunc_log10f:
2814 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002815 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002816 case LibFunc_log2:
2817 case LibFunc_log2f:
2818 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002819 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002820 case LibFunc_fabs:
2821 case LibFunc_fabsf:
2822 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002823 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002824 case LibFunc_fmin:
2825 case LibFunc_fminf:
2826 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002827 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002828 case LibFunc_fmax:
2829 case LibFunc_fmaxf:
2830 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002831 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002832 case LibFunc_copysign:
2833 case LibFunc_copysignf:
2834 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002835 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002836 case LibFunc_floor:
2837 case LibFunc_floorf:
2838 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002839 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002840 case LibFunc_ceil:
2841 case LibFunc_ceilf:
2842 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002843 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002844 case LibFunc_trunc:
2845 case LibFunc_truncf:
2846 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002847 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002848 case LibFunc_rint:
2849 case LibFunc_rintf:
2850 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002851 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002852 case LibFunc_nearbyint:
2853 case LibFunc_nearbyintf:
2854 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002855 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002856 case LibFunc_round:
2857 case LibFunc_roundf:
2858 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002859 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002860 case LibFunc_pow:
2861 case LibFunc_powf:
2862 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002863 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002864 case LibFunc_sqrt:
2865 case LibFunc_sqrtf:
2866 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002867 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002868 }
2869
2870 return Intrinsic::not_intrinsic;
2871}
2872
Sanjay Patelaee84212014-11-04 16:27:42 +00002873/// Return true if we can prove that the specified FP value is never equal to
2874/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002875///
2876/// NOTE: this function will need to be revisited when we support non-default
2877/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002878bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2879 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002880 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002881 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002882
Sanjay Patel20df88a2017-11-13 17:56:23 +00002883 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002884 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002885 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002886
Sanjay Patel20df88a2017-11-13 17:56:23 +00002887 auto *Op = dyn_cast<Operator>(V);
2888 if (!Op)
2889 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002890
Sanjay Patel20df88a2017-11-13 17:56:23 +00002891 // Check if the nsz fast-math flag is set.
2892 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002893 if (FPO->hasNoSignedZeros())
2894 return true;
2895
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002896 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002897 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002898 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002899
Chris Lattnera12a6de2008-06-02 01:29:46 +00002900 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002901 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002902 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002903
Sanjay Patel20df88a2017-11-13 17:56:23 +00002904 if (auto *Call = dyn_cast<CallInst>(Op)) {
2905 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002906 switch (IID) {
2907 default:
2908 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002909 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002910 case Intrinsic::sqrt:
Matt Arsenault56b31d82018-08-06 15:16:26 +00002911 case Intrinsic::canonicalize:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002912 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002913 // fabs(x) != -0.0
2914 case Intrinsic::fabs:
2915 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002916 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002917 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002918
Chris Lattnera12a6de2008-06-02 01:29:46 +00002919 return false;
2920}
2921
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002922/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2923/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2924/// bit despite comparing equal.
2925static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2926 const TargetLibraryInfo *TLI,
2927 bool SignBitOnly,
2928 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002929 // TODO: This function does not do the right thing when SignBitOnly is true
2930 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2931 // which flips the sign bits of NaNs. See
2932 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2933
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002934 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2935 return !CFP->getValueAPF().isNegative() ||
2936 (!SignBitOnly && CFP->getValueAPF().isZero());
2937 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002938
Craig Topper69c89722018-02-26 22:33:17 +00002939 // Handle vector of constants.
2940 if (auto *CV = dyn_cast<Constant>(V)) {
2941 if (CV->getType()->isVectorTy()) {
2942 unsigned NumElts = CV->getType()->getVectorNumElements();
2943 for (unsigned i = 0; i != NumElts; ++i) {
2944 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2945 if (!CFP)
2946 return false;
2947 if (CFP->getValueAPF().isNegative() &&
2948 (SignBitOnly || !CFP->getValueAPF().isZero()))
2949 return false;
2950 }
2951
2952 // All non-negative ConstantFPs.
2953 return true;
2954 }
2955 }
2956
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002957 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002958 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002959
2960 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002961 if (!I)
2962 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002963
2964 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002965 default:
2966 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002967 // Unsigned integers are always nonnegative.
2968 case Instruction::UIToFP:
2969 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002970 case Instruction::FMul:
2971 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002972 if (I->getOperand(0) == I->getOperand(1) &&
2973 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002974 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002975
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002976 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002977 case Instruction::FAdd:
2978 case Instruction::FDiv:
2979 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002980 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2981 Depth + 1) &&
2982 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2983 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002984 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002985 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2986 Depth + 1) &&
2987 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2988 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002989 case Instruction::FPExt:
2990 case Instruction::FPTrunc:
2991 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002992 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2993 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002994 case Instruction::ExtractElement:
2995 // Look through extract element. At the moment we keep this simple and skip
2996 // tracking the specific element. But at least we might find information
2997 // valid for all elements of the vector.
2998 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2999 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003000 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003001 const auto *CI = cast<CallInst>(I);
3002 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00003003 switch (IID) {
3004 default:
3005 break;
3006 case Intrinsic::maxnum:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003007 return (isKnownNeverNaN(I->getOperand(0), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003008 cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI,
3009 SignBitOnly, Depth + 1)) ||
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003010 (isKnownNeverNaN(I->getOperand(1), TLI) &&
Sanjay Patelf9a0d592018-08-02 13:46:20 +00003011 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3012 SignBitOnly, Depth + 1));
3013
Thomas Livelyc3392502018-10-19 19:01:26 +00003014 case Intrinsic::maximum:
3015 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3016 Depth + 1) ||
3017 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3018 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003019 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00003020 case Intrinsic::minimum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003021 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3022 Depth + 1) &&
3023 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3024 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003025 case Intrinsic::exp:
3026 case Intrinsic::exp2:
3027 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00003028 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00003029
3030 case Intrinsic::sqrt:
3031 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3032 if (!SignBitOnly)
3033 return true;
3034 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3035 CannotBeNegativeZero(CI->getOperand(0), TLI));
3036
David Majnemer3ee5f342016-04-13 06:55:52 +00003037 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00003038 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00003039 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00003040 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00003041 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003042 }
Justin Lebar322c1272017-01-27 00:58:34 +00003043 // TODO: This is not correct. Given that exp is an integer, here are the
3044 // ways that pow can return a negative value:
3045 //
3046 // pow(x, exp) --> negative if exp is odd and x is negative.
3047 // pow(-0, exp) --> -inf if exp is negative odd.
3048 // pow(-0, exp) --> -0 if exp is positive odd.
3049 // pow(-inf, exp) --> -0 if exp is negative odd.
3050 // pow(-inf, exp) --> -inf if exp is positive odd.
3051 //
3052 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3053 // but we must return false if x == -0. Unfortunately we do not currently
3054 // have a way of expressing this constraint. See details in
3055 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003056 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3057 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00003058
David Majnemer3ee5f342016-04-13 06:55:52 +00003059 case Intrinsic::fma:
3060 case Intrinsic::fmuladd:
3061 // x*x+y is non-negative if y is non-negative.
3062 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003063 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3064 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3065 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00003066 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003067 break;
3068 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003069 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003070}
3071
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00003072bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3073 const TargetLibraryInfo *TLI) {
3074 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3075}
3076
3077bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3078 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3079}
3080
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003081bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3082 unsigned Depth) {
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003083 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3084
3085 // If we're told that NaNs won't happen, assume they won't.
3086 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3087 if (FPMathOp->hasNoNaNs())
3088 return true;
3089
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003090 // Handle scalar constants.
3091 if (auto *CFP = dyn_cast<ConstantFP>(V))
3092 return !CFP->isNaN();
3093
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003094 if (Depth == MaxDepth)
3095 return false;
3096
Matt Arsenault450fcc72018-08-20 16:51:00 +00003097 if (auto *Inst = dyn_cast<Instruction>(V)) {
3098 switch (Inst->getOpcode()) {
3099 case Instruction::FAdd:
3100 case Instruction::FMul:
3101 case Instruction::FSub:
3102 case Instruction::FDiv:
3103 case Instruction::FRem: {
3104 // TODO: Need isKnownNeverInfinity
3105 return false;
3106 }
3107 case Instruction::Select: {
3108 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3109 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3110 }
3111 case Instruction::SIToFP:
3112 case Instruction::UIToFP:
3113 return true;
3114 case Instruction::FPTrunc:
3115 case Instruction::FPExt:
3116 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3117 default:
3118 break;
3119 }
3120 }
3121
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003122 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3123 switch (II->getIntrinsicID()) {
3124 case Intrinsic::canonicalize:
3125 case Intrinsic::fabs:
3126 case Intrinsic::copysign:
Matt Arsenault450fcc72018-08-20 16:51:00 +00003127 case Intrinsic::exp:
3128 case Intrinsic::exp2:
3129 case Intrinsic::floor:
3130 case Intrinsic::ceil:
3131 case Intrinsic::trunc:
3132 case Intrinsic::rint:
3133 case Intrinsic::nearbyint:
3134 case Intrinsic::round:
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003135 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3136 case Intrinsic::sqrt:
3137 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3138 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
Sanjay Patele088d032019-05-07 22:58:31 +00003139 case Intrinsic::minnum:
3140 case Intrinsic::maxnum:
3141 // If either operand is not NaN, the result is not NaN.
3142 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3143 isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00003144 default:
3145 return false;
3146 }
3147 }
3148
Sanjay Patel6840c5f2017-09-05 23:13:13 +00003149 // Bail out for constant expressions, but try to handle vector constants.
3150 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
3151 return false;
3152
3153 // For vectors, verify that each element is not NaN.
3154 unsigned NumElts = V->getType()->getVectorNumElements();
3155 for (unsigned i = 0; i != NumElts; ++i) {
3156 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3157 if (!Elt)
3158 return false;
3159 if (isa<UndefValue>(Elt))
3160 continue;
3161 auto *CElt = dyn_cast<ConstantFP>(Elt);
3162 if (!CElt || CElt->isNaN())
3163 return false;
3164 }
3165 // All elements were confirmed not-NaN or undefined.
3166 return true;
3167}
3168
Chris Lattner9cb10352010-12-26 20:15:01 +00003169Value *llvm::isBytewiseValue(Value *V) {
JF Bastien73d8e4e2018-09-21 05:17:42 +00003170
Chris Lattner9cb10352010-12-26 20:15:01 +00003171 // All byte-wide stores are splatable, even of arbitrary variables.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003172 if (V->getType()->isIntegerTy(8))
3173 return V;
3174
3175 LLVMContext &Ctx = V->getContext();
3176
3177 // Undef don't care.
3178 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3179 if (isa<UndefValue>(V))
3180 return UndefInt8;
3181
3182 Constant *C = dyn_cast<Constant>(V);
3183 if (!C) {
3184 // Conceptually, we could handle things like:
3185 // %a = zext i8 %X to i16
3186 // %b = shl i16 %a, 8
3187 // %c = or i16 %a, %b
3188 // but until there is an example that actually needs this, it doesn't seem
3189 // worth worrying about.
3190 return nullptr;
3191 }
Chris Lattneracf6b072011-02-19 19:35:49 +00003192
3193 // Handle 'null' ConstantArrayZero etc.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003194 if (C->isNullValue())
3195 return Constant::getNullValue(Type::getInt8Ty(Ctx));
Craig Topper1bef2c82012-12-22 19:15:35 +00003196
JF Bastien73d8e4e2018-09-21 05:17:42 +00003197 // Constant floating-point values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00003198 // corresponding integer value is "byteable". An important case is 0.0.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003199 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3200 Type *Ty = nullptr;
3201 if (CFP->getType()->isHalfTy())
3202 Ty = Type::getInt16Ty(Ctx);
3203 else if (CFP->getType()->isFloatTy())
3204 Ty = Type::getInt32Ty(Ctx);
3205 else if (CFP->getType()->isDoubleTy())
3206 Ty = Type::getInt64Ty(Ctx);
Chris Lattner9cb10352010-12-26 20:15:01 +00003207 // Don't handle long double formats, which have strange constraints.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003208 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty)) : nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003209 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003210
Benjamin Kramer17d90152015-02-07 19:29:02 +00003211 // We can handle constant integers that are multiple of 8 bits.
JF Bastien73d8e4e2018-09-21 05:17:42 +00003212 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00003213 if (CI->getBitWidth() % 8 == 0) {
3214 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Benjamin Kramerb4b51502015-03-25 16:49:59 +00003215 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00003216 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003217 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00003218 }
3219 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003220
JF Bastien73d8e4e2018-09-21 05:17:42 +00003221 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3222 if (LHS == RHS)
3223 return LHS;
3224 if (!LHS || !RHS)
Craig Topper9f008862014-04-15 04:59:12 +00003225 return nullptr;
JF Bastien73d8e4e2018-09-21 05:17:42 +00003226 if (LHS == UndefInt8)
3227 return RHS;
3228 if (RHS == UndefInt8)
3229 return LHS;
3230 return nullptr;
3231 };
Craig Topper1bef2c82012-12-22 19:15:35 +00003232
JF Bastien73d8e4e2018-09-21 05:17:42 +00003233 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3234 Value *Val = UndefInt8;
3235 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3236 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I)))))
Craig Topper9f008862014-04-15 04:59:12 +00003237 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003238 return Val;
3239 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00003240
JF Bastien73d8e4e2018-09-21 05:17:42 +00003241 if (isa<ConstantVector>(C)) {
3242 Constant *Splat = cast<ConstantVector>(C)->getSplatValue();
3243 return Splat ? isBytewiseValue(Splat) : nullptr;
3244 }
3245
3246 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3247 Value *Val = UndefInt8;
3248 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3249 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I)))))
3250 return nullptr;
3251 return Val;
3252 }
3253
3254 // Don't try to handle the handful of other constants.
Craig Topper9f008862014-04-15 04:59:12 +00003255 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00003256}
3257
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003258// This is the recursive version of BuildSubAggregate. It takes a few different
3259// arguments. Idxs is the index within the nested struct From that we are
3260// looking at now (which is of type IndexedType). IdxSkip is the number of
3261// indices from Idxs that should be left out when inserting into the resulting
3262// struct. To is the result struct built so far, new insertvalue instructions
3263// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00003264static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00003265 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003266 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003267 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003268 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003269 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003270 // Save the original To argument so we can modify it
3271 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003272 // General case, the type indexed by Idxs is a struct
3273 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3274 // Process each struct element recursively
3275 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003276 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003277 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003278 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003279 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003280 if (!To) {
3281 // Couldn't find any inserted value for this index? Cleanup
3282 while (PrevTo != OrigTo) {
3283 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3284 PrevTo = Del->getAggregateOperand();
3285 Del->eraseFromParent();
3286 }
3287 // Stop processing elements
3288 break;
3289 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003290 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00003291 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003292 if (To)
3293 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003294 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003295 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3296 // the struct's elements had a value that was inserted directly. In the latter
3297 // case, perhaps we can't determine each of the subelements individually, but
3298 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00003299
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003300 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003301 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003302
3303 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003304 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003305
Vedant Kumard3196742018-02-28 19:08:52 +00003306 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003307 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3308 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003309}
3310
3311// This helper takes a nested struct and extracts a part of it (which is again a
3312// struct) into a new value. For example, given the struct:
3313// { a, { b, { c, d }, e } }
3314// and the indices "1, 1" this returns
3315// { c, d }.
3316//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003317// It does this by inserting an insertvalue for each element in the resulting
3318// struct, as opposed to just inserting a single struct. This will only work if
3319// each of the elements of the substruct are known (ie, inserted into From by an
3320// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003321//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003322// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003323static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003324 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003325 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003326 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003327 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003328 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003329 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003330 unsigned IdxSkip = Idxs.size();
3331
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003332 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003333}
3334
Vedant Kumard3196742018-02-28 19:08:52 +00003335/// Given an aggregate and a sequence of indices, see if the scalar value
3336/// indexed is already around as a register, for example if it was inserted
3337/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003338///
3339/// If InsertBefore is not null, this function will duplicate (modified)
3340/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003341Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3342 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003343 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003344 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003345 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003346 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003347 // We have indices, so V should have an indexable type.
3348 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3349 "Not looking at a struct or array?");
3350 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3351 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003352
Chris Lattner67058832012-01-25 06:48:06 +00003353 if (Constant *C = dyn_cast<Constant>(V)) {
3354 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003355 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003356 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3357 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003358
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003359 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003360 // Loop the indices for the insertvalue instruction in parallel with the
3361 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003362 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003363 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3364 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003365 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003366 // We can't handle this without inserting insertvalues
3367 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003368 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003369
3370 // The requested index identifies a part of a nested aggregate. Handle
3371 // this specially. For example,
3372 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3373 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3374 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3375 // This can be changed into
3376 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3377 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3378 // which allows the unused 0,0 element from the nested struct to be
3379 // removed.
3380 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3381 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003382 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003383
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003384 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003385 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003386 // looking for, then.
3387 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003388 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003389 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003390 }
3391 // If we end up here, the indices of the insertvalue match with those
3392 // requested (though possibly only partially). Now we recursively look at
3393 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003394 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003395 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003396 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003397 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003398
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003399 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003400 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003401 // something else, we can extract from that something else directly instead.
3402 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003403
3404 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003405 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003406 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003407 SmallVector<unsigned, 5> Idxs;
3408 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003409 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003410 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003411
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003412 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003413 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003414
Craig Topper1bef2c82012-12-22 19:15:35 +00003415 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003416 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003417
Jay Foad57aa6362011-07-13 10:26:04 +00003418 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003419 }
3420 // Otherwise, we don't know (such as, extracting from a function return value
3421 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003422 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003423}
Evan Chengda3db112008-06-30 07:31:25 +00003424
Sanjay Patelaee84212014-11-04 16:27:42 +00003425/// Analyze the specified pointer to see if it can be expressed as a base
3426/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003427Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003428 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003429 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003430 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003431
3432 // We walk up the defs but use a visited set to handle unreachable code. In
3433 // that case, we stop after accumulating the cycle once (not that it
3434 // matters).
3435 SmallPtrSet<Value *, 16> Visited;
3436 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003437 if (Ptr->getType()->isVectorTy())
3438 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003439
Nuno Lopes368c4d02012-12-31 20:48:35 +00003440 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003441 // If one of the values we have visited is an addrspacecast, then
3442 // the pointer type of this GEP may be different from the type
3443 // of the Ptr parameter which was passed to this function. This
3444 // means when we construct GEPOffset, we need to use the size
3445 // of GEP's pointer type rather than the size of the original
3446 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003447 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003448 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3449 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003450
Florian Hahn79024052019-01-04 14:53:22 +00003451 APInt OrigByteOffset(ByteOffset);
3452 ByteOffset += GEPOffset.sextOrTrunc(ByteOffset.getBitWidth());
3453 if (ByteOffset.getMinSignedBits() > 64) {
3454 // Stop traversal if the pointer offset wouldn't fit into int64_t
3455 // (this should be removed if Offset is updated to an APInt)
3456 ByteOffset = OrigByteOffset;
3457 break;
3458 }
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003459
Nuno Lopes368c4d02012-12-31 20:48:35 +00003460 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003461 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3462 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003463 Ptr = cast<Operator>(Ptr)->getOperand(0);
3464 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003465 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003466 break;
3467 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003468 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003469 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003470 }
3471 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003472 Offset = ByteOffset.getSExtValue();
3473 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003474}
3475
Matthias Braun50ec0b52017-05-19 22:37:09 +00003476bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3477 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003478 // Make sure the GEP has exactly three arguments.
3479 if (GEP->getNumOperands() != 3)
3480 return false;
3481
Matthias Braun50ec0b52017-05-19 22:37:09 +00003482 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3483 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003484 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003485 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003486 return false;
3487
3488 // Check to make sure that the first operand of the GEP is an integer and
3489 // has value 0 so that we are sure we're indexing into the initializer.
3490 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3491 if (!FirstIdx || !FirstIdx->isZero())
3492 return false;
3493
3494 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003495}
Chris Lattnere28618d2010-11-30 22:25:26 +00003496
Matthias Braun50ec0b52017-05-19 22:37:09 +00003497bool llvm::getConstantDataArrayInfo(const Value *V,
3498 ConstantDataArraySlice &Slice,
3499 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003500 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003501
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003502 // Look through bitcast instructions and geps.
3503 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003504
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003505 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003506 // offset.
3507 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003508 // The GEP operator should be based on a pointer to string constant, and is
3509 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003510 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003511 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003512
Evan Chengda3db112008-06-30 07:31:25 +00003513 // If the second index isn't a ConstantInt, then this is a variable index
3514 // into the array. If this occurs, we can't say anything meaningful about
3515 // the string.
3516 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003517 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003518 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003519 else
3520 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003521 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3522 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003523 }
Nick Lewycky46209882011-10-20 00:34:35 +00003524
Evan Chengda3db112008-06-30 07:31:25 +00003525 // The GEP instruction, constant or instruction, must reference a global
3526 // variable that is a constant and is initialized. The referenced constant
3527 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003528 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003529 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003530 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003531
Matthias Braun50ec0b52017-05-19 22:37:09 +00003532 const ConstantDataArray *Array;
3533 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003534 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003535 Type *GVTy = GV->getValueType();
3536 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003537 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003538 Array = nullptr;
3539 } else {
3540 const DataLayout &DL = GV->getParent()->getDataLayout();
3541 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3542 uint64_t Length = SizeInBytes / (ElementSize / 8);
3543 if (Length <= Offset)
3544 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003545
Matthias Braun50ec0b52017-05-19 22:37:09 +00003546 Slice.Array = nullptr;
3547 Slice.Offset = 0;
3548 Slice.Length = Length - Offset;
3549 return true;
3550 }
3551 } else {
3552 // This must be a ConstantDataArray.
3553 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3554 if (!Array)
3555 return false;
3556 ArrayTy = Array->getType();
3557 }
3558 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003559 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003560
Matthias Braun50ec0b52017-05-19 22:37:09 +00003561 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003562 if (Offset > NumElts)
3563 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003564
Matthias Braun50ec0b52017-05-19 22:37:09 +00003565 Slice.Array = Array;
3566 Slice.Offset = Offset;
3567 Slice.Length = NumElts - Offset;
3568 return true;
3569}
3570
3571/// This function computes the length of a null-terminated C string pointed to
3572/// by V. If successful, it returns true and returns the string in Str.
3573/// If unsuccessful, it returns false.
3574bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3575 uint64_t Offset, bool TrimAtNul) {
3576 ConstantDataArraySlice Slice;
3577 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3578 return false;
3579
3580 if (Slice.Array == nullptr) {
3581 if (TrimAtNul) {
3582 Str = StringRef();
3583 return true;
3584 }
3585 if (Slice.Length == 1) {
3586 Str = StringRef("", 1);
3587 return true;
3588 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003589 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003590 // of 0s at hand.
3591 return false;
3592 }
3593
3594 // Start out with the entire array in the StringRef.
3595 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003596 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003597 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003598
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003599 if (TrimAtNul) {
3600 // Trim off the \0 and anything after it. If the array is not nul
3601 // terminated, we just return the whole end of string. The client may know
3602 // some other way that the string is length-bound.
3603 Str = Str.substr(0, Str.find('\0'));
3604 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003605 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003606}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003607
3608// These next two are very similar to the above, but also look through PHI
3609// nodes.
3610// TODO: See if we can integrate these two together.
3611
Sanjay Patelaee84212014-11-04 16:27:42 +00003612/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003613/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003614static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003615 SmallPtrSetImpl<const PHINode*> &PHIs,
3616 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003617 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003618 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003619
3620 // If this is a PHI node, there are two cases: either we have already seen it
3621 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003622 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003623 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003624 return ~0ULL; // already in the set.
3625
3626 // If it was new, see if all the input strings are the same length.
3627 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003628 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003629 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003630 if (Len == 0) return 0; // Unknown length -> unknown.
3631
3632 if (Len == ~0ULL) continue;
3633
3634 if (Len != LenSoFar && LenSoFar != ~0ULL)
3635 return 0; // Disagree -> unknown.
3636 LenSoFar = Len;
3637 }
3638
3639 // Success, all agree.
3640 return LenSoFar;
3641 }
3642
3643 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003644 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003645 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003646 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003647 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003648 if (Len2 == 0) return 0;
3649 if (Len1 == ~0ULL) return Len2;
3650 if (Len2 == ~0ULL) return Len1;
3651 if (Len1 != Len2) return 0;
3652 return Len1;
3653 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003654
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003655 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003656 ConstantDataArraySlice Slice;
3657 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003658 return 0;
3659
Matthias Braun50ec0b52017-05-19 22:37:09 +00003660 if (Slice.Array == nullptr)
3661 return 1;
3662
3663 // Search for nul characters
3664 unsigned NullIndex = 0;
3665 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3666 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3667 break;
3668 }
3669
3670 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003671}
3672
Sanjay Patelaee84212014-11-04 16:27:42 +00003673/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003674/// the specified pointer, return 'len+1'. If we can't, return 0.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003675uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
David Bolvansky41f4b642018-05-22 15:41:23 +00003676 if (!V->getType()->isPointerTy())
3677 return 0;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003678
Pete Cooper35b00d52016-08-13 01:05:32 +00003679 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003680 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003681 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3682 // an empty string as a length.
3683 return Len == ~0ULL ? 1 : Len;
3684}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003685
Chandler Carruth363ac682019-01-07 05:42:51 +00003686const Value *llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call) {
3687 assert(Call &&
3688 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
3689 if (const Value *RV = Call->getReturnedArgOperand())
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003690 return RV;
3691 // This can be used only as a aliasing property.
Chandler Carruth363ac682019-01-07 05:42:51 +00003692 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call))
3693 return Call->getArgOperand(0);
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003694 return nullptr;
3695}
3696
3697bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
Chandler Carruth363ac682019-01-07 05:42:51 +00003698 const CallBase *Call) {
3699 return Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
3700 Call->getIntrinsicID() == Intrinsic::strip_invariant_group;
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003701}
3702
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003703/// \p PN defines a loop-variant pointer to an object. Check if the
Adam Nemete2b885c2015-04-23 20:09:20 +00003704/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003705static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3706 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003707 // Find the loop-defined value.
3708 Loop *L = LI->getLoopFor(PN->getParent());
3709 if (PN->getNumIncomingValues() != 2)
3710 return true;
3711
3712 // Find the value from previous iteration.
3713 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3714 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3715 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3716 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3717 return true;
3718
3719 // If a new pointer is loaded in the loop, the pointer references a different
3720 // object in every iteration. E.g.:
3721 // for (i)
3722 // int *p = a[i];
3723 // ...
3724 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3725 if (!L->isLoopInvariant(Load->getPointerOperand()))
3726 return false;
3727 return true;
3728}
3729
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003730Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3731 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003732 if (!V->getType()->isPointerTy())
3733 return V;
3734 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3735 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3736 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003737 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3738 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003739 V = cast<Operator>(V)->getOperand(0);
3740 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003741 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003742 return V;
3743 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003744 } else if (isa<AllocaInst>(V)) {
3745 // An alloca can't be further simplified.
3746 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003747 } else {
Chandler Carruth363ac682019-01-07 05:42:51 +00003748 if (auto *Call = dyn_cast<CallBase>(V)) {
Piotr Padlewski5b3db452018-07-02 04:49:30 +00003749 // CaptureTracking can know about special capturing properties of some
3750 // intrinsics like launder.invariant.group, that can't be expressed with
3751 // the attributes, but have properties like returning aliasing pointer.
3752 // Because some analysis may assume that nocaptured pointer is not
3753 // returned from some special intrinsic (because function would have to
3754 // be marked with returns attribute), it is crucial to use this function
3755 // because it should be in sync with CaptureTracking. Not using it may
3756 // cause weird miscompilations where 2 aliasing pointers are assumed to
3757 // noalias.
Chandler Carruth363ac682019-01-07 05:42:51 +00003758 if (auto *RP = getArgumentAliasingToReturnedPointer(Call)) {
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003759 V = RP;
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003760 continue;
3761 }
Piotr Padlewskid6f73462018-05-23 09:16:44 +00003762 }
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003763
Dan Gohman05b18f12010-12-15 20:49:55 +00003764 // See if InstructionSimplify knows any relevant tricks.
3765 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003766 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003767 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003768 V = Simplified;
3769 continue;
3770 }
3771
Dan Gohmana4fcd242010-12-15 20:02:24 +00003772 return V;
3773 }
3774 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3775 }
3776 return V;
3777}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003778
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003779void llvm::GetUnderlyingObjects(const Value *V,
3780 SmallVectorImpl<const Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003781 const DataLayout &DL, LoopInfo *LI,
3782 unsigned MaxLookup) {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003783 SmallPtrSet<const Value *, 4> Visited;
3784 SmallVector<const Value *, 4> Worklist;
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003785 Worklist.push_back(V);
3786 do {
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003787 const Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003788 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003789
David Blaikie70573dc2014-11-19 07:49:26 +00003790 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003791 continue;
3792
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003793 if (auto *SI = dyn_cast<SelectInst>(P)) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003794 Worklist.push_back(SI->getTrueValue());
3795 Worklist.push_back(SI->getFalseValue());
3796 continue;
3797 }
3798
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003799 if (auto *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003800 // If this PHI changes the underlying object in every iteration of the
3801 // loop, don't look through it. Consider:
3802 // int **A;
3803 // for (i) {
3804 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3805 // Curr = A[i];
3806 // *Prev, *Curr;
3807 //
3808 // Prev is tracking Curr one iteration behind so they refer to different
3809 // underlying objects.
3810 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3811 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003812 for (Value *IncValue : PN->incoming_values())
3813 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003814 continue;
3815 }
3816
3817 Objects.push_back(P);
3818 } while (!Worklist.empty());
3819}
3820
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003821/// This is the function that does the work of looking through basic
3822/// ptrtoint+arithmetic+inttoptr sequences.
3823static const Value *getUnderlyingObjectFromInt(const Value *V) {
3824 do {
3825 if (const Operator *U = dyn_cast<Operator>(V)) {
3826 // If we find a ptrtoint, we can transfer control back to the
3827 // regular getUnderlyingObjectFromInt.
3828 if (U->getOpcode() == Instruction::PtrToInt)
3829 return U->getOperand(0);
3830 // If we find an add of a constant, a multiplied value, or a phi, it's
3831 // likely that the other operand will lead us to the base
3832 // object. We don't have to worry about the case where the
3833 // object address is somehow being computed by the multiply,
3834 // because our callers only care when the result is an
3835 // identifiable object.
3836 if (U->getOpcode() != Instruction::Add ||
3837 (!isa<ConstantInt>(U->getOperand(1)) &&
3838 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3839 !isa<PHINode>(U->getOperand(1))))
3840 return V;
3841 V = U->getOperand(0);
3842 } else {
3843 return V;
3844 }
3845 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3846 } while (true);
3847}
3848
3849/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3850/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003851/// It returns false if unidentified object is found in GetUnderlyingObjects.
3852bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003853 SmallVectorImpl<Value *> &Objects,
3854 const DataLayout &DL) {
3855 SmallPtrSet<const Value *, 16> Visited;
3856 SmallVector<const Value *, 4> Working(1, V);
3857 do {
3858 V = Working.pop_back_val();
3859
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003860 SmallVector<const Value *, 4> Objs;
3861 GetUnderlyingObjects(V, Objs, DL);
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003862
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00003863 for (const Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003864 if (!Visited.insert(V).second)
3865 continue;
3866 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3867 const Value *O =
3868 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3869 if (O->getType()->isPointerTy()) {
3870 Working.push_back(O);
3871 continue;
3872 }
3873 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003874 // If GetUnderlyingObjects fails to find an identifiable object,
3875 // getUnderlyingObjectsForCodeGen also fails for safety.
3876 if (!isIdentifiedObject(V)) {
3877 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003878 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003879 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003880 Objects.push_back(const_cast<Value *>(V));
3881 }
3882 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003883 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003884}
3885
Sanjay Patelaee84212014-11-04 16:27:42 +00003886/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003887bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003888 for (const User *U : V->users()) {
3889 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003890 if (!II) return false;
3891
Vedant Kumarb264d692018-12-21 21:49:40 +00003892 if (!II->isLifetimeStartOrEnd())
Nick Lewycky3e334a42011-06-27 04:20:45 +00003893 return false;
3894 }
3895 return true;
3896}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003897
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003898bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3899 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003900 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003901 const Operator *Inst = dyn_cast<Operator>(V);
3902 if (!Inst)
3903 return false;
3904
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003905 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3906 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3907 if (C->canTrap())
3908 return false;
3909
3910 switch (Inst->getOpcode()) {
3911 default:
3912 return true;
3913 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003914 case Instruction::URem: {
3915 // x / y is undefined if y == 0.
3916 const APInt *V;
3917 if (match(Inst->getOperand(1), m_APInt(V)))
3918 return *V != 0;
3919 return false;
3920 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003921 case Instruction::SDiv:
3922 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003923 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003924 const APInt *Numerator, *Denominator;
3925 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3926 return false;
3927 // We cannot hoist this division if the denominator is 0.
3928 if (*Denominator == 0)
3929 return false;
3930 // It's safe to hoist if the denominator is not 0 or -1.
3931 if (*Denominator != -1)
3932 return true;
3933 // At this point we know that the denominator is -1. It is safe to hoist as
3934 // long we know that the numerator is not INT_MIN.
3935 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3936 return !Numerator->isMinSignedValue();
3937 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003938 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003939 }
3940 case Instruction::Load: {
3941 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003942 if (!LI->isUnordered() ||
3943 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003944 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003945 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003946 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3947 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003948 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003949 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003950 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3951 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003952 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003953 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003954 auto *CI = cast<const CallInst>(Inst);
3955 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003956
Matt Arsenault6a288c12017-05-03 02:26:10 +00003957 // The called function could have undefined behavior or side-effects, even
3958 // if marked readnone nounwind.
3959 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003960 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003961 case Instruction::VAArg:
3962 case Instruction::Alloca:
3963 case Instruction::Invoke:
Craig Topper784929d2019-02-08 20:48:56 +00003964 case Instruction::CallBr:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003965 case Instruction::PHI:
3966 case Instruction::Store:
3967 case Instruction::Ret:
3968 case Instruction::Br:
3969 case Instruction::IndirectBr:
3970 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003971 case Instruction::Unreachable:
3972 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003973 case Instruction::AtomicRMW:
3974 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003975 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003976 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003977 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003978 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003979 case Instruction::CatchRet:
3980 case Instruction::CleanupPad:
3981 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003982 return false; // Misc instructions which have effects
3983 }
3984}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003985
Quentin Colombet6443cce2015-08-06 18:44:34 +00003986bool llvm::mayBeMemoryDependent(const Instruction &I) {
3987 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3988}
3989
Nikita Popovd0f13e62019-05-26 13:22:01 +00003990/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
3991static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
3992 switch (OR) {
3993 case ConstantRange::OverflowResult::MayOverflow:
3994 return OverflowResult::MayOverflow;
Nikita Popov332c1002019-05-28 18:08:31 +00003995 case ConstantRange::OverflowResult::AlwaysOverflowsLow:
3996 return OverflowResult::AlwaysOverflowsLow;
3997 case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
3998 return OverflowResult::AlwaysOverflowsHigh;
Nikita Popovd0f13e62019-05-26 13:22:01 +00003999 case ConstantRange::OverflowResult::NeverOverflows:
4000 return OverflowResult::NeverOverflows;
4001 }
4002 llvm_unreachable("Unknown OverflowResult");
4003}
4004
4005/// Combine constant ranges from computeConstantRange() and computeKnownBits().
4006static ConstantRange computeConstantRangeIncludingKnownBits(
4007 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4008 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4009 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4010 KnownBits Known = computeKnownBits(
4011 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4012 ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4013 ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4014 ConstantRange::PreferredRangeType RangeType =
4015 ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
4016 return CR1.intersectWith(CR2, RangeType);
4017}
4018
Florian Hahn19f9e322018-08-17 14:39:04 +00004019OverflowResult llvm::computeOverflowForUnsignedMul(
4020 const Value *LHS, const Value *RHS, const DataLayout &DL,
4021 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4022 bool UseInstrInfo) {
Nikita Popovd0f13e62019-05-26 13:22:01 +00004023 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4024 nullptr, UseInstrInfo);
4025 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4026 nullptr, UseInstrInfo);
4027 ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4028 ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4029 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
David Majnemer491331a2015-01-02 07:29:43 +00004030}
David Majnemer5310c1e2015-01-07 00:39:50 +00004031
Florian Hahn19f9e322018-08-17 14:39:04 +00004032OverflowResult
4033llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4034 const DataLayout &DL, AssumptionCache *AC,
4035 const Instruction *CxtI,
4036 const DominatorTree *DT, bool UseInstrInfo) {
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004037 // Multiplying n * m significant bits yields a result of n + m significant
4038 // bits. If the total number of significant bits does not exceed the
4039 // result bit width (minus 1), there is no overflow.
4040 // This means if we have enough leading sign bits in the operands
4041 // we can guarantee that the result does not overflow.
4042 // Ref: "Hacker's Delight" by Henry Warren
4043 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4044
4045 // Note that underestimating the number of sign bits gives a more
4046 // conservative answer.
4047 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4048 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4049
4050 // First handle the easy case: if we have enough sign bits there's
4051 // definitely no overflow.
4052 if (SignBits > BitWidth + 1)
4053 return OverflowResult::NeverOverflows;
4054
4055 // There are two ambiguous cases where there can be no overflow:
4056 // SignBits == BitWidth + 1 and
4057 // SignBits == BitWidth
4058 // The second case is difficult to check, therefore we only handle the
4059 // first case.
4060 if (SignBits == BitWidth + 1) {
4061 // It overflows only when both arguments are negative and the true
4062 // product is exactly the minimum negative number.
4063 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4064 // For simplicity we just check if at least one side is not negative.
Florian Hahn19f9e322018-08-17 14:39:04 +00004065 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4066 nullptr, UseInstrInfo);
4067 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4068 nullptr, UseInstrInfo);
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004069 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4070 return OverflowResult::NeverOverflows;
4071 }
4072 return OverflowResult::MayOverflow;
4073}
4074
Florian Hahn19f9e322018-08-17 14:39:04 +00004075OverflowResult llvm::computeOverflowForUnsignedAdd(
4076 const Value *LHS, const Value *RHS, const DataLayout &DL,
4077 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4078 bool UseInstrInfo) {
Nikita Popov20838192019-03-19 17:53:56 +00004079 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4080 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4081 nullptr, UseInstrInfo);
4082 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4083 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4084 nullptr, UseInstrInfo);
Nikita Popov614b1be2019-03-15 18:37:45 +00004085 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
David Majnemer5310c1e2015-01-07 00:39:50 +00004086}
James Molloy71b91c22015-05-11 14:42:20 +00004087
Pete Cooper35b00d52016-08-13 01:05:32 +00004088static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4089 const Value *RHS,
4090 const AddOperator *Add,
4091 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004092 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00004093 const Instruction *CxtI,
4094 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00004095 if (Add && Add->hasNoSignedWrap()) {
4096 return OverflowResult::NeverOverflows;
4097 }
4098
Craig Topperbb973722017-05-15 02:44:08 +00004099 // If LHS and RHS each have at least two sign bits, the addition will look
4100 // like
4101 //
4102 // XX..... +
4103 // YY.....
4104 //
4105 // If the carry into the most significant position is 0, X and Y can't both
4106 // be 1 and therefore the carry out of the addition is also 0.
4107 //
4108 // If the carry into the most significant position is 1, X and Y can't both
4109 // be 0 and therefore the carry out of the addition is also 1.
4110 //
4111 // Since the carry into the most significant position is always equal to
4112 // the carry out of the addition, there is no signed overflow.
4113 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4114 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4115 return OverflowResult::NeverOverflows;
4116
Nikita Popov10edd2b2019-04-09 16:12:59 +00004117 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4118 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4119 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4120 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov322e2db2019-03-17 21:25:26 +00004121 OverflowResult OR =
4122 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4123 if (OR != OverflowResult::MayOverflow)
4124 return OR;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004125
4126 // The remaining code needs Add to be available. Early returns if not so.
4127 if (!Add)
4128 return OverflowResult::MayOverflow;
4129
4130 // If the sign of Add is the same as at least one of the operands, this add
Nikita Popov280a6b02019-03-22 17:51:40 +00004131 // CANNOT overflow. If this can be determined from the known bits of the
4132 // operands the above signedAddMayOverflow() check will have already done so.
4133 // The only other way to improve on the known bits is from an assumption, so
4134 // call computeKnownBitsFromAssume() directly.
Jingyue Wu10fcea52015-08-20 18:27:04 +00004135 bool LHSOrRHSKnownNonNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004136 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
Fangrui Songf78650a2018-07-30 19:41:25 +00004137 bool LHSOrRHSKnownNegative =
Nikita Popov6e9157d2019-04-09 07:13:09 +00004138 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00004139 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Nikita Popov6e9157d2019-04-09 07:13:09 +00004140 KnownBits AddKnown(LHSRange.getBitWidth());
Nikita Popov280a6b02019-03-22 17:51:40 +00004141 computeKnownBitsFromAssume(
4142 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
Craig Topper6e11a052017-05-08 16:22:48 +00004143 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
Nikita Popov280a6b02019-03-22 17:51:40 +00004144 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
Jingyue Wu10fcea52015-08-20 18:27:04 +00004145 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00004146 }
4147
4148 return OverflowResult::MayOverflow;
4149}
4150
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004151OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4152 const Value *RHS,
4153 const DataLayout &DL,
4154 AssumptionCache *AC,
4155 const Instruction *CxtI,
4156 const DominatorTree *DT) {
Nikita Popov20838192019-03-19 17:53:56 +00004157 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4158 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4159 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4160 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov614b1be2019-03-15 18:37:45 +00004161 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004162}
4163
4164OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4165 const Value *RHS,
4166 const DataLayout &DL,
4167 AssumptionCache *AC,
4168 const Instruction *CxtI,
4169 const DominatorTree *DT) {
4170 // If LHS and RHS each have at least two sign bits, the subtraction
4171 // cannot overflow.
4172 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4173 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4174 return OverflowResult::NeverOverflows;
4175
Nikita Popov4b2323d2019-04-09 17:01:49 +00004176 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4177 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4178 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4179 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
Nikita Popov3af5b282019-03-21 17:23:51 +00004180 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +00004181}
4182
Nikita Popov79dffc62019-04-16 18:55:16 +00004183bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
Pete Cooper35b00d52016-08-13 01:05:32 +00004184 const DominatorTree &DT) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004185 SmallVector<const BranchInst *, 2> GuardingBranches;
4186 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004187
Nikita Popov79dffc62019-04-16 18:55:16 +00004188 for (const User *U : WO->users()) {
Pete Cooper35b00d52016-08-13 01:05:32 +00004189 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004190 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4191
4192 if (EVI->getIndices()[0] == 0)
4193 Results.push_back(EVI);
4194 else {
4195 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4196
Pete Cooper35b00d52016-08-13 01:05:32 +00004197 for (const auto *U : EVI->users())
4198 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004199 assert(B->isConditional() && "How else is it using an i1?");
4200 GuardingBranches.push_back(B);
4201 }
4202 }
4203 } else {
4204 // We are using the aggregate directly in a way we don't want to analyze
4205 // here (storing it to a global, say).
4206 return false;
4207 }
4208 }
4209
Pete Cooper35b00d52016-08-13 01:05:32 +00004210 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004211 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4212 if (!NoWrapEdge.isSingleEdge())
4213 return false;
4214
4215 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00004216 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004217 // If the extractvalue itself is not executed on overflow, the we don't
4218 // need to check each use separately, since domination is transitive.
4219 if (DT.dominates(NoWrapEdge, Result->getParent()))
4220 continue;
4221
4222 for (auto &RU : Result->uses())
4223 if (!DT.dominates(NoWrapEdge, RU))
4224 return false;
4225 }
4226
4227 return true;
4228 };
4229
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004230 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00004231}
4232
4233
Pete Cooper35b00d52016-08-13 01:05:32 +00004234OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004235 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004236 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004237 const Instruction *CxtI,
4238 const DominatorTree *DT) {
4239 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004240 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004241}
4242
Pete Cooper35b00d52016-08-13 01:05:32 +00004243OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
4244 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004245 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004246 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00004247 const Instruction *CxtI,
4248 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004249 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00004250}
4251
Jingyue Wu42f1d672015-07-28 18:22:40 +00004252bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004253 // A memory operation returns normally if it isn't volatile. A volatile
4254 // operation is allowed to trap.
4255 //
4256 // An atomic operation isn't guaranteed to return in a reasonable amount of
4257 // time because it's possible for another thread to interfere with it for an
4258 // arbitrary length of time, but programs aren't allowed to rely on that.
4259 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
4260 return !LI->isVolatile();
4261 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
4262 return !SI->isVolatile();
4263 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
4264 return !CXI->isVolatile();
4265 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
4266 return !RMWI->isVolatile();
4267 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
4268 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004269
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004270 // If there is no successor, then execution can't transfer to it.
4271 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
4272 return !CRI->unwindsToCaller();
4273 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
4274 return !CatchSwitch->unwindsToCaller();
4275 if (isa<ResumeInst>(I))
4276 return false;
4277 if (isa<ReturnInst>(I))
4278 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00004279 if (isa<UnreachableInst>(I))
4280 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00004281
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004282 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00004283 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00004284 // Call sites that throw have implicit non-local control flow.
4285 if (!CS.doesNotThrow())
4286 return false;
4287
4288 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
4289 // etc. and thus not return. However, LLVM already assumes that
4290 //
4291 // - Thread exiting actions are modeled as writes to memory invisible to
4292 // the program.
4293 //
4294 // - Loops that don't have side effects (side effects are volatile/atomic
4295 // stores and IO) always terminate (see http://llvm.org/PR965).
4296 // Furthermore IO itself is also modeled as writes to memory invisible to
4297 // the program.
4298 //
4299 // We rely on those assumptions here, and use the memory effects of the call
4300 // target as a proxy for checking that it always returns.
4301
4302 // FIXME: This isn't aggressive enough; a call which only writes to a global
4303 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00004304 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00004305 match(I, m_Intrinsic<Intrinsic::assume>()) ||
Max Kazantsevb3168a42019-02-14 11:10:21 +00004306 match(I, m_Intrinsic<Intrinsic::sideeffect>()) ||
4307 match(I, m_Intrinsic<Intrinsic::experimental_widenable_condition>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00004308 }
4309
4310 // Other instructions return normally.
4311 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004312}
4313
Philip Reamesfbffd122018-03-08 21:25:30 +00004314bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
Hiroshi Inouec437f312019-01-30 05:26:31 +00004315 // TODO: This is slightly conservative for invoke instruction since exiting
Philip Reamesfbffd122018-03-08 21:25:30 +00004316 // via an exception *is* normal control for them.
4317 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
4318 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
4319 return false;
4320 return true;
4321}
4322
Jingyue Wu42f1d672015-07-28 18:22:40 +00004323bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
4324 const Loop *L) {
4325 // The loop header is guaranteed to be executed for every iteration.
4326 //
4327 // FIXME: Relax this constraint to cover all basic blocks that are
4328 // guaranteed to be executed at every iteration.
4329 if (I->getParent() != L->getHeader()) return false;
4330
4331 for (const Instruction &LI : *L->getHeader()) {
4332 if (&LI == I) return true;
4333 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
4334 }
4335 llvm_unreachable("Instruction not contained in its own parent basic block.");
4336}
4337
4338bool llvm::propagatesFullPoison(const Instruction *I) {
4339 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004340 case Instruction::Add:
4341 case Instruction::Sub:
4342 case Instruction::Xor:
4343 case Instruction::Trunc:
4344 case Instruction::BitCast:
4345 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00004346 case Instruction::Mul:
4347 case Instruction::Shl:
4348 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004349 // These operations all propagate poison unconditionally. Note that poison
4350 // is not any particular value, so xor or subtraction of poison with
4351 // itself still yields poison, not zero.
4352 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004353
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004354 case Instruction::AShr:
4355 case Instruction::SExt:
4356 // For these operations, one bit of the input is replicated across
4357 // multiple output bits. A replicated poison bit is still poison.
4358 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004359
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004360 case Instruction::ICmp:
4361 // Comparing poison with any value yields poison. This is why, for
4362 // instance, x s< (x +nsw 1) can be folded to true.
4363 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004364
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004365 default:
4366 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004367 }
4368}
4369
4370const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4371 switch (I->getOpcode()) {
4372 case Instruction::Store:
4373 return cast<StoreInst>(I)->getPointerOperand();
4374
4375 case Instruction::Load:
4376 return cast<LoadInst>(I)->getPointerOperand();
4377
4378 case Instruction::AtomicCmpXchg:
4379 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4380
4381 case Instruction::AtomicRMW:
4382 return cast<AtomicRMWInst>(I)->getPointerOperand();
4383
4384 case Instruction::UDiv:
4385 case Instruction::SDiv:
4386 case Instruction::URem:
4387 case Instruction::SRem:
4388 return I->getOperand(1);
4389
4390 default:
4391 return nullptr;
4392 }
4393}
4394
Philip Reames4bf1c232019-06-10 20:41:27 +00004395bool llvm::mustTriggerUB(const Instruction *I,
4396 const SmallSet<const Value *, 16>& KnownPoison) {
4397 auto *NotPoison = getGuaranteedNonFullPoisonOp(I);
4398 return (NotPoison && KnownPoison.count(NotPoison));
4399}
4400
4401
Sanjoy Das08989c72017-04-30 19:41:19 +00004402bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004403 // We currently only look for uses of poison values within the same basic
4404 // block, as that makes it easier to guarantee that the uses will be
4405 // executed given that PoisonI is executed.
4406 //
4407 // FIXME: Expand this to consider uses beyond the same basic block. To do
4408 // this, look out for the distinction between post-dominance and strong
4409 // post-dominance.
4410 const BasicBlock *BB = PoisonI->getParent();
4411
4412 // Set of instructions that we have proved will yield poison if PoisonI
4413 // does.
4414 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004415 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004416 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004417 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004418
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004419 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004420
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004421 unsigned Iter = 0;
4422 while (Iter++ < MaxDepth) {
4423 for (auto &I : make_range(Begin, End)) {
4424 if (&I != PoisonI) {
Philip Reames4bf1c232019-06-10 20:41:27 +00004425 if (mustTriggerUB(&I, YieldsPoison))
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004426 return true;
4427 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4428 return false;
4429 }
4430
4431 // Mark poison that propagates from I through uses of I.
4432 if (YieldsPoison.count(&I)) {
4433 for (const User *User : I.users()) {
4434 const Instruction *UserI = cast<Instruction>(User);
4435 if (propagatesFullPoison(UserI))
4436 YieldsPoison.insert(User);
4437 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004438 }
4439 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004440
4441 if (auto *NextBB = BB->getSingleSuccessor()) {
4442 if (Visited.insert(NextBB).second) {
4443 BB = NextBB;
4444 Begin = BB->getFirstNonPHI()->getIterator();
4445 End = BB->end();
4446 continue;
4447 }
4448 }
4449
4450 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004451 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004452 return false;
4453}
4454
Pete Cooper35b00d52016-08-13 01:05:32 +00004455static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004456 if (FMF.noNaNs())
4457 return true;
4458
4459 if (auto *C = dyn_cast<ConstantFP>(V))
4460 return !C->isNaN();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004461
4462 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4463 if (!C->getElementType()->isFloatingPointTy())
4464 return false;
4465 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4466 if (C->getElementAsAPFloat(I).isNaN())
4467 return false;
4468 }
4469 return true;
4470 }
4471
James Molloy134bec22015-08-11 09:12:57 +00004472 return false;
4473}
4474
Pete Cooper35b00d52016-08-13 01:05:32 +00004475static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004476 if (auto *C = dyn_cast<ConstantFP>(V))
4477 return !C->isZero();
Thomas Livelyd47b5c72018-09-28 21:36:43 +00004478
4479 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
4480 if (!C->getElementType()->isFloatingPointTy())
4481 return false;
4482 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
4483 if (C->getElementAsAPFloat(I).isZero())
4484 return false;
4485 }
4486 return true;
4487 }
4488
James Molloy134bec22015-08-11 09:12:57 +00004489 return false;
4490}
4491
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004492/// Match clamp pattern for float types without care about NaNs or signed zeros.
4493/// Given non-min/max outer cmp/select from the clamp pattern this
4494/// function recognizes if it can be substitued by a "canonical" min/max
4495/// pattern.
4496static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4497 Value *CmpLHS, Value *CmpRHS,
4498 Value *TrueVal, Value *FalseVal,
4499 Value *&LHS, Value *&RHS) {
4500 // Try to match
4501 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4502 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4503 // and return description of the outer Max/Min.
4504
4505 // First, check if select has inverse order:
4506 if (CmpRHS == FalseVal) {
4507 std::swap(TrueVal, FalseVal);
4508 Pred = CmpInst::getInversePredicate(Pred);
4509 }
4510
4511 // Assume success now. If there's no match, callers should not use these anyway.
4512 LHS = TrueVal;
4513 RHS = FalseVal;
4514
4515 const APFloat *FC1;
4516 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4517 return {SPF_UNKNOWN, SPNB_NA, false};
4518
4519 const APFloat *FC2;
4520 switch (Pred) {
4521 case CmpInst::FCMP_OLT:
4522 case CmpInst::FCMP_OLE:
4523 case CmpInst::FCMP_ULT:
4524 case CmpInst::FCMP_ULE:
4525 if (match(FalseVal,
4526 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4527 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4528 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4529 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4530 break;
4531 case CmpInst::FCMP_OGT:
4532 case CmpInst::FCMP_OGE:
4533 case CmpInst::FCMP_UGT:
4534 case CmpInst::FCMP_UGE:
4535 if (match(FalseVal,
4536 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4537 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4538 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4539 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4540 break;
4541 default:
4542 break;
4543 }
4544
4545 return {SPF_UNKNOWN, SPNB_NA, false};
4546}
4547
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004548/// Recognize variations of:
4549/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4550static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4551 Value *CmpLHS, Value *CmpRHS,
4552 Value *TrueVal, Value *FalseVal) {
4553 // Swap the select operands and predicate to match the patterns below.
4554 if (CmpRHS != TrueVal) {
4555 Pred = ICmpInst::getSwappedPredicate(Pred);
4556 std::swap(TrueVal, FalseVal);
4557 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004558 const APInt *C1;
4559 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4560 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004561 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4562 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004563 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004564 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004565
4566 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4567 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004568 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004569 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004570
4571 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4572 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004573 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004574 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004575
4576 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4577 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004578 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004579 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004580 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004581 return {SPF_UNKNOWN, SPNB_NA, false};
4582}
4583
Sanjay Patel78114302018-01-02 20:56:45 +00004584/// Recognize variations of:
4585/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4586static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4587 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004588 Value *TVal, Value *FVal,
4589 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004590 // TODO: Allow FP min/max with nnan/nsz.
4591 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4592
4593 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004594 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004595 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4596 return {SPF_UNKNOWN, SPNB_NA, false};
4597
4598 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004599 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004600 if (L.Flavor != R.Flavor)
4601 return {SPF_UNKNOWN, SPNB_NA, false};
4602
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004603 // We have something like: x Pred y ? min(a, b) : min(c, d).
4604 // Try to match the compare to the min/max operations of the select operands.
4605 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004606 switch (L.Flavor) {
4607 case SPF_SMIN:
4608 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4609 Pred = ICmpInst::getSwappedPredicate(Pred);
4610 std::swap(CmpLHS, CmpRHS);
4611 }
4612 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4613 break;
4614 return {SPF_UNKNOWN, SPNB_NA, false};
4615 case SPF_SMAX:
4616 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4617 Pred = ICmpInst::getSwappedPredicate(Pred);
4618 std::swap(CmpLHS, CmpRHS);
4619 }
4620 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4621 break;
4622 return {SPF_UNKNOWN, SPNB_NA, false};
4623 case SPF_UMIN:
4624 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4625 Pred = ICmpInst::getSwappedPredicate(Pred);
4626 std::swap(CmpLHS, CmpRHS);
4627 }
4628 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4629 break;
4630 return {SPF_UNKNOWN, SPNB_NA, false};
4631 case SPF_UMAX:
4632 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4633 Pred = ICmpInst::getSwappedPredicate(Pred);
4634 std::swap(CmpLHS, CmpRHS);
4635 }
4636 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4637 break;
4638 return {SPF_UNKNOWN, SPNB_NA, false};
4639 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004640 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004641 }
4642
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004643 // If there is a common operand in the already matched min/max and the other
4644 // min/max operands match the compare operands (either directly or inverted),
4645 // then this is min/max of the same flavor.
4646
Sanjay Patel78114302018-01-02 20:56:45 +00004647 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004648 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4649 if (D == B) {
4650 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4651 match(A, m_Not(m_Specific(CmpRHS)))))
4652 return {L.Flavor, SPNB_NA, false};
4653 }
Sanjay Patel78114302018-01-02 20:56:45 +00004654 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004655 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4656 if (C == B) {
4657 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4658 match(A, m_Not(m_Specific(CmpRHS)))))
4659 return {L.Flavor, SPNB_NA, false};
4660 }
Sanjay Patel78114302018-01-02 20:56:45 +00004661 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004662 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4663 if (D == A) {
4664 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4665 match(B, m_Not(m_Specific(CmpRHS)))))
4666 return {L.Flavor, SPNB_NA, false};
4667 }
Sanjay Patel78114302018-01-02 20:56:45 +00004668 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004669 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4670 if (C == A) {
4671 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4672 match(B, m_Not(m_Specific(CmpRHS)))))
4673 return {L.Flavor, SPNB_NA, false};
4674 }
Sanjay Patel78114302018-01-02 20:56:45 +00004675
4676 return {SPF_UNKNOWN, SPNB_NA, false};
4677}
4678
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004679/// Match non-obvious integer minimum and maximum sequences.
4680static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4681 Value *CmpLHS, Value *CmpRHS,
4682 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004683 Value *&LHS, Value *&RHS,
4684 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004685 // Assume success. If there's no match, callers should not use these anyway.
4686 LHS = TrueVal;
4687 RHS = FalseVal;
4688
4689 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4690 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4691 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004692
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004693 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004694 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4695 return SPR;
Fangrui Songf78650a2018-07-30 19:41:25 +00004696
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004697 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004698 return {SPF_UNKNOWN, SPNB_NA, false};
4699
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004700 // Z = X -nsw Y
4701 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4702 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4703 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004704 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004705 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004706
4707 // Z = X -nsw Y
4708 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4709 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4710 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004711 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004712 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004713
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004714 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004715 if (!match(CmpRHS, m_APInt(C1)))
4716 return {SPF_UNKNOWN, SPNB_NA, false};
4717
4718 // An unsigned min/max can be written with a signed compare.
4719 const APInt *C2;
4720 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4721 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4722 // Is the sign bit set?
4723 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4724 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004725 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4726 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004727 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004728
4729 // Is the sign bit clear?
4730 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4731 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004732 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4733 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004734 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004735 }
4736
4737 // Look through 'not' ops to find disguised signed min/max.
4738 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4739 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4740 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004741 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004742 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004743
4744 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4745 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4746 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004747 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004748 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004749
4750 return {SPF_UNKNOWN, SPNB_NA, false};
4751}
4752
Chen Zheng69bb0642018-07-21 12:27:54 +00004753bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004754 assert(X && Y && "Invalid operand");
4755
Chen Zheng69bb0642018-07-21 12:27:54 +00004756 // X = sub (0, Y) || X = sub nsw (0, Y)
4757 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
4758 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004759 return true;
4760
Chen Zheng69bb0642018-07-21 12:27:54 +00004761 // Y = sub (0, X) || Y = sub nsw (0, X)
4762 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
4763 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004764 return true;
4765
Chen Zheng69bb0642018-07-21 12:27:54 +00004766 // 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 +00004767 Value *A, *B;
Chen Zheng69bb0642018-07-21 12:27:54 +00004768 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
4769 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
4770 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
4771 match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
Chen Zhengfdf13ef2018-07-12 03:06:04 +00004772}
4773
James Molloy134bec22015-08-11 09:12:57 +00004774static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4775 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004776 Value *CmpLHS, Value *CmpRHS,
4777 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004778 Value *&LHS, Value *&RHS,
4779 unsigned Depth) {
Sanjay Patele7c94ef2018-11-04 14:28:48 +00004780 if (CmpInst::isFPPredicate(Pred)) {
4781 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
4782 // 0.0 operand, set the compare's 0.0 operands to that same value for the
4783 // purpose of identifying min/max. Disregard vector constants with undefined
4784 // elements because those can not be back-propagated for analysis.
4785 Value *OutputZeroVal = nullptr;
4786 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
4787 !cast<Constant>(TrueVal)->containsUndefElement())
4788 OutputZeroVal = TrueVal;
4789 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
4790 !cast<Constant>(FalseVal)->containsUndefElement())
4791 OutputZeroVal = FalseVal;
4792
4793 if (OutputZeroVal) {
4794 if (match(CmpLHS, m_AnyZeroFP()))
4795 CmpLHS = OutputZeroVal;
4796 if (match(CmpRHS, m_AnyZeroFP()))
4797 CmpRHS = OutputZeroVal;
4798 }
4799 }
4800
James Molloy71b91c22015-05-11 14:42:20 +00004801 LHS = CmpLHS;
4802 RHS = CmpRHS;
4803
Sanjay Patel9a399792017-12-26 15:09:19 +00004804 // Signed zero may return inconsistent results between implementations.
4805 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4806 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4807 // Therefore, we behave conservatively and only proceed if at least one of the
4808 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004809 switch (Pred) {
4810 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004811 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004812 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4813 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4814 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4815 !isKnownNonZero(CmpRHS))
4816 return {SPF_UNKNOWN, SPNB_NA, false};
4817 }
4818
4819 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4820 bool Ordered = false;
4821
4822 // When given one NaN and one non-NaN input:
4823 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4824 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4825 // ordered comparison fails), which could be NaN or non-NaN.
4826 // so here we discover exactly what NaN behavior is required/accepted.
4827 if (CmpInst::isFPPredicate(Pred)) {
4828 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4829 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4830
4831 if (LHSSafe && RHSSafe) {
4832 // Both operands are known non-NaN.
4833 NaNBehavior = SPNB_RETURNS_ANY;
4834 } else if (CmpInst::isOrdered(Pred)) {
4835 // An ordered comparison will return false when given a NaN, so it
4836 // returns the RHS.
4837 Ordered = true;
4838 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004839 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004840 NaNBehavior = SPNB_RETURNS_NAN;
4841 else if (RHSSafe)
4842 NaNBehavior = SPNB_RETURNS_OTHER;
4843 else
4844 // Completely unsafe.
4845 return {SPF_UNKNOWN, SPNB_NA, false};
4846 } else {
4847 Ordered = false;
4848 // An unordered comparison will return true when given a NaN, so it
4849 // returns the LHS.
4850 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004851 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004852 NaNBehavior = SPNB_RETURNS_OTHER;
4853 else if (RHSSafe)
4854 NaNBehavior = SPNB_RETURNS_NAN;
4855 else
4856 // Completely unsafe.
4857 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004858 }
4859 }
4860
James Molloy71b91c22015-05-11 14:42:20 +00004861 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004862 std::swap(CmpLHS, CmpRHS);
4863 Pred = CmpInst::getSwappedPredicate(Pred);
4864 if (NaNBehavior == SPNB_RETURNS_NAN)
4865 NaNBehavior = SPNB_RETURNS_OTHER;
4866 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4867 NaNBehavior = SPNB_RETURNS_NAN;
4868 Ordered = !Ordered;
4869 }
4870
4871 // ([if]cmp X, Y) ? X : Y
4872 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004873 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004874 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004875 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004876 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004877 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004878 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004879 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004880 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004881 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004882 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4883 case FCmpInst::FCMP_UGT:
4884 case FCmpInst::FCMP_UGE:
4885 case FCmpInst::FCMP_OGT:
4886 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4887 case FCmpInst::FCMP_ULT:
4888 case FCmpInst::FCMP_ULE:
4889 case FCmpInst::FCMP_OLT:
4890 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004891 }
4892 }
Fangrui Songf78650a2018-07-30 19:41:25 +00004893
Chen Zhengccc84222018-07-16 02:23:00 +00004894 if (isKnownNegation(TrueVal, FalseVal)) {
4895 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
4896 // match against either LHS or sext(LHS).
4897 auto MaybeSExtCmpLHS =
4898 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
4899 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
4900 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
4901 if (match(TrueVal, MaybeSExtCmpLHS)) {
4902 // Set the return values. If the compare uses the negated value (-X >s 0),
4903 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004904 LHS = TrueVal;
4905 RHS = FalseVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004906 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
4907 std::swap(LHS, RHS);
4908
4909 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
4910 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
4911 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4912 return {SPF_ABS, SPNB_NA, false};
4913
Simon Pilgrima56f2822019-03-19 16:24:55 +00004914 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
4915 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
4916 return {SPF_ABS, SPNB_NA, false};
4917
Chen Zhengccc84222018-07-16 02:23:00 +00004918 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
4919 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
4920 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4921 return {SPF_NABS, SPNB_NA, false};
4922 }
4923 else if (match(FalseVal, MaybeSExtCmpLHS)) {
4924 // Set the return values. If the compare uses the negated value (-X >s 0),
4925 // swap the return values because the negated value is always 'RHS'.
Sanjay Patel284ba0c2018-07-02 14:43:40 +00004926 LHS = FalseVal;
4927 RHS = TrueVal;
Chen Zhengccc84222018-07-16 02:23:00 +00004928 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
4929 std::swap(LHS, RHS);
4930
4931 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
4932 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
4933 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
4934 return {SPF_NABS, SPNB_NA, false};
4935
4936 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
4937 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
4938 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
4939 return {SPF_ABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004940 }
James Molloy71b91c22015-05-11 14:42:20 +00004941 }
4942
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004943 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004944 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004945
4946 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4947 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4948 // semantics than minNum. Be conservative in such case.
4949 if (NaNBehavior != SPNB_RETURNS_ANY ||
4950 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4951 !isKnownNonZero(CmpRHS)))
4952 return {SPF_UNKNOWN, SPNB_NA, false};
4953
4954 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004955}
James Molloy270ef8c2015-05-15 16:04:50 +00004956
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004957/// Helps to match a select pattern in case of a type mismatch.
4958///
4959/// The function processes the case when type of true and false values of a
4960/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004961/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004962/// operation after "select". If yes, it returns the new second value of
4963/// "select" (with the assumption that cast is moved):
4964/// 1. As operand of cast instruction when both values of "select" are same cast
4965/// instructions.
4966/// 2. As restored constant (by applying reverse cast operation) when the first
4967/// value of the "select" is a cast operation and the second value is a
4968/// constant.
4969/// NOTE: We return only the new second value because the first value could be
4970/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004971static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4972 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004973 auto *Cast1 = dyn_cast<CastInst>(V1);
4974 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004975 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004976
Sanjay Patel14a4b812017-01-29 16:34:57 +00004977 *CastOp = Cast1->getOpcode();
4978 Type *SrcTy = Cast1->getSrcTy();
4979 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4980 // If V1 and V2 are both the same cast from the same type, look through V1.
4981 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4982 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004983 return nullptr;
4984 }
4985
Sanjay Patel14a4b812017-01-29 16:34:57 +00004986 auto *C = dyn_cast<Constant>(V2);
4987 if (!C)
4988 return nullptr;
4989
David Majnemerd2a074b2016-04-29 18:40:34 +00004990 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004991 switch (*CastOp) {
4992 case Instruction::ZExt:
4993 if (CmpI->isUnsigned())
4994 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4995 break;
4996 case Instruction::SExt:
4997 if (CmpI->isSigned())
4998 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4999 break;
5000 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00005001 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00005002 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
5003 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00005004 // Here we have the following case:
5005 //
5006 // %cond = cmp iN %x, CmpConst
5007 // %tr = trunc iN %x to iK
5008 // %narrowsel = select i1 %cond, iK %t, iK C
5009 //
5010 // We can always move trunc after select operation:
5011 //
5012 // %cond = cmp iN %x, CmpConst
5013 // %widesel = select i1 %cond, iN %x, iN CmpConst
5014 // %tr = trunc iN %widesel to iK
5015 //
5016 // Note that C could be extended in any way because we don't care about
5017 // upper bits after truncation. It can't be abs pattern, because it would
5018 // look like:
5019 //
5020 // select i1 %cond, x, -x.
5021 //
5022 // So only min/max pattern could be matched. Such match requires widened C
5023 // == CmpConst. That is why set widened C = CmpConst, condition trunc
5024 // CmpConst == C is checked below.
5025 CastedTo = CmpConst;
5026 } else {
5027 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
5028 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00005029 break;
5030 case Instruction::FPTrunc:
5031 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
5032 break;
5033 case Instruction::FPExt:
5034 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
5035 break;
5036 case Instruction::FPToUI:
5037 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
5038 break;
5039 case Instruction::FPToSI:
5040 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
5041 break;
5042 case Instruction::UIToFP:
5043 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
5044 break;
5045 case Instruction::SIToFP:
5046 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
5047 break;
5048 default:
5049 break;
5050 }
David Majnemerd2a074b2016-04-29 18:40:34 +00005051
5052 if (!CastedTo)
5053 return nullptr;
5054
David Majnemerd2a074b2016-04-29 18:40:34 +00005055 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00005056 Constant *CastedBack =
5057 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00005058 if (CastedBack != C)
5059 return nullptr;
5060
5061 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00005062}
5063
Sanjay Patele8dc0902016-05-23 17:57:54 +00005064SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005065 Instruction::CastOps *CastOp,
5066 unsigned Depth) {
5067 if (Depth >= MaxDepth)
5068 return {SPF_UNKNOWN, SPNB_NA, false};
5069
James Molloy270ef8c2015-05-15 16:04:50 +00005070 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00005071 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005072
James Molloy134bec22015-08-11 09:12:57 +00005073 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
5074 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005075
James Molloy134bec22015-08-11 09:12:57 +00005076 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00005077 Value *CmpLHS = CmpI->getOperand(0);
5078 Value *CmpRHS = CmpI->getOperand(1);
5079 Value *TrueVal = SI->getTrueValue();
5080 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00005081 FastMathFlags FMF;
5082 if (isa<FPMathOperator>(CmpI))
5083 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00005084
5085 // Bail out early.
5086 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00005087 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00005088
5089 // Deal with type mismatches.
5090 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00005091 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
5092 // If this is a potential fmin/fmax with a cast to integer, then ignore
5093 // -0.0 because there is no corresponding integer value.
5094 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5095 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005096 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005097 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005098 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005099 }
5100 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
5101 // If this is a potential fmin/fmax with a cast to integer, then ignore
5102 // -0.0 because there is no corresponding integer value.
5103 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
5104 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00005105 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00005106 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005107 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00005108 }
James Molloy270ef8c2015-05-15 16:04:50 +00005109 }
James Molloy134bec22015-08-11 09:12:57 +00005110 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00005111 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00005112}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00005113
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00005114CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
5115 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
5116 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
5117 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
5118 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
5119 if (SPF == SPF_FMINNUM)
5120 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
5121 if (SPF == SPF_FMAXNUM)
5122 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
5123 llvm_unreachable("unhandled!");
5124}
5125
5126SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
5127 if (SPF == SPF_SMIN) return SPF_SMAX;
5128 if (SPF == SPF_UMIN) return SPF_UMAX;
5129 if (SPF == SPF_SMAX) return SPF_SMIN;
5130 if (SPF == SPF_UMAX) return SPF_UMIN;
5131 llvm_unreachable("unhandled!");
5132}
5133
5134CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
5135 return getMinMaxPred(getInverseMinMaxFlavor(SPF));
5136}
5137
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005138/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00005139static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
5140 const Value *RHS, const DataLayout &DL,
5141 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005142 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005143 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
5144 return true;
5145
5146 switch (Pred) {
5147 default:
5148 return false;
5149
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005150 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005151 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005152
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005153 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005154 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005155 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005156 return false;
5157 }
5158
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005159 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00005160 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005161
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005162 // LHS u<= LHS +_{nuw} C for any C
5163 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00005164 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00005165
5166 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00005167 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
5168 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00005169 const APInt *&CA, const APInt *&CB) {
5170 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
5171 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
5172 return true;
5173
5174 // If X & C == 0 then (X | C) == X +_{nuw} C
5175 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
5176 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00005177 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00005178 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
5179 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00005180 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00005181 return true;
5182 }
5183
5184 return false;
5185 };
5186
Pete Cooper35b00d52016-08-13 01:05:32 +00005187 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00005188 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00005189 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
5190 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00005191
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005192 return false;
5193 }
5194 }
5195}
5196
5197/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00005198/// ALHS ARHS" is true. Otherwise, return None.
5199static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00005200isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00005201 const Value *ARHS, const Value *BLHS, const Value *BRHS,
5202 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005203 switch (Pred) {
5204 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00005205 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005206
5207 case CmpInst::ICMP_SLT:
5208 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005209 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
5210 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005211 return true;
5212 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005213
5214 case CmpInst::ICMP_ULT:
5215 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00005216 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
5217 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005218 return true;
5219 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00005220 }
5221}
5222
Chad Rosier226a7342016-05-05 17:41:19 +00005223/// Return true if the operands of the two compares match. IsSwappedOps is true
5224/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00005225static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
5226 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00005227 bool &IsSwappedOps) {
5228
5229 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
5230 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
5231 return IsMatchingOps || IsSwappedOps;
5232}
5233
Sanjay Patel798c5982018-12-19 16:49:18 +00005234/// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
5235/// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
5236/// Otherwise, return None if we can't infer anything.
Chad Rosier41dd31f2016-04-20 19:15:26 +00005237static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Chad Rosier41dd31f2016-04-20 19:15:26 +00005238 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005239 bool AreSwappedOps) {
5240 // Canonicalize the predicate as if the operands were not commuted.
5241 if (AreSwappedOps)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005242 BPred = ICmpInst::getSwappedPredicate(BPred);
Sanjay Patel798c5982018-12-19 16:49:18 +00005243
Chad Rosier99bc4802016-04-21 16:18:02 +00005244 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005245 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00005246 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00005247 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005248
Chad Rosier41dd31f2016-04-20 19:15:26 +00005249 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00005250}
5251
Sanjay Patel798c5982018-12-19 16:49:18 +00005252/// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
5253/// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
5254/// Otherwise, return None if we can't infer anything.
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005255static Optional<bool>
Sanjay Patel798c5982018-12-19 16:49:18 +00005256isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00005257 const ConstantInt *C1,
5258 CmpInst::Predicate BPred,
Sanjay Patel798c5982018-12-19 16:49:18 +00005259 const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005260 ConstantRange DomCR =
5261 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
5262 ConstantRange CR =
5263 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
5264 ConstantRange Intersection = DomCR.intersectWith(CR);
5265 ConstantRange Difference = DomCR.difference(CR);
5266 if (Intersection.isEmptySet())
5267 return false;
5268 if (Difference.isEmptySet())
5269 return true;
5270 return None;
5271}
5272
Chad Rosier2f498032017-07-28 18:47:43 +00005273/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5274/// false. Otherwise, return None if we can't infer anything.
5275static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
5276 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005277 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005278 unsigned Depth) {
5279 Value *ALHS = LHS->getOperand(0);
5280 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00005281 // The rest of the logic assumes the LHS condition is true. If that's not the
5282 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00005283 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005284 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00005285
5286 Value *BLHS = RHS->getOperand(0);
5287 Value *BRHS = RHS->getOperand(1);
5288 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00005289
Chad Rosier226a7342016-05-05 17:41:19 +00005290 // Can we infer anything when the two compares have matching operands?
Sanjay Patel798c5982018-12-19 16:49:18 +00005291 bool AreSwappedOps;
5292 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
Chad Rosier226a7342016-05-05 17:41:19 +00005293 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005294 APred, BPred, AreSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005295 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00005296 // No amount of additional analysis will infer the second condition, so
5297 // early exit.
5298 return None;
5299 }
5300
5301 // Can we infer anything when the LHS operands match and the RHS operands are
5302 // constants (not necessarily matching)?
5303 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
5304 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
Sanjay Patel798c5982018-12-19 16:49:18 +00005305 APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
Chad Rosier226a7342016-05-05 17:41:19 +00005306 return Implication;
5307 // No amount of additional analysis will infer the second condition, so
5308 // early exit.
5309 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00005310 }
5311
Chad Rosier41dd31f2016-04-20 19:15:26 +00005312 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00005313 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00005314 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00005315}
Chad Rosier2f498032017-07-28 18:47:43 +00005316
Chad Rosierf73a10d2017-08-01 19:22:36 +00005317/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
5318/// false. Otherwise, return None if we can't infer anything. We expect the
5319/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
5320static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
5321 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005322 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00005323 unsigned Depth) {
5324 // The LHS must be an 'or' or an 'and' instruction.
5325 assert((LHS->getOpcode() == Instruction::And ||
5326 LHS->getOpcode() == Instruction::Or) &&
5327 "Expected LHS to be 'and' or 'or'.");
5328
Davide Italiano1a943a92017-08-09 16:06:54 +00005329 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00005330
5331 // If the result of an 'or' is false, then we know both legs of the 'or' are
5332 // false. Similarly, if the result of an 'and' is true, then we know both
5333 // legs of the 'and' are true.
5334 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00005335 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
5336 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00005337 // FIXME: Make this non-recursion.
5338 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005339 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005340 return Implication;
5341 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00005342 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00005343 return Implication;
5344 return None;
5345 }
5346 return None;
5347}
5348
Chad Rosier2f498032017-07-28 18:47:43 +00005349Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00005350 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00005351 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00005352 // Bail out when we hit the limit.
5353 if (Depth == MaxDepth)
5354 return None;
5355
Chad Rosierf73a10d2017-08-01 19:22:36 +00005356 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
5357 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00005358 if (LHS->getType() != RHS->getType())
5359 return None;
5360
5361 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00005362 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00005363
5364 // LHS ==> RHS by definition
5365 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005366 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00005367
Chad Rosierf73a10d2017-08-01 19:22:36 +00005368 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00005369 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00005370 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00005371
Chad Rosier2f498032017-07-28 18:47:43 +00005372 assert(OpTy->isIntegerTy(1) && "implied by above");
5373
Chad Rosier2f498032017-07-28 18:47:43 +00005374 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00005375 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
5376 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
5377 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00005378 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005379
Chad Rosierf73a10d2017-08-01 19:22:36 +00005380 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
5381 // an icmp. FIXME: Add support for and/or on the RHS.
5382 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
5383 if (LHSBO && RHSCmp) {
5384 if ((LHSBO->getOpcode() == Instruction::And ||
5385 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00005386 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00005387 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00005388 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00005389}
Sanjay Patel7d82d372018-12-02 13:26:03 +00005390
5391Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
5392 const Instruction *ContextI,
5393 const DataLayout &DL) {
5394 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
5395 if (!ContextI || !ContextI->getParent())
5396 return None;
5397
5398 // TODO: This is a poor/cheap way to determine dominance. Should we use a
5399 // dominator tree (eg, from a SimplifyQuery) instead?
5400 const BasicBlock *ContextBB = ContextI->getParent();
5401 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
5402 if (!PredBB)
5403 return None;
5404
5405 // We need a conditional branch in the predecessor.
5406 Value *PredCond;
5407 BasicBlock *TrueBB, *FalseBB;
5408 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
5409 return None;
5410
5411 // The branch should get simplified. Don't bother simplifying this condition.
5412 if (TrueBB == FalseBB)
5413 return None;
5414
5415 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
5416 "Predecessor block does not point to successor?");
5417
5418 // Is this condition implied by the predecessor condition?
5419 bool CondIsTrue = TrueBB == ContextBB;
5420 return isImpliedCondition(PredCond, Cond, DL, CondIsTrue);
5421}
Nikita Popov49097592019-03-09 21:17:42 +00005422
5423static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
5424 APInt &Upper, const InstrInfoQuery &IIQ) {
5425 unsigned Width = Lower.getBitWidth();
5426 const APInt *C;
5427 switch (BO.getOpcode()) {
5428 case Instruction::Add:
5429 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5430 // FIXME: If we have both nuw and nsw, we should reduce the range further.
5431 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5432 // 'add nuw x, C' produces [C, UINT_MAX].
5433 Lower = *C;
5434 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
5435 if (C->isNegative()) {
5436 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
5437 Lower = APInt::getSignedMinValue(Width);
5438 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5439 } else {
5440 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
5441 Lower = APInt::getSignedMinValue(Width) + *C;
5442 Upper = APInt::getSignedMaxValue(Width) + 1;
5443 }
5444 }
5445 }
5446 break;
5447
5448 case Instruction::And:
5449 if (match(BO.getOperand(1), m_APInt(C)))
5450 // 'and x, C' produces [0, C].
5451 Upper = *C + 1;
5452 break;
5453
5454 case Instruction::Or:
5455 if (match(BO.getOperand(1), m_APInt(C)))
5456 // 'or x, C' produces [C, UINT_MAX].
5457 Lower = *C;
5458 break;
5459
5460 case Instruction::AShr:
5461 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5462 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
5463 Lower = APInt::getSignedMinValue(Width).ashr(*C);
5464 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
5465 } else if (match(BO.getOperand(0), m_APInt(C))) {
5466 unsigned ShiftAmount = Width - 1;
5467 if (!C->isNullValue() && IIQ.isExact(&BO))
5468 ShiftAmount = C->countTrailingZeros();
5469 if (C->isNegative()) {
5470 // 'ashr C, x' produces [C, C >> (Width-1)]
5471 Lower = *C;
5472 Upper = C->ashr(ShiftAmount) + 1;
5473 } else {
5474 // 'ashr C, x' produces [C >> (Width-1), C]
5475 Lower = C->ashr(ShiftAmount);
5476 Upper = *C + 1;
5477 }
5478 }
5479 break;
5480
5481 case Instruction::LShr:
5482 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
5483 // 'lshr x, C' produces [0, UINT_MAX >> C].
5484 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
5485 } else if (match(BO.getOperand(0), m_APInt(C))) {
5486 // 'lshr C, x' produces [C >> (Width-1), C].
5487 unsigned ShiftAmount = Width - 1;
5488 if (!C->isNullValue() && IIQ.isExact(&BO))
5489 ShiftAmount = C->countTrailingZeros();
5490 Lower = C->lshr(ShiftAmount);
5491 Upper = *C + 1;
5492 }
5493 break;
5494
5495 case Instruction::Shl:
5496 if (match(BO.getOperand(0), m_APInt(C))) {
5497 if (IIQ.hasNoUnsignedWrap(&BO)) {
5498 // 'shl nuw C, x' produces [C, C << CLZ(C)]
5499 Lower = *C;
5500 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
5501 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
5502 if (C->isNegative()) {
5503 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
5504 unsigned ShiftAmount = C->countLeadingOnes() - 1;
5505 Lower = C->shl(ShiftAmount);
5506 Upper = *C + 1;
5507 } else {
5508 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
5509 unsigned ShiftAmount = C->countLeadingZeros() - 1;
5510 Lower = *C;
5511 Upper = C->shl(ShiftAmount) + 1;
5512 }
5513 }
5514 }
5515 break;
5516
5517 case Instruction::SDiv:
5518 if (match(BO.getOperand(1), m_APInt(C))) {
5519 APInt IntMin = APInt::getSignedMinValue(Width);
5520 APInt IntMax = APInt::getSignedMaxValue(Width);
5521 if (C->isAllOnesValue()) {
5522 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
5523 // where C != -1 and C != 0 and C != 1
5524 Lower = IntMin + 1;
5525 Upper = IntMax + 1;
5526 } else if (C->countLeadingZeros() < Width - 1) {
5527 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
5528 // where C != -1 and C != 0 and C != 1
5529 Lower = IntMin.sdiv(*C);
5530 Upper = IntMax.sdiv(*C);
5531 if (Lower.sgt(Upper))
5532 std::swap(Lower, Upper);
5533 Upper = Upper + 1;
5534 assert(Upper != Lower && "Upper part of range has wrapped!");
5535 }
5536 } else if (match(BO.getOperand(0), m_APInt(C))) {
5537 if (C->isMinSignedValue()) {
5538 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
5539 Lower = *C;
5540 Upper = Lower.lshr(1) + 1;
5541 } else {
5542 // 'sdiv C, x' produces [-|C|, |C|].
5543 Upper = C->abs() + 1;
5544 Lower = (-Upper) + 1;
5545 }
5546 }
5547 break;
5548
5549 case Instruction::UDiv:
5550 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
5551 // 'udiv x, C' produces [0, UINT_MAX / C].
5552 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
5553 } else if (match(BO.getOperand(0), m_APInt(C))) {
5554 // 'udiv C, x' produces [0, C].
5555 Upper = *C + 1;
5556 }
5557 break;
5558
5559 case Instruction::SRem:
5560 if (match(BO.getOperand(1), m_APInt(C))) {
5561 // 'srem x, C' produces (-|C|, |C|).
5562 Upper = C->abs();
5563 Lower = (-Upper) + 1;
5564 }
5565 break;
5566
5567 case Instruction::URem:
5568 if (match(BO.getOperand(1), m_APInt(C)))
5569 // 'urem x, C' produces [0, C).
5570 Upper = *C;
5571 break;
5572
5573 default:
5574 break;
5575 }
5576}
5577
5578static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
5579 APInt &Upper) {
5580 unsigned Width = Lower.getBitWidth();
5581 const APInt *C;
5582 switch (II.getIntrinsicID()) {
5583 case Intrinsic::uadd_sat:
5584 // uadd.sat(x, C) produces [C, UINT_MAX].
5585 if (match(II.getOperand(0), m_APInt(C)) ||
5586 match(II.getOperand(1), m_APInt(C)))
5587 Lower = *C;
5588 break;
5589 case Intrinsic::sadd_sat:
5590 if (match(II.getOperand(0), m_APInt(C)) ||
5591 match(II.getOperand(1), m_APInt(C))) {
5592 if (C->isNegative()) {
5593 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
5594 Lower = APInt::getSignedMinValue(Width);
5595 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
5596 } else {
5597 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
5598 Lower = APInt::getSignedMinValue(Width) + *C;
5599 Upper = APInt::getSignedMaxValue(Width) + 1;
5600 }
5601 }
5602 break;
5603 case Intrinsic::usub_sat:
5604 // usub.sat(C, x) produces [0, C].
5605 if (match(II.getOperand(0), m_APInt(C)))
5606 Upper = *C + 1;
5607 // usub.sat(x, C) produces [0, UINT_MAX - C].
5608 else if (match(II.getOperand(1), m_APInt(C)))
5609 Upper = APInt::getMaxValue(Width) - *C + 1;
5610 break;
5611 case Intrinsic::ssub_sat:
5612 if (match(II.getOperand(0), m_APInt(C))) {
5613 if (C->isNegative()) {
5614 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
5615 Lower = APInt::getSignedMinValue(Width);
5616 Upper = *C - APInt::getSignedMinValue(Width) + 1;
5617 } else {
5618 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
5619 Lower = *C - APInt::getSignedMaxValue(Width);
5620 Upper = APInt::getSignedMaxValue(Width) + 1;
5621 }
5622 } else if (match(II.getOperand(1), m_APInt(C))) {
5623 if (C->isNegative()) {
5624 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
5625 Lower = APInt::getSignedMinValue(Width) - *C;
5626 Upper = APInt::getSignedMaxValue(Width) + 1;
5627 } else {
5628 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
5629 Lower = APInt::getSignedMinValue(Width);
5630 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
5631 }
5632 }
5633 break;
5634 default:
5635 break;
5636 }
5637}
5638
Nikita Popovf89343b2019-03-18 21:20:03 +00005639static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
5640 APInt &Upper) {
5641 const Value *LHS, *RHS;
5642 SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
5643 if (R.Flavor == SPF_UNKNOWN)
5644 return;
5645
5646 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5647
Nikita Popov00b5eca2019-03-20 18:16:02 +00005648 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
5649 // If the negation part of the abs (in RHS) has the NSW flag,
5650 // then the result of abs(X) is [0..SIGNED_MAX],
5651 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
Nikita Popovf89343b2019-03-18 21:20:03 +00005652 Lower = APInt::getNullValue(BitWidth);
Nikita Popov00b5eca2019-03-20 18:16:02 +00005653 if (cast<Instruction>(RHS)->hasNoSignedWrap())
5654 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5655 else
5656 Upper = APInt::getSignedMinValue(BitWidth) + 1;
Nikita Popovf89343b2019-03-18 21:20:03 +00005657 return;
5658 }
5659
5660 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
5661 // The result of -abs(X) is <= 0.
5662 Lower = APInt::getSignedMinValue(BitWidth);
5663 Upper = APInt(BitWidth, 1);
5664 return;
5665 }
5666
Nikita Popov3db93ac2019-04-07 17:22:16 +00005667 const APInt *C;
5668 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
5669 return;
5670
5671 switch (R.Flavor) {
5672 case SPF_UMIN:
5673 Upper = *C + 1;
5674 break;
5675 case SPF_UMAX:
5676 Lower = *C;
5677 break;
5678 case SPF_SMIN:
5679 Lower = APInt::getSignedMinValue(BitWidth);
5680 Upper = *C + 1;
5681 break;
5682 case SPF_SMAX:
5683 Lower = *C;
5684 Upper = APInt::getSignedMaxValue(BitWidth) + 1;
5685 break;
5686 default:
5687 break;
5688 }
Nikita Popovf89343b2019-03-18 21:20:03 +00005689}
5690
Nikita Popov49097592019-03-09 21:17:42 +00005691ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo) {
5692 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
5693
Nikita Popov20838192019-03-19 17:53:56 +00005694 const APInt *C;
5695 if (match(V, m_APInt(C)))
5696 return ConstantRange(*C);
5697
Nikita Popov49097592019-03-09 21:17:42 +00005698 InstrInfoQuery IIQ(UseInstrInfo);
5699 unsigned BitWidth = V->getType()->getScalarSizeInBits();
5700 APInt Lower = APInt(BitWidth, 0);
5701 APInt Upper = APInt(BitWidth, 0);
5702 if (auto *BO = dyn_cast<BinaryOperator>(V))
5703 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
5704 else if (auto *II = dyn_cast<IntrinsicInst>(V))
5705 setLimitsForIntrinsic(*II, Lower, Upper);
Nikita Popovf89343b2019-03-18 21:20:03 +00005706 else if (auto *SI = dyn_cast<SelectInst>(V))
5707 setLimitsForSelectPattern(*SI, Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005708
Nikita Popovdbc3fba2019-04-21 15:22:54 +00005709 ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
Nikita Popov49097592019-03-09 21:17:42 +00005710
5711 if (auto *I = dyn_cast<Instruction>(V))
5712 if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
5713 CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
5714
5715 return CR;
5716}