blob: 7ae7c4ef939a953942e42e6725abdb1f6c8925bd [file] [log] [blame]
Chris Lattner084a1b52009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sandsa0219882010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsed6d6c32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner084a1b52009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/Statistic.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000023#include "llvm/Analysis/AliasAnalysis.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000024#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000027#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000028#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000029#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalAlias.h"
34#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000036#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000037#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000038using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000039using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000040
Chandler Carruthf1221bd2014-04-22 02:48:03 +000041#define DEBUG_TYPE "instsimplify"
42
Chris Lattner9e4aa022011-02-09 17:15:04 +000043enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000044
Duncan Sands3547d2e2010-12-22 09:40:51 +000045STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumReassoc, "Number of reassociations");
47
Benjamin Kramercfd8d902014-09-12 08:56:53 +000048namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000049struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000051 const TargetLibraryInfo *TLI;
52 const DominatorTree *DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000053 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000054 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000055
Mehdi Aminia28d91d2015-03-10 02:37:25 +000056 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000057 const DominatorTree *dt, AssumptionCache *ac = nullptr,
58 const Instruction *cxti = nullptr)
59 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000060};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000061} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000062
63static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000065 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000066static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000068static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000069 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000070static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
71 const Query &Q, unsigned MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +000072static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
73static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000074static Value *SimplifyCastInst(unsigned, Value *, Type *,
75 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000076
Sanjay Patel472cc782016-01-11 22:14:42 +000077/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000078/// a vector with every element false, as appropriate for the type.
79static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000080 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000081 "Expected i1 type or a vector of i1!");
82 return Constant::getNullValue(Ty);
83}
84
Sanjay Patel472cc782016-01-11 22:14:42 +000085/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000086/// a vector with every element true, as appropriate for the type.
87static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000088 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000089 "Expected i1 type or a vector of i1!");
90 return Constant::getAllOnesValue(Ty);
91}
92
Duncan Sands3d5692a2011-10-30 19:56:36 +000093/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
94static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
95 Value *RHS) {
96 CmpInst *Cmp = dyn_cast<CmpInst>(V);
97 if (!Cmp)
98 return false;
99 CmpInst::Predicate CPred = Cmp->getPredicate();
100 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
101 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
102 return true;
103 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
104 CRHS == LHS;
105}
106
Sanjay Patel472cc782016-01-11 22:14:42 +0000107/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000108static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
109 Instruction *I = dyn_cast<Instruction>(V);
110 if (!I)
111 // Arguments and constants dominate all instructions.
112 return true;
113
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000114 // If we are processing instructions (and/or basic blocks) that have not been
115 // fully added to a function, the parent nodes may still be null. Simply
116 // return the conservative answer in these cases.
117 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
118 return false;
119
Duncan Sands5ffc2982010-11-16 12:16:38 +0000120 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000121 if (DT) {
122 if (!DT->isReachableFromEntry(P->getParent()))
123 return true;
124 if (!DT->isReachableFromEntry(I->getParent()))
125 return false;
126 return DT->dominates(I, P);
127 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000128
David Majnemer8a1c45d2015-12-12 05:38:55 +0000129 // Otherwise, if the instruction is in the entry block and is not an invoke,
130 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000131 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000132 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000133 return true;
134
135 return false;
136}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000137
Sanjay Patel472cc782016-01-11 22:14:42 +0000138/// Simplify "A op (B op' C)" by distributing op over op', turning it into
139/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000140/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
141/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
142/// Returns the simplified value, or null if no simplification was performed.
143static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000144 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000145 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000146 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000147 // Recursion is always used, so bail out at once if we already hit the limit.
148 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000149 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000150
151 // Check whether the expression has the form "(A op' B) op C".
152 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
153 if (Op0->getOpcode() == OpcodeToExpand) {
154 // It does! Try turning it into "(A op C) op' (B op C)".
155 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
156 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000157 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
158 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000159 // They do! Return "L op' R" if it simplifies or is already available.
160 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000161 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
162 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000163 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000164 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000165 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000166 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000167 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000168 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000169 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000170 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000171 }
172 }
173
174 // Check whether the expression has the form "A op (B op' C)".
175 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
176 if (Op1->getOpcode() == OpcodeToExpand) {
177 // It does! Try turning it into "(A op B) op' (A op C)".
178 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
179 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000180 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
181 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000182 // They do! Return "L op' R" if it simplifies or is already available.
183 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000184 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
185 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000186 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000187 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000188 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000190 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000191 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000192 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000193 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000194 }
195 }
196
Craig Topper9f008862014-04-15 04:59:12 +0000197 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000198}
199
Sanjay Patel472cc782016-01-11 22:14:42 +0000200/// Generic simplifications for associative binary operations.
201/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000202static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000203 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000204 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000205 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
206
207 // Recursion is always used, so bail out at once if we already hit the limit.
208 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000209 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000210
211 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
212 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
213
214 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
215 if (Op0 && Op0->getOpcode() == Opcode) {
216 Value *A = Op0->getOperand(0);
217 Value *B = Op0->getOperand(1);
218 Value *C = RHS;
219
220 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000221 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000222 // It does! Return "A op V" if it simplifies or is already available.
223 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000224 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000225 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000226 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000227 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000228 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000229 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000230 }
231 }
232
233 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
234 if (Op1 && Op1->getOpcode() == Opcode) {
235 Value *A = LHS;
236 Value *B = Op1->getOperand(0);
237 Value *C = Op1->getOperand(1);
238
239 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000240 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000241 // It does! Return "V op C" if it simplifies or is already available.
242 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000243 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000244 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000245 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000246 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000247 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000248 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000249 }
250 }
251
252 // The remaining transforms require commutativity as well as associativity.
253 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000254 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000255
256 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
257 if (Op0 && Op0->getOpcode() == Opcode) {
258 Value *A = Op0->getOperand(0);
259 Value *B = Op0->getOperand(1);
260 Value *C = RHS;
261
262 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000263 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000264 // It does! Return "V op B" if it simplifies or is already available.
265 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000266 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000267 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000268 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000269 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000270 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000271 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000272 }
273 }
274
275 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
276 if (Op1 && Op1->getOpcode() == Opcode) {
277 Value *A = LHS;
278 Value *B = Op1->getOperand(0);
279 Value *C = Op1->getOperand(1);
280
281 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000282 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283 // It does! Return "B op V" if it simplifies or is already available.
284 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000285 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000287 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000288 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000289 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000290 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000291 }
292 }
293
Craig Topper9f008862014-04-15 04:59:12 +0000294 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000295}
296
Sanjay Patel472cc782016-01-11 22:14:42 +0000297/// In the case of a binary operation with a select instruction as an operand,
298/// try to simplify the binop by seeing whether evaluating it on both branches
299/// of the select results in the same value. Returns the common value if so,
300/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000301static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000302 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000303 // Recursion is always used, so bail out at once if we already hit the limit.
304 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000305 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000306
Duncan Sandsb0579e92010-11-10 13:00:08 +0000307 SelectInst *SI;
308 if (isa<SelectInst>(LHS)) {
309 SI = cast<SelectInst>(LHS);
310 } else {
311 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
312 SI = cast<SelectInst>(RHS);
313 }
314
315 // Evaluate the BinOp on the true and false branches of the select.
316 Value *TV;
317 Value *FV;
318 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000319 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000321 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000322 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
323 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000324 }
325
Duncan Sandse3c53952011-01-01 16:12:09 +0000326 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000327 // If they both failed to simplify then return null.
328 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000329 return TV;
330
331 // If one branch simplified to undef, return the other one.
332 if (TV && isa<UndefValue>(TV))
333 return FV;
334 if (FV && isa<UndefValue>(FV))
335 return TV;
336
337 // If applying the operation did not change the true and false select values,
338 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000339 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000340 return SI;
341
342 // If one branch simplified and the other did not, and the simplified
343 // value is equal to the unsimplified one, return the simplified value.
344 // For example, select (cond, X, X & Z) & Z -> X & Z.
345 if ((FV && !TV) || (TV && !FV)) {
346 // Check that the simplified value has the form "X op Y" where "op" is the
347 // same as the original operation.
348 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
349 if (Simplified && Simplified->getOpcode() == Opcode) {
350 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
351 // We already know that "op" is the same as for the simplified value. See
352 // if the operands match too. If so, return the simplified value.
353 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
354 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
355 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000356 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
357 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000358 return Simplified;
359 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000360 Simplified->getOperand(1) == UnsimplifiedLHS &&
361 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000362 return Simplified;
363 }
364 }
365
Craig Topper9f008862014-04-15 04:59:12 +0000366 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000367}
368
Sanjay Patel472cc782016-01-11 22:14:42 +0000369/// In the case of a comparison with a select instruction, try to simplify the
370/// comparison by seeing whether both branches of the select result in the same
371/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000372static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000373 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000374 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000375 // Recursion is always used, so bail out at once if we already hit the limit.
376 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000377 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000378
Duncan Sandsb0579e92010-11-10 13:00:08 +0000379 // Make sure the select is on the LHS.
380 if (!isa<SelectInst>(LHS)) {
381 std::swap(LHS, RHS);
382 Pred = CmpInst::getSwappedPredicate(Pred);
383 }
384 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
385 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000386 Value *Cond = SI->getCondition();
387 Value *TV = SI->getTrueValue();
388 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000389
Duncan Sands06504022011-02-03 09:37:39 +0000390 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000391 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000392 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000393 if (TCmp == Cond) {
394 // It not only simplified, it simplified to the select condition. Replace
395 // it with 'true'.
396 TCmp = getTrue(Cond->getType());
397 } else if (!TCmp) {
398 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
399 // condition then we can replace it with 'true'. Otherwise give up.
400 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000401 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000403 }
404
Duncan Sands3d5692a2011-10-30 19:56:36 +0000405 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000406 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000407 if (FCmp == Cond) {
408 // It not only simplified, it simplified to the select condition. Replace
409 // it with 'false'.
410 FCmp = getFalse(Cond->getType());
411 } else if (!FCmp) {
412 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
413 // condition then we can replace it with 'false'. Otherwise give up.
414 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000415 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000416 FCmp = getFalse(Cond->getType());
417 }
418
419 // If both sides simplified to the same value, then use it as the result of
420 // the original comparison.
421 if (TCmp == FCmp)
422 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000423
424 // The remaining cases only make sense if the select condition has the same
425 // type as the result of the comparison, so bail out if this is not so.
426 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000427 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 // If the false value simplified to false, then the result of the compare
429 // is equal to "Cond && TCmp". This also catches the case when the false
430 // value simplified to false and the true value to true, returning "Cond".
431 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000432 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000433 return V;
434 // If the true value simplified to true, then the result of the compare
435 // is equal to "Cond || FCmp".
436 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000437 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000438 return V;
439 // Finally, if the false value simplified to true and the true value to
440 // false, then the result of the compare is equal to "!Cond".
441 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
442 if (Value *V =
443 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000444 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000445 return V;
446
Craig Topper9f008862014-04-15 04:59:12 +0000447 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000448}
449
Sanjay Patel472cc782016-01-11 22:14:42 +0000450/// In the case of a binary operation with an operand that is a PHI instruction,
451/// try to simplify the binop by seeing whether evaluating it on the incoming
452/// phi values yields the same result for every value. If so returns the common
453/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000454static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000455 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000456 // Recursion is always used, so bail out at once if we already hit the limit.
457 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000458 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000459
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000460 PHINode *PI;
461 if (isa<PHINode>(LHS)) {
462 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000463 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000464 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000465 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 } else {
467 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
468 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000469 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000470 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000471 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000472 }
473
474 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000475 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000476 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000477 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000478 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000479 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000480 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
481 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000482 // If the operation failed to simplify, or simplified to a different value
483 // to previously, then give up.
484 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000485 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000486 CommonValue = V;
487 }
488
489 return CommonValue;
490}
491
Sanjay Patel472cc782016-01-11 22:14:42 +0000492/// In the case of a comparison with a PHI instruction, try to simplify the
493/// comparison by seeing whether comparing with all of the incoming phi values
494/// yields the same result every time. If so returns the common result,
495/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000496static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000497 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000498 // Recursion is always used, so bail out at once if we already hit the limit.
499 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000500 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000501
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000502 // Make sure the phi is on the LHS.
503 if (!isa<PHINode>(LHS)) {
504 std::swap(LHS, RHS);
505 Pred = CmpInst::getSwappedPredicate(Pred);
506 }
507 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
508 PHINode *PI = cast<PHINode>(LHS);
509
Duncan Sands5ffc2982010-11-16 12:16:38 +0000510 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000511 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000512 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000513
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000514 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000515 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000516 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000517 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000518 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000519 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000520 // If the operation failed to simplify, or simplified to a different value
521 // to previously, then give up.
522 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000523 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000524 CommonValue = V;
525 }
526
527 return CommonValue;
528}
529
Sanjay Patel472cc782016-01-11 22:14:42 +0000530/// Given operands for an Add, see if we can fold the result.
531/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000532static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000533 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000534 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000535 if (Constant *CRHS = dyn_cast<Constant>(Op1))
536 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000537
Chris Lattner3d9823b2009-11-27 17:42:22 +0000538 // Canonicalize the constant to the RHS.
539 std::swap(Op0, Op1);
540 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000541
Duncan Sands0a2c41682010-12-15 14:07:39 +0000542 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000543 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000544 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000545
Duncan Sands0a2c41682010-12-15 14:07:39 +0000546 // X + 0 -> X
547 if (match(Op1, m_Zero()))
548 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000549
Duncan Sands0a2c41682010-12-15 14:07:39 +0000550 // X + (Y - X) -> Y
551 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000552 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000553 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000554 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
555 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000556 return Y;
557
558 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000559 if (match(Op0, m_Not(m_Specific(Op1))) ||
560 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000561 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000562
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000563 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000564 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000565 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000566 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000567
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000568 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000569 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000570 MaxRecurse))
571 return V;
572
Duncan Sandsb238de02010-11-19 09:20:39 +0000573 // Threading Add over selects and phi nodes is pointless, so don't bother.
574 // Threading over the select in "A + select(cond, B, C)" means evaluating
575 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
576 // only if B and C are equal. If B and C are equal then (since we assume
577 // that operands have already been simplified) "select(cond, B, C)" should
578 // have been simplified to the common value of B and C already. Analysing
579 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
580 // for threading over phi nodes.
581
Craig Topper9f008862014-04-15 04:59:12 +0000582 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000583}
584
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000585Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 const DominatorTree *DT, AssumptionCache *AC,
588 const Instruction *CxtI) {
589 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000590 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000591}
592
Chandler Carrutha0796552012-03-12 11:19:31 +0000593/// \brief Compute the base pointer and cumulative constant offsets for V.
594///
595/// This strips all constant offsets off of V, leaving it the base pointer, and
596/// accumulates the total constant offset applied in the returned constant. It
597/// returns 0 if V is not a pointer, and returns the constant '0' if there are
598/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000599///
600/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
601/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
602/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000603static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000604 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000605 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000606
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000608 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000609
610 // Even though we don't look through PHI nodes, we could be called on an
611 // instruction in an unreachable block, which may be on a cycle.
612 SmallPtrSet<Value *, 4> Visited;
613 Visited.insert(V);
614 do {
615 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000616 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000618 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 V = GEP->getPointerOperand();
620 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000621 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000623 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000624 break;
625 V = GA->getAliasee();
626 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000627 if (auto CS = CallSite(V))
628 if (Value *RV = CS.getReturnedArgOperand()) {
629 V = RV;
630 continue;
631 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000632 break;
633 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000634 assert(V->getType()->getScalarType()->isPointerTy() &&
635 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000636 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000637
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000638 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
639 if (V->getType()->isVectorTy())
640 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
641 OffsetIntPtr);
642 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000643}
644
645/// \brief Compute the constant difference between two pointer values.
646/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000647static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
648 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000649 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
650 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000651
652 // If LHS and RHS are not related via constant offsets to the same base
653 // value, there is nothing we can do here.
654 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000655 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000656
657 // Otherwise, the difference of LHS - RHS can be computed as:
658 // LHS - RHS
659 // = (LHSOffset + Base) - (RHSOffset + Base)
660 // = LHSOffset - RHSOffset
661 return ConstantExpr::getSub(LHSOffset, RHSOffset);
662}
663
Sanjay Patel472cc782016-01-11 22:14:42 +0000664/// Given operands for a Sub, see if we can fold the result.
665/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000666static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000667 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000668 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000669 if (Constant *CRHS = dyn_cast<Constant>(Op1))
670 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000671
672 // X - undef -> undef
673 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000674 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000675 return UndefValue::get(Op0->getType());
676
677 // X - 0 -> X
678 if (match(Op1, m_Zero()))
679 return Op0;
680
681 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000682 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000683 return Constant::getNullValue(Op0->getType());
684
Sanjay Patelefd88852016-10-19 21:23:45 +0000685 // Is this a negation?
686 if (match(Op0, m_Zero())) {
687 // 0 - X -> 0 if the sub is NUW.
688 if (isNUW)
689 return Op0;
690
691 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
692 APInt KnownZero(BitWidth, 0);
693 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000694 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patelefd88852016-10-19 21:23:45 +0000695 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
696 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
697 // Op1 must be 0 because negating the minimum signed value is undefined.
698 if (isNSW)
699 return Op0;
700
701 // 0 - X -> X if X is 0 or the minimum signed value.
702 return Op1;
703 }
704 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000705
Duncan Sands99589d02011-01-18 11:50:19 +0000706 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
707 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000708 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000709 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
710 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000711 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000712 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000713 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000714 // It does, we successfully reassociated!
715 ++NumReassoc;
716 return W;
717 }
718 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000719 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000720 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000721 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000722 // It does, we successfully reassociated!
723 ++NumReassoc;
724 return W;
725 }
726 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000727
Duncan Sands99589d02011-01-18 11:50:19 +0000728 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
729 // For example, X - (X + 1) -> -1
730 X = Op0;
731 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
732 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000736 // It does, we successfully reassociated!
737 ++NumReassoc;
738 return W;
739 }
740 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000741 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000742 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000743 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000744 // It does, we successfully reassociated!
745 ++NumReassoc;
746 return W;
747 }
748 }
749
750 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
751 // For example, X - (X - Y) -> Y.
752 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000753 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
754 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000756 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000757 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000758 // It does, we successfully reassociated!
759 ++NumReassoc;
760 return W;
761 }
762
Duncan Sands395ac42d2012-03-13 14:07:05 +0000763 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
764 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
765 match(Op1, m_Trunc(m_Value(Y))))
766 if (X->getType() == Y->getType())
767 // See if "V === X - Y" simplifies.
768 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
769 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000770 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
771 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000772 // It does, return the simplified "trunc V".
773 return W;
774
775 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000776 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000777 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000778 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000779 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
780
Duncan Sands99589d02011-01-18 11:50:19 +0000781 // i1 sub -> xor.
782 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000783 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000784 return V;
785
Duncan Sands0a2c41682010-12-15 14:07:39 +0000786 // Threading Sub over selects and phi nodes is pointless, so don't bother.
787 // Threading over the select in "A - select(cond, B, C)" means evaluating
788 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
789 // only if B and C are equal. If B and C are equal then (since we assume
790 // that operands have already been simplified) "select(cond, B, C)" should
791 // have been simplified to the common value of B and C already. Analysing
792 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
793 // for threading over phi nodes.
794
Craig Topper9f008862014-04-15 04:59:12 +0000795 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000796}
797
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000798Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000800 const DominatorTree *DT, AssumptionCache *AC,
801 const Instruction *CxtI) {
802 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000803 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000804}
805
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000806/// Given operands for an FAdd, see if we can fold the result. If not, this
807/// returns null.
808static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
809 const Query &Q, unsigned MaxRecurse) {
810 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000811 if (Constant *CRHS = dyn_cast<Constant>(Op1))
812 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000813
814 // Canonicalize the constant to the RHS.
815 std::swap(Op0, Op1);
816 }
817
818 // fadd X, -0 ==> X
819 if (match(Op1, m_NegZero()))
820 return Op0;
821
822 // fadd X, 0 ==> X, when we know X is not -0
823 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000824 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000825 return Op0;
826
827 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
828 // where nnan and ninf have to occur at least once somewhere in this
829 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000830 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000831 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
832 SubOp = Op1;
833 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
834 SubOp = Op0;
835 if (SubOp) {
836 Instruction *FSub = cast<Instruction>(SubOp);
837 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
838 (FMF.noInfs() || FSub->hasNoInfs()))
839 return Constant::getNullValue(Op0->getType());
840 }
841
Craig Topper9f008862014-04-15 04:59:12 +0000842 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000843}
844
845/// Given operands for an FSub, see if we can fold the result. If not, this
846/// returns null.
847static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
848 const Query &Q, unsigned MaxRecurse) {
849 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000850 if (Constant *CRHS = dyn_cast<Constant>(Op1))
851 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852 }
853
854 // fsub X, 0 ==> X
855 if (match(Op1, m_Zero()))
856 return Op0;
857
858 // fsub X, -0 ==> X, when we know X is not -0
859 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000860 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000861 return Op0;
862
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000863 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000864 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000865 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
866 return X;
867
868 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000869 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000870 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
871 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872
Benjamin Kramer228680d2015-06-14 21:01:20 +0000873 // fsub nnan x, x ==> 0.0
874 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000875 return Constant::getNullValue(Op0->getType());
876
Craig Topper9f008862014-04-15 04:59:12 +0000877 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000878}
879
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000880/// Given the operands for an FMul, see if we can fold the result
881static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
882 FastMathFlags FMF,
883 const Query &Q,
884 unsigned MaxRecurse) {
885 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000886 if (Constant *CRHS = dyn_cast<Constant>(Op1))
887 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000888
889 // Canonicalize the constant to the RHS.
890 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000891 }
892
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000893 // fmul X, 1.0 ==> X
894 if (match(Op1, m_FPOne()))
895 return Op0;
896
897 // fmul nnan nsz X, 0 ==> 0
898 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
899 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000900
Craig Topper9f008862014-04-15 04:59:12 +0000901 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000902}
903
Sanjay Patel472cc782016-01-11 22:14:42 +0000904/// Given operands for a Mul, see if we can fold the result.
905/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000906static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
907 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000908 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000909 if (Constant *CRHS = dyn_cast<Constant>(Op1))
910 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000911
912 // Canonicalize the constant to the RHS.
913 std::swap(Op0, Op1);
914 }
915
916 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000917 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000918 return Constant::getNullValue(Op0->getType());
919
920 // X * 0 -> 0
921 if (match(Op1, m_Zero()))
922 return Op1;
923
924 // X * 1 -> X
925 if (match(Op1, m_One()))
926 return Op0;
927
Duncan Sandsb67edc62011-01-30 18:03:50 +0000928 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000929 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000930 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
931 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
932 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000933
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000934 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000935 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000936 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000937 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938
939 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000940 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
944 // Mul distributes over Add. Try some generic simplifications based on this.
945 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000946 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000947 return V;
948
949 // If the operation is with the result of a select instruction, check whether
950 // operating on either branch of the select always yields the same value.
951 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000952 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000953 MaxRecurse))
954 return V;
955
956 // If the operation is with the result of a phi instruction, check whether
957 // operating on all incoming values of the phi always yields the same value.
958 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000959 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000960 MaxRecurse))
961 return V;
962
Craig Topper9f008862014-04-15 04:59:12 +0000963 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000964}
965
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000966Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000968 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000969 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000970 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000971 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000972 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000973}
974
975Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000976 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000977 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000978 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000979 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000980 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000981 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000982}
983
Chandler Carruth66b31302015-01-04 12:03:27 +0000984Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000985 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000986 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000987 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000988 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000989 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000990 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000991}
992
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000993Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000994 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000995 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000996 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000997 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000998 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000999}
1000
Sanjay Patel472cc782016-01-11 22:14:42 +00001001/// Given operands for an SDiv or UDiv, see if we can fold the result.
1002/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001003static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001004 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001005 if (Constant *C0 = dyn_cast<Constant>(Op0))
1006 if (Constant *C1 = dyn_cast<Constant>(Op1))
1007 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001008
Duncan Sands65995fa2011-01-28 18:50:50 +00001009 bool isSigned = Opcode == Instruction::SDiv;
1010
Duncan Sands771e82a2011-01-28 16:51:11 +00001011 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001012 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001013 return Op1;
1014
David Majnemer71dc8fb2014-12-10 07:52:18 +00001015 // X / 0 -> undef, we don't need to preserve faults!
1016 if (match(Op1, m_Zero()))
1017 return UndefValue::get(Op1->getType());
1018
Duncan Sands771e82a2011-01-28 16:51:11 +00001019 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001020 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001021 return Constant::getNullValue(Op0->getType());
1022
1023 // 0 / X -> 0, we don't need to preserve faults!
1024 if (match(Op0, m_Zero()))
1025 return Op0;
1026
1027 // X / 1 -> X
1028 if (match(Op1, m_One()))
1029 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001030
1031 if (Op0->getType()->isIntegerTy(1))
1032 // It can't be division by zero, hence it must be division by one.
1033 return Op0;
1034
1035 // X / X -> 1
1036 if (Op0 == Op1)
1037 return ConstantInt::get(Op0->getType(), 1);
1038
1039 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001040 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001041 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1042 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001043 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001044 // If the Mul knows it does not overflow, then we are good to go.
1045 if ((isSigned && Mul->hasNoSignedWrap()) ||
1046 (!isSigned && Mul->hasNoUnsignedWrap()))
1047 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001048 // If X has the form X = A / Y then X * Y cannot overflow.
1049 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1050 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1051 return X;
1052 }
1053
Duncan Sands65995fa2011-01-28 18:50:50 +00001054 // (X rem Y) / Y -> 0
1055 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1056 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1057 return Constant::getNullValue(Op0->getType());
1058
David Majnemercb9d5962014-10-11 10:20:01 +00001059 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1060 ConstantInt *C1, *C2;
1061 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1062 match(Op1, m_ConstantInt(C2))) {
1063 bool Overflow;
1064 C1->getValue().umul_ov(C2->getValue(), Overflow);
1065 if (Overflow)
1066 return Constant::getNullValue(Op0->getType());
1067 }
1068
Duncan Sands65995fa2011-01-28 18:50:50 +00001069 // If the operation is with the result of a select instruction, check whether
1070 // operating on either branch of the select always yields the same value.
1071 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001072 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001073 return V;
1074
1075 // If the operation is with the result of a phi instruction, check whether
1076 // operating on all incoming values of the phi always yields the same value.
1077 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001078 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001079 return V;
1080
Craig Topper9f008862014-04-15 04:59:12 +00001081 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001082}
1083
Sanjay Patel472cc782016-01-11 22:14:42 +00001084/// Given operands for an SDiv, see if we can fold the result.
1085/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001086static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1087 unsigned MaxRecurse) {
1088 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001089 return V;
1090
Craig Topper9f008862014-04-15 04:59:12 +00001091 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001092}
1093
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001094Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001095 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001096 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001097 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001098 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001099 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001100}
1101
Sanjay Patel472cc782016-01-11 22:14:42 +00001102/// Given operands for a UDiv, see if we can fold the result.
1103/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001104static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1105 unsigned MaxRecurse) {
1106 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001107 return V;
1108
Craig Topper9f008862014-04-15 04:59:12 +00001109 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001110}
1111
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001112Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001113 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001114 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001115 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001116 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001117 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001118}
1119
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001120static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1121 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001122 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001123 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001124 return Op0;
1125
1126 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001127 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001128 return Op1;
1129
Zia Ansari394cef82016-12-08 23:27:40 +00001130 // X / 1.0 -> X
1131 if (match(Op1, m_FPOne()))
1132 return Op0;
1133
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001134 // 0 / X -> 0
1135 // Requires that NaNs are off (X could be zero) and signed zeroes are
1136 // ignored (X could be positive or negative, so the output sign is unknown).
1137 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1138 return Op0;
1139
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001140 if (FMF.noNaNs()) {
1141 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001142 if (Op0 == Op1)
1143 return ConstantFP::get(Op0->getType(), 1.0);
1144
1145 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001146 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001147 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1148 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1149 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1150 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1151 BinaryOperator::getFNegArgument(Op1) == Op0))
1152 return ConstantFP::get(Op0->getType(), -1.0);
1153 }
1154
Craig Topper9f008862014-04-15 04:59:12 +00001155 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001156}
1157
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001158Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001159 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001160 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001161 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001162 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001163 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001164 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001165}
1166
Sanjay Patel472cc782016-01-11 22:14:42 +00001167/// Given operands for an SRem or URem, see if we can fold the result.
1168/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001169static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001170 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001171 if (Constant *C0 = dyn_cast<Constant>(Op0))
1172 if (Constant *C1 = dyn_cast<Constant>(Op1))
1173 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001174
Duncan Sandsa3e36992011-05-02 16:27:02 +00001175 // X % undef -> undef
1176 if (match(Op1, m_Undef()))
1177 return Op1;
1178
1179 // undef % X -> 0
1180 if (match(Op0, m_Undef()))
1181 return Constant::getNullValue(Op0->getType());
1182
1183 // 0 % X -> 0, we don't need to preserve faults!
1184 if (match(Op0, m_Zero()))
1185 return Op0;
1186
1187 // X % 0 -> undef, we don't need to preserve faults!
1188 if (match(Op1, m_Zero()))
1189 return UndefValue::get(Op0->getType());
1190
1191 // X % 1 -> 0
1192 if (match(Op1, m_One()))
1193 return Constant::getNullValue(Op0->getType());
1194
1195 if (Op0->getType()->isIntegerTy(1))
1196 // It can't be remainder by zero, hence it must be remainder by one.
1197 return Constant::getNullValue(Op0->getType());
1198
1199 // X % X -> 0
1200 if (Op0 == Op1)
1201 return Constant::getNullValue(Op0->getType());
1202
David Majnemerb435a422014-09-17 04:16:35 +00001203 // (X % Y) % Y -> X % Y
1204 if ((Opcode == Instruction::SRem &&
1205 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1206 (Opcode == Instruction::URem &&
1207 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001208 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001209
Duncan Sandsa3e36992011-05-02 16:27:02 +00001210 // If the operation is with the result of a select instruction, check whether
1211 // operating on either branch of the select always yields the same value.
1212 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001213 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001214 return V;
1215
1216 // If the operation is with the result of a phi instruction, check whether
1217 // operating on all incoming values of the phi always yields the same value.
1218 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001219 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001220 return V;
1221
Craig Topper9f008862014-04-15 04:59:12 +00001222 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001223}
1224
Sanjay Patel472cc782016-01-11 22:14:42 +00001225/// Given operands for an SRem, see if we can fold the result.
1226/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001227static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1228 unsigned MaxRecurse) {
1229 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230 return V;
1231
Craig Topper9f008862014-04-15 04:59:12 +00001232 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233}
1234
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001235Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001236 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001237 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001238 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001239 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001240 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001241}
1242
Sanjay Patel472cc782016-01-11 22:14:42 +00001243/// Given operands for a URem, see if we can fold the result.
1244/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001245static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001246 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001247 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248 return V;
1249
David Majnemer8c0e62f2017-01-06 21:23:51 +00001250 // urem %V, C -> %V if %V < C
1251 if (MaxRecurse) {
1252 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1253 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1254 if (C->isAllOnesValue()) {
1255 return Op0;
1256 }
1257 }
1258 }
1259
Craig Topper9f008862014-04-15 04:59:12 +00001260 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001261}
1262
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001264 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001265 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001266 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001267 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001268 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001269}
1270
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001271static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1272 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001273 // undef % X -> undef (the undef could be a snan).
1274 if (match(Op0, m_Undef()))
1275 return Op0;
1276
1277 // X % undef -> undef
1278 if (match(Op1, m_Undef()))
1279 return Op1;
1280
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001281 // 0 % X -> 0
1282 // Requires that NaNs are off (X could be zero) and signed zeroes are
1283 // ignored (X could be positive or negative, so the output sign is unknown).
1284 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1285 return Op0;
1286
Craig Topper9f008862014-04-15 04:59:12 +00001287 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001288}
1289
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001290Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001291 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001292 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001293 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001294 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001295 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001296 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001297}
1298
Sanjay Patel472cc782016-01-11 22:14:42 +00001299/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001300static bool isUndefShift(Value *Amount) {
1301 Constant *C = dyn_cast<Constant>(Amount);
1302 if (!C)
1303 return false;
1304
1305 // X shift by undef -> undef because it may shift by the bitwidth.
1306 if (isa<UndefValue>(C))
1307 return true;
1308
1309 // Shifting by the bitwidth or more is undefined.
1310 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1311 if (CI->getValue().getLimitedValue() >=
1312 CI->getType()->getScalarSizeInBits())
1313 return true;
1314
1315 // If all lanes of a vector shift are undefined the whole shift is.
1316 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1317 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1318 if (!isUndefShift(C->getAggregateElement(I)))
1319 return false;
1320 return true;
1321 }
1322
1323 return false;
1324}
1325
Sanjay Patel472cc782016-01-11 22:14:42 +00001326/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1327/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001328static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001329 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001330 if (Constant *C0 = dyn_cast<Constant>(Op0))
1331 if (Constant *C1 = dyn_cast<Constant>(Op1))
1332 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001333
Duncan Sands571fd9a2011-01-14 14:44:12 +00001334 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001335 if (match(Op0, m_Zero()))
1336 return Op0;
1337
Duncan Sands571fd9a2011-01-14 14:44:12 +00001338 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001339 if (match(Op1, m_Zero()))
1340 return Op0;
1341
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001342 // Fold undefined shifts.
1343 if (isUndefShift(Op1))
1344 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001345
Duncan Sands571fd9a2011-01-14 14:44:12 +00001346 // If the operation is with the result of a select instruction, check whether
1347 // operating on either branch of the select always yields the same value.
1348 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001349 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001350 return V;
1351
1352 // If the operation is with the result of a phi instruction, check whether
1353 // operating on all incoming values of the phi always yields the same value.
1354 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001355 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001356 return V;
1357
Sanjay Patel6786bc52016-05-10 20:46:54 +00001358 // If any bits in the shift amount make that value greater than or equal to
1359 // the number of bits in the type, the shift is undefined.
1360 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1361 APInt KnownZero(BitWidth, 0);
1362 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001363 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001364 if (KnownOne.getLimitedValue() >= BitWidth)
1365 return UndefValue::get(Op0->getType());
1366
1367 // If all valid bits in the shift amount are known zero, the first operand is
1368 // unchanged.
1369 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1370 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1371 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1372 return Op0;
1373
Craig Topper9f008862014-04-15 04:59:12 +00001374 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001375}
1376
David Majnemerbf7550e2014-11-05 00:59:59 +00001377/// \brief Given operands for an Shl, LShr or AShr, see if we can
1378/// fold the result. If not, this returns null.
1379static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1380 bool isExact, const Query &Q,
1381 unsigned MaxRecurse) {
1382 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1383 return V;
1384
1385 // X >> X -> 0
1386 if (Op0 == Op1)
1387 return Constant::getNullValue(Op0->getType());
1388
David Majnemer65c52ae2014-12-17 01:54:33 +00001389 // undef >> X -> 0
1390 // undef >> X -> undef (if it's exact)
1391 if (match(Op0, m_Undef()))
1392 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1393
David Majnemerbf7550e2014-11-05 00:59:59 +00001394 // The low bit cannot be shifted out of an exact shift if it is set.
1395 if (isExact) {
1396 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1397 APInt Op0KnownZero(BitWidth, 0);
1398 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001399 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1400 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001401 if (Op0KnownOne[0])
1402 return Op0;
1403 }
1404
1405 return nullptr;
1406}
1407
Sanjay Patel472cc782016-01-11 22:14:42 +00001408/// Given operands for an Shl, see if we can fold the result.
1409/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001410static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001411 const Query &Q, unsigned MaxRecurse) {
1412 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001413 return V;
1414
1415 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001416 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001417 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001418 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001419
Chris Lattner9e4aa022011-02-09 17:15:04 +00001420 // (X >> A) << A -> X
1421 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001422 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001423 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001424 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001425}
1426
Chris Lattner9e4aa022011-02-09 17:15:04 +00001427Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001428 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001429 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001430 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001431 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001432 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001433}
1434
Sanjay Patel472cc782016-01-11 22:14:42 +00001435/// Given operands for an LShr, see if we can fold the result.
1436/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001437static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001438 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001439 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1440 MaxRecurse))
1441 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001442
Chris Lattner9e4aa022011-02-09 17:15:04 +00001443 // (X << A) >> A -> X
1444 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001445 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001446 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001447
Craig Topper9f008862014-04-15 04:59:12 +00001448 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001449}
1450
Chris Lattner9e4aa022011-02-09 17:15:04 +00001451Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001452 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001453 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001454 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001455 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001456 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001457 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001458}
1459
Sanjay Patel472cc782016-01-11 22:14:42 +00001460/// Given operands for an AShr, see if we can fold the result.
1461/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001462static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001463 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001464 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1465 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001466 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001467
1468 // all ones >>a X -> all ones
1469 if (match(Op0, m_AllOnes()))
1470 return Op0;
1471
Chris Lattner9e4aa022011-02-09 17:15:04 +00001472 // (X << A) >> A -> X
1473 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001474 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001475 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001476
Suyog Sarda68862412014-07-17 06:28:15 +00001477 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001478 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001479 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1480 return Op0;
1481
Craig Topper9f008862014-04-15 04:59:12 +00001482 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001483}
1484
Chris Lattner9e4aa022011-02-09 17:15:04 +00001485Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001486 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001487 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001488 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001489 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001490 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001491 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001492}
1493
David Majnemer1af36e52014-12-06 10:51:40 +00001494static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1495 ICmpInst *UnsignedICmp, bool IsAnd) {
1496 Value *X, *Y;
1497
1498 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001499 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1500 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001501 return nullptr;
1502
1503 ICmpInst::Predicate UnsignedPred;
1504 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1505 ICmpInst::isUnsigned(UnsignedPred))
1506 ;
1507 else if (match(UnsignedICmp,
1508 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1509 ICmpInst::isUnsigned(UnsignedPred))
1510 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1511 else
1512 return nullptr;
1513
1514 // X < Y && Y != 0 --> X < Y
1515 // X < Y || Y != 0 --> Y != 0
1516 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1517 return IsAnd ? UnsignedICmp : ZeroICmp;
1518
1519 // X >= Y || Y != 0 --> true
1520 // X >= Y || Y == 0 --> X >= Y
1521 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1522 if (EqPred == ICmpInst::ICMP_NE)
1523 return getTrue(UnsignedICmp->getType());
1524 return UnsignedICmp;
1525 }
1526
David Majnemerd5b3aa42014-12-08 18:30:43 +00001527 // X < Y && Y == 0 --> false
1528 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1529 IsAnd)
1530 return getFalse(UnsignedICmp->getType());
1531
David Majnemer1af36e52014-12-06 10:51:40 +00001532 return nullptr;
1533}
1534
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001535/// Commuted variants are assumed to be handled by calling this function again
1536/// with the parameters swapped.
1537static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1538 ICmpInst::Predicate Pred0, Pred1;
1539 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001540 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1541 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001542 return nullptr;
1543
1544 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1545 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1546 // can eliminate Op1 from this 'and'.
1547 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1548 return Op0;
1549
1550 // Check for any combination of predicates that are guaranteed to be disjoint.
1551 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1552 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1553 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1554 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1555 return getFalse(Op0->getType());
1556
1557 return nullptr;
1558}
1559
1560/// Commuted variants are assumed to be handled by calling this function again
1561/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001562static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001563 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1564 return X;
1565
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001566 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1567 return X;
1568
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001569 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001570 Type *ITy = Op0->getType();
1571 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001572 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001573 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001574 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1575 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1576 // Make a constant range that's the intersection of the two icmp ranges.
1577 // If the intersection is empty, we know that the result is false.
1578 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1579 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1580 if (Range0.intersectWith(Range1).isEmptySet())
1581 return getFalse(ITy);
1582 }
1583
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001584 // (icmp (add V, C0), C1) & (icmp V, C0)
1585 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001586 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001587
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001588 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001589 return nullptr;
1590
David Majnemera315bd82014-09-15 08:15:28 +00001591 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001592 if (AddInst->getOperand(1) != Op1->getOperand(1))
1593 return nullptr;
1594
David Majnemera315bd82014-09-15 08:15:28 +00001595 bool isNSW = AddInst->hasNoSignedWrap();
1596 bool isNUW = AddInst->hasNoUnsignedWrap();
1597
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001598 const APInt Delta = *C1 - *C0;
1599 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001600 if (Delta == 2) {
1601 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1602 return getFalse(ITy);
1603 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1604 return getFalse(ITy);
1605 }
1606 if (Delta == 1) {
1607 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1608 return getFalse(ITy);
1609 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1610 return getFalse(ITy);
1611 }
1612 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001613 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001614 if (Delta == 2)
1615 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1616 return getFalse(ITy);
1617 if (Delta == 1)
1618 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1619 return getFalse(ITy);
1620 }
1621
1622 return nullptr;
1623}
1624
Sanjay Patel472cc782016-01-11 22:14:42 +00001625/// Given operands for an And, see if we can fold the result.
1626/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001627static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001628 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001629 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001630 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1631 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001632
Chris Lattnera71e9d62009-11-10 00:55:12 +00001633 // Canonicalize the constant to the RHS.
1634 std::swap(Op0, Op1);
1635 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001636
Chris Lattnera71e9d62009-11-10 00:55:12 +00001637 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001638 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001639 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001640
Chris Lattnera71e9d62009-11-10 00:55:12 +00001641 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001642 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001643 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001644
Duncan Sandsc89ac072010-11-17 18:52:15 +00001645 // X & 0 = 0
1646 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001647 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001648
Duncan Sandsc89ac072010-11-17 18:52:15 +00001649 // X & -1 = X
1650 if (match(Op1, m_AllOnes()))
1651 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001652
Chris Lattnera71e9d62009-11-10 00:55:12 +00001653 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001654 if (match(Op0, m_Not(m_Specific(Op1))) ||
1655 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001656 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001657
Chris Lattnera71e9d62009-11-10 00:55:12 +00001658 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001659 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001660 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001661 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001662 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001663
Chris Lattnera71e9d62009-11-10 00:55:12 +00001664 // A & (A | ?) = A
1665 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001666 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001667 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001668
Duncan Sandsba286d72011-10-26 20:55:21 +00001669 // A & (-A) = A if A is a power of two or zero.
1670 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1671 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001672 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1673 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001674 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001675 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1676 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001677 return Op1;
1678 }
1679
David Majnemera315bd82014-09-15 08:15:28 +00001680 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1681 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1682 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1683 return V;
1684 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1685 return V;
1686 }
1687 }
1688
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001689 // The compares may be hidden behind casts. Look through those and try the
1690 // same folds as above.
1691 auto *Cast0 = dyn_cast<CastInst>(Op0);
1692 auto *Cast1 = dyn_cast<CastInst>(Op1);
1693 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1694 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1695 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1696 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1697 if (Cmp0 && Cmp1) {
1698 Instruction::CastOps CastOpc = Cast0->getOpcode();
1699 Type *ResultType = Cast0->getType();
1700 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1701 return ConstantExpr::getCast(CastOpc, V, ResultType);
1702 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1703 return ConstantExpr::getCast(CastOpc, V, ResultType);
1704 }
1705 }
1706
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001707 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001708 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1709 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001710 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001711
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001712 // And distributes over Or. Try some generic simplifications based on this.
1713 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001714 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001715 return V;
1716
1717 // And distributes over Xor. Try some generic simplifications based on this.
1718 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001719 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001720 return V;
1721
Duncan Sandsb0579e92010-11-10 13:00:08 +00001722 // If the operation is with the result of a select instruction, check whether
1723 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001724 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001725 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1726 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001727 return V;
1728
1729 // If the operation is with the result of a phi instruction, check whether
1730 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001731 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001732 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001733 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001734 return V;
1735
Craig Topper9f008862014-04-15 04:59:12 +00001736 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001737}
1738
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001739Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001740 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001741 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001742 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001743 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001744 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001745}
1746
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001747/// Commuted variants are assumed to be handled by calling this function again
1748/// with the parameters swapped.
1749static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1750 ICmpInst::Predicate Pred0, Pred1;
1751 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001752 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1753 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001754 return nullptr;
1755
1756 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1757 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1758 // can eliminate Op0 from this 'or'.
1759 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1760 return Op1;
1761
1762 // Check for any combination of predicates that cover the entire range of
1763 // possibilities.
1764 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1765 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1766 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1767 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1768 return getTrue(Op0->getType());
1769
1770 return nullptr;
1771}
1772
1773/// Commuted variants are assumed to be handled by calling this function again
1774/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001775static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001776 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1777 return X;
1778
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001779 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1780 return X;
1781
Sanjay Patel220a8732016-09-28 14:27:21 +00001782 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001783 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001784 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001785 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001786 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001787 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001788
Sanjay Patel220a8732016-09-28 14:27:21 +00001789 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1790 return nullptr;
1791
1792 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1793 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001794 return nullptr;
1795
1796 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001797 bool isNSW = AddInst->hasNoSignedWrap();
1798 bool isNUW = AddInst->hasNoUnsignedWrap();
1799
Sanjay Patel220a8732016-09-28 14:27:21 +00001800 const APInt Delta = *C1 - *C0;
1801 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001802 if (Delta == 2) {
1803 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1804 return getTrue(ITy);
1805 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1806 return getTrue(ITy);
1807 }
1808 if (Delta == 1) {
1809 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1810 return getTrue(ITy);
1811 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1812 return getTrue(ITy);
1813 }
1814 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001815 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001816 if (Delta == 2)
1817 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1818 return getTrue(ITy);
1819 if (Delta == 1)
1820 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1821 return getTrue(ITy);
1822 }
1823
1824 return nullptr;
1825}
1826
Sanjay Patel472cc782016-01-11 22:14:42 +00001827/// Given operands for an Or, see if we can fold the result.
1828/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001829static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1830 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001831 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001832 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1833 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001834
Chris Lattnera71e9d62009-11-10 00:55:12 +00001835 // Canonicalize the constant to the RHS.
1836 std::swap(Op0, Op1);
1837 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001838
Chris Lattnera71e9d62009-11-10 00:55:12 +00001839 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001840 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001841 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001842
Chris Lattnera71e9d62009-11-10 00:55:12 +00001843 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001844 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001845 return Op0;
1846
Duncan Sandsc89ac072010-11-17 18:52:15 +00001847 // X | 0 = X
1848 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001849 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001850
Duncan Sandsc89ac072010-11-17 18:52:15 +00001851 // X | -1 = -1
1852 if (match(Op1, m_AllOnes()))
1853 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001854
Chris Lattnera71e9d62009-11-10 00:55:12 +00001855 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001856 if (match(Op0, m_Not(m_Specific(Op1))) ||
1857 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001858 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001859
Chris Lattnera71e9d62009-11-10 00:55:12 +00001860 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001861 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001862 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001863 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001864 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001865
Chris Lattnera71e9d62009-11-10 00:55:12 +00001866 // A | (A & ?) = A
1867 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001868 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001869 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001870
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001871 // ~(A & ?) | A = -1
1872 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1873 (A == Op1 || B == Op1))
1874 return Constant::getAllOnesValue(Op1->getType());
1875
1876 // A | ~(A & ?) = -1
1877 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1878 (A == Op0 || B == Op0))
1879 return Constant::getAllOnesValue(Op0->getType());
1880
David Majnemera315bd82014-09-15 08:15:28 +00001881 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1882 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1883 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1884 return V;
1885 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1886 return V;
1887 }
1888 }
1889
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001890 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001891 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1892 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001893 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001894
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001895 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001896 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1897 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001898 return V;
1899
Duncan Sandsb0579e92010-11-10 13:00:08 +00001900 // If the operation is with the result of a select instruction, check whether
1901 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001902 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001903 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001904 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001905 return V;
1906
Nick Lewycky8561a492014-06-19 03:51:46 +00001907 // (A & C)|(B & D)
1908 Value *C = nullptr, *D = nullptr;
1909 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1910 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1911 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1912 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1913 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1914 // (A & C1)|(B & C2)
1915 // If we have: ((V + N) & C1) | (V & C2)
1916 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1917 // replace with V+N.
1918 Value *V1, *V2;
1919 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1920 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1921 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001922 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001923 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001924 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001925 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001926 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001927 return A;
1928 }
1929 // Or commutes, try both ways.
1930 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1931 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1932 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001933 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001934 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001935 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001936 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001937 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001938 return B;
1939 }
1940 }
1941 }
1942
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001943 // If the operation is with the result of a phi instruction, check whether
1944 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001945 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001946 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001947 return V;
1948
Craig Topper9f008862014-04-15 04:59:12 +00001949 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001950}
1951
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001952Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001953 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001954 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001955 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001956 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001957 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001958}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001959
Sanjay Patel472cc782016-01-11 22:14:42 +00001960/// Given operands for a Xor, see if we can fold the result.
1961/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001962static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1963 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001964 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001965 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1966 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001967
1968 // Canonicalize the constant to the RHS.
1969 std::swap(Op0, Op1);
1970 }
1971
1972 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001973 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001974 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001975
1976 // A ^ 0 = A
1977 if (match(Op1, m_Zero()))
1978 return Op0;
1979
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001980 // A ^ A = 0
1981 if (Op0 == Op1)
1982 return Constant::getNullValue(Op0->getType());
1983
Duncan Sandsc89ac072010-11-17 18:52:15 +00001984 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001985 if (match(Op0, m_Not(m_Specific(Op1))) ||
1986 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001987 return Constant::getAllOnesValue(Op0->getType());
1988
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001989 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001990 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1991 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001992 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001993
Duncan Sandsb238de02010-11-19 09:20:39 +00001994 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1995 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1996 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1997 // only if B and C are equal. If B and C are equal then (since we assume
1998 // that operands have already been simplified) "select(cond, B, C)" should
1999 // have been simplified to the common value of B and C already. Analysing
2000 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2001 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002002
Craig Topper9f008862014-04-15 04:59:12 +00002003 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002004}
2005
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002006Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002007 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002008 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002009 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002010 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002011 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002012}
2013
Chris Lattner229907c2011-07-18 04:54:35 +00002014static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002015 return CmpInst::makeCmpResultType(Op->getType());
2016}
2017
Sanjay Patel472cc782016-01-11 22:14:42 +00002018/// Rummage around inside V looking for something equivalent to the comparison
2019/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2020/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002021static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2022 Value *LHS, Value *RHS) {
2023 SelectInst *SI = dyn_cast<SelectInst>(V);
2024 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002025 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002026 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2027 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002028 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002029 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2030 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2031 return Cmp;
2032 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2033 LHS == CmpRHS && RHS == CmpLHS)
2034 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002035 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002036}
2037
Dan Gohman9631d902013-02-01 00:49:06 +00002038// A significant optimization not implemented here is assuming that alloca
2039// addresses are not equal to incoming argument values. They don't *alias*,
2040// as we say, but that doesn't mean they aren't equal, so we take a
2041// conservative approach.
2042//
2043// This is inspired in part by C++11 5.10p1:
2044// "Two pointers of the same type compare equal if and only if they are both
2045// null, both point to the same function, or both represent the same
2046// address."
2047//
2048// This is pretty permissive.
2049//
2050// It's also partly due to C11 6.5.9p6:
2051// "Two pointers compare equal if and only if both are null pointers, both are
2052// pointers to the same object (including a pointer to an object and a
2053// subobject at its beginning) or function, both are pointers to one past the
2054// last element of the same array object, or one is a pointer to one past the
2055// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002056// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002057// object in the address space.)
2058//
2059// C11's version is more restrictive, however there's no reason why an argument
2060// couldn't be a one-past-the-end value for a stack object in the caller and be
2061// equal to the beginning of a stack object in the callee.
2062//
2063// If the C and C++ standards are ever made sufficiently restrictive in this
2064// area, it may be possible to update LLVM's semantics accordingly and reinstate
2065// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002066static Constant *
2067computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2068 const DominatorTree *DT, CmpInst::Predicate Pred,
2069 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002070 // First, skip past any trivial no-ops.
2071 LHS = LHS->stripPointerCasts();
2072 RHS = RHS->stripPointerCasts();
2073
2074 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002075 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002076 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2077 return ConstantInt::get(GetCompareTy(LHS),
2078 !CmpInst::isTrueWhenEqual(Pred));
2079
Chandler Carruth8059c842012-03-25 21:28:14 +00002080 // We can only fold certain predicates on pointer comparisons.
2081 switch (Pred) {
2082 default:
Craig Topper9f008862014-04-15 04:59:12 +00002083 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002084
2085 // Equality comaprisons are easy to fold.
2086 case CmpInst::ICMP_EQ:
2087 case CmpInst::ICMP_NE:
2088 break;
2089
2090 // We can only handle unsigned relational comparisons because 'inbounds' on
2091 // a GEP only protects against unsigned wrapping.
2092 case CmpInst::ICMP_UGT:
2093 case CmpInst::ICMP_UGE:
2094 case CmpInst::ICMP_ULT:
2095 case CmpInst::ICMP_ULE:
2096 // However, we have to switch them to their signed variants to handle
2097 // negative indices from the base pointer.
2098 Pred = ICmpInst::getSignedPredicate(Pred);
2099 break;
2100 }
2101
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002102 // Strip off any constant offsets so that we can reason about them.
2103 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2104 // here and compare base addresses like AliasAnalysis does, however there are
2105 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2106 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2107 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002108 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2109 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002110
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002111 // If LHS and RHS are related via constant offsets to the same base
2112 // value, we can replace it with an icmp which just compares the offsets.
2113 if (LHS == RHS)
2114 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002115
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002116 // Various optimizations for (in)equality comparisons.
2117 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2118 // Different non-empty allocations that exist at the same time have
2119 // different addresses (if the program can tell). Global variables always
2120 // exist, so they always exist during the lifetime of each other and all
2121 // allocas. Two different allocas usually have different addresses...
2122 //
2123 // However, if there's an @llvm.stackrestore dynamically in between two
2124 // allocas, they may have the same address. It's tempting to reduce the
2125 // scope of the problem by only looking at *static* allocas here. That would
2126 // cover the majority of allocas while significantly reducing the likelihood
2127 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2128 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2129 // an entry block. Also, if we have a block that's not attached to a
2130 // function, we can't tell if it's "static" under the current definition.
2131 // Theoretically, this problem could be fixed by creating a new kind of
2132 // instruction kind specifically for static allocas. Such a new instruction
2133 // could be required to be at the top of the entry block, thus preventing it
2134 // from being subject to a @llvm.stackrestore. Instcombine could even
2135 // convert regular allocas into these special allocas. It'd be nifty.
2136 // However, until then, this problem remains open.
2137 //
2138 // So, we'll assume that two non-empty allocas have different addresses
2139 // for now.
2140 //
2141 // With all that, if the offsets are within the bounds of their allocations
2142 // (and not one-past-the-end! so we can't use inbounds!), and their
2143 // allocations aren't the same, the pointers are not equal.
2144 //
2145 // Note that it's not necessary to check for LHS being a global variable
2146 // address, due to canonicalization and constant folding.
2147 if (isa<AllocaInst>(LHS) &&
2148 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002149 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2150 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002151 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002152 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002153 getObjectSize(LHS, LHSSize, DL, TLI) &&
2154 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002155 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2156 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002157 if (!LHSOffsetValue.isNegative() &&
2158 !RHSOffsetValue.isNegative() &&
2159 LHSOffsetValue.ult(LHSSize) &&
2160 RHSOffsetValue.ult(RHSSize)) {
2161 return ConstantInt::get(GetCompareTy(LHS),
2162 !CmpInst::isTrueWhenEqual(Pred));
2163 }
2164 }
2165
2166 // Repeat the above check but this time without depending on DataLayout
2167 // or being able to compute a precise size.
2168 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2169 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2170 LHSOffset->isNullValue() &&
2171 RHSOffset->isNullValue())
2172 return ConstantInt::get(GetCompareTy(LHS),
2173 !CmpInst::isTrueWhenEqual(Pred));
2174 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002175
2176 // Even if an non-inbounds GEP occurs along the path we can still optimize
2177 // equality comparisons concerning the result. We avoid walking the whole
2178 // chain again by starting where the last calls to
2179 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002180 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2181 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002182 if (LHS == RHS)
2183 return ConstantExpr::getICmp(Pred,
2184 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2185 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002186
2187 // If one side of the equality comparison must come from a noalias call
2188 // (meaning a system memory allocation function), and the other side must
2189 // come from a pointer that cannot overlap with dynamically-allocated
2190 // memory within the lifetime of the current function (allocas, byval
2191 // arguments, globals), then determine the comparison result here.
2192 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2193 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2194 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2195
2196 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002197 auto IsNAC = [](ArrayRef<Value *> Objects) {
2198 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002199 };
2200
2201 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002202 // noalias calls. For allocas, we consider only static ones (dynamic
2203 // allocas might be transformed into calls to malloc not simultaneously
2204 // live with the compared-to allocation). For globals, we exclude symbols
2205 // that might be resolve lazily to symbols in another dynamically-loaded
2206 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002207 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2208 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002209 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2210 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2211 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2212 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002213 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002214 !GV->isThreadLocal();
2215 if (const Argument *A = dyn_cast<Argument>(V))
2216 return A->hasByValAttr();
2217 return false;
2218 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002219 };
2220
2221 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2222 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2223 return ConstantInt::get(GetCompareTy(LHS),
2224 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002225
2226 // Fold comparisons for non-escaping pointer even if the allocation call
2227 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2228 // dynamic allocation call could be either of the operands.
2229 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002230 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002231 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002232 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002233 MI = RHS;
2234 // FIXME: We should also fold the compare when the pointer escapes, but the
2235 // compare dominates the pointer escape
2236 if (MI && !PointerMayBeCaptured(MI, true, true))
2237 return ConstantInt::get(GetCompareTy(LHS),
2238 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002239 }
2240
2241 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002242 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002243}
Chris Lattner01990f02012-02-24 19:01:58 +00002244
Sanjay Pateldc65a272016-12-03 17:30:22 +00002245/// Fold an icmp when its operands have i1 scalar type.
2246static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2247 Value *RHS, const Query &Q) {
2248 Type *ITy = GetCompareTy(LHS); // The return type.
2249 Type *OpTy = LHS->getType(); // The operand type.
2250 if (!OpTy->getScalarType()->isIntegerTy(1))
2251 return nullptr;
2252
2253 switch (Pred) {
2254 default:
2255 break;
2256 case ICmpInst::ICMP_EQ:
2257 // X == 1 -> X
2258 if (match(RHS, m_One()))
2259 return LHS;
2260 break;
2261 case ICmpInst::ICMP_NE:
2262 // X != 0 -> X
2263 if (match(RHS, m_Zero()))
2264 return LHS;
2265 break;
2266 case ICmpInst::ICMP_UGT:
2267 // X >u 0 -> X
2268 if (match(RHS, m_Zero()))
2269 return LHS;
2270 break;
2271 case ICmpInst::ICMP_UGE:
2272 // X >=u 1 -> X
2273 if (match(RHS, m_One()))
2274 return LHS;
2275 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2276 return getTrue(ITy);
2277 break;
2278 case ICmpInst::ICMP_SGE:
2279 /// For signed comparison, the values for an i1 are 0 and -1
2280 /// respectively. This maps into a truth table of:
2281 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2282 /// 0 | 0 | 1 (0 >= 0) | 1
2283 /// 0 | 1 | 1 (0 >= -1) | 1
2284 /// 1 | 0 | 0 (-1 >= 0) | 0
2285 /// 1 | 1 | 1 (-1 >= -1) | 1
2286 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2287 return getTrue(ITy);
2288 break;
2289 case ICmpInst::ICMP_SLT:
2290 // X <s 0 -> X
2291 if (match(RHS, m_Zero()))
2292 return LHS;
2293 break;
2294 case ICmpInst::ICMP_SLE:
2295 // X <=s -1 -> X
2296 if (match(RHS, m_One()))
2297 return LHS;
2298 break;
2299 case ICmpInst::ICMP_ULE:
2300 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2301 return getTrue(ITy);
2302 break;
2303 }
2304
2305 return nullptr;
2306}
2307
2308/// Try hard to fold icmp with zero RHS because this is a common case.
2309static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2310 Value *RHS, const Query &Q) {
2311 if (!match(RHS, m_Zero()))
2312 return nullptr;
2313
2314 Type *ITy = GetCompareTy(LHS); // The return type.
2315 bool LHSKnownNonNegative, LHSKnownNegative;
2316 switch (Pred) {
2317 default:
2318 llvm_unreachable("Unknown ICmp predicate!");
2319 case ICmpInst::ICMP_ULT:
2320 return getFalse(ITy);
2321 case ICmpInst::ICMP_UGE:
2322 return getTrue(ITy);
2323 case ICmpInst::ICMP_EQ:
2324 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002325 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002326 return getFalse(ITy);
2327 break;
2328 case ICmpInst::ICMP_NE:
2329 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002330 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002331 return getTrue(ITy);
2332 break;
2333 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002334 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2335 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002336 if (LHSKnownNegative)
2337 return getTrue(ITy);
2338 if (LHSKnownNonNegative)
2339 return getFalse(ITy);
2340 break;
2341 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002342 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2343 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002344 if (LHSKnownNegative)
2345 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002346 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002347 return getFalse(ITy);
2348 break;
2349 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002350 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2351 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002352 if (LHSKnownNegative)
2353 return getFalse(ITy);
2354 if (LHSKnownNonNegative)
2355 return getTrue(ITy);
2356 break;
2357 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002358 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2359 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002360 if (LHSKnownNegative)
2361 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002362 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002363 return getTrue(ITy);
2364 break;
2365 }
2366
2367 return nullptr;
2368}
2369
Sanjay Patel67bde282016-08-22 23:12:02 +00002370static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2371 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002372 const APInt *C;
2373 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002374 return nullptr;
2375
2376 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002377 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002378 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002379 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002380 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002381 return ConstantInt::getTrue(GetCompareTy(RHS));
2382
Sanjay Patel67bde282016-08-22 23:12:02 +00002383 // Many binary operators with constant RHS have easy to compute constant
2384 // range. Use them to check whether the comparison is a tautology.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002385 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002386 APInt Lower = APInt(Width, 0);
2387 APInt Upper = APInt(Width, 0);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002388 const APInt *C2;
2389 if (match(LHS, m_URem(m_Value(), m_APInt(C2)))) {
2390 // 'urem x, C2' produces [0, C2).
2391 Upper = *C2;
2392 } else if (match(LHS, m_SRem(m_Value(), m_APInt(C2)))) {
2393 // 'srem x, C2' produces (-|C2|, |C2|).
2394 Upper = C2->abs();
Sanjay Patel67bde282016-08-22 23:12:02 +00002395 Lower = (-Upper) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002396 } else if (match(LHS, m_UDiv(m_APInt(C2), m_Value()))) {
2397 // 'udiv C2, x' produces [0, C2].
2398 Upper = *C2 + 1;
2399 } else if (match(LHS, m_UDiv(m_Value(), m_APInt(C2)))) {
2400 // 'udiv x, C2' produces [0, UINT_MAX / C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002401 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002402 if (*C2 != 0)
2403 Upper = NegOne.udiv(*C2) + 1;
2404 } else if (match(LHS, m_SDiv(m_APInt(C2), m_Value()))) {
2405 if (C2->isMinSignedValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002406 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002407 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002408 Upper = Lower.lshr(1) + 1;
2409 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002410 // 'sdiv C2, x' produces [-|C2|, |C2|].
2411 Upper = C2->abs() + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002412 Lower = (-Upper) + 1;
2413 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002414 } else if (match(LHS, m_SDiv(m_Value(), m_APInt(C2)))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002415 APInt IntMin = APInt::getSignedMinValue(Width);
2416 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002417 if (C2->isAllOnesValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002418 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002419 // where C2 != -1 and C2 != 0 and C2 != 1
Sanjay Patel67bde282016-08-22 23:12:02 +00002420 Lower = IntMin + 1;
2421 Upper = IntMax + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002422 } else if (C2->countLeadingZeros() < Width - 1) {
2423 // 'sdiv x, C2' produces [INT_MIN / C2, INT_MAX / C2]
2424 // where C2 != -1 and C2 != 0 and C2 != 1
2425 Lower = IntMin.sdiv(*C2);
2426 Upper = IntMax.sdiv(*C2);
Sanjay Patel67bde282016-08-22 23:12:02 +00002427 if (Lower.sgt(Upper))
2428 std::swap(Lower, Upper);
2429 Upper = Upper + 1;
2430 assert(Upper != Lower && "Upper part of range has wrapped!");
2431 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002432 } else if (match(LHS, m_NUWShl(m_APInt(C2), m_Value()))) {
2433 // 'shl nuw C2, x' produces [C2, C2 << CLZ(C2)]
2434 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002435 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002436 } else if (match(LHS, m_NSWShl(m_APInt(C2), m_Value()))) {
2437 if (C2->isNegative()) {
2438 // 'shl nsw C2, x' produces [C2 << CLO(C2)-1, C2]
2439 unsigned ShiftAmount = C2->countLeadingOnes() - 1;
2440 Lower = C2->shl(ShiftAmount);
2441 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002442 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002443 // 'shl nsw C2, x' produces [C2, C2 << CLZ(C2)-1]
2444 unsigned ShiftAmount = C2->countLeadingZeros() - 1;
2445 Lower = *C2;
2446 Upper = C2->shl(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002447 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002448 } else if (match(LHS, m_LShr(m_Value(), m_APInt(C2)))) {
2449 // 'lshr x, C2' produces [0, UINT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002450 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002451 if (C2->ult(Width))
2452 Upper = NegOne.lshr(*C2) + 1;
2453 } else if (match(LHS, m_LShr(m_APInt(C2), m_Value()))) {
2454 // 'lshr C2, x' produces [C2 >> (Width-1), C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002455 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002456 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2457 ShiftAmount = C2->countTrailingZeros();
2458 Lower = C2->lshr(ShiftAmount);
2459 Upper = *C2 + 1;
2460 } else if (match(LHS, m_AShr(m_Value(), m_APInt(C2)))) {
2461 // 'ashr x, C2' produces [INT_MIN >> C2, INT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002462 APInt IntMin = APInt::getSignedMinValue(Width);
2463 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002464 if (C2->ult(Width)) {
2465 Lower = IntMin.ashr(*C2);
2466 Upper = IntMax.ashr(*C2) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002467 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002468 } else if (match(LHS, m_AShr(m_APInt(C2), m_Value()))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002469 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002470 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2471 ShiftAmount = C2->countTrailingZeros();
2472 if (C2->isNegative()) {
2473 // 'ashr C2, x' produces [C2, C2 >> (Width-1)]
2474 Lower = *C2;
2475 Upper = C2->ashr(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002476 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002477 // 'ashr C2, x' produces [C2 >> (Width-1), C2]
2478 Lower = C2->ashr(ShiftAmount);
2479 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002480 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002481 } else if (match(LHS, m_Or(m_Value(), m_APInt(C2)))) {
2482 // 'or x, C2' produces [C2, UINT_MAX].
2483 Lower = *C2;
2484 } else if (match(LHS, m_And(m_Value(), m_APInt(C2)))) {
2485 // 'and x, C2' produces [0, C2].
2486 Upper = *C2 + 1;
2487 } else if (match(LHS, m_NUWAdd(m_Value(), m_APInt(C2)))) {
2488 // 'add nuw x, C2' produces [C2, UINT_MAX].
2489 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002490 }
2491
2492 ConstantRange LHS_CR =
2493 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2494
2495 if (auto *I = dyn_cast<Instruction>(LHS))
2496 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2497 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2498
2499 if (!LHS_CR.isFullSet()) {
2500 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002501 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002502 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002503 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002504 }
2505
2506 return nullptr;
2507}
2508
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002509static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2510 Value *RHS, const Query &Q,
2511 unsigned MaxRecurse) {
2512 Type *ITy = GetCompareTy(LHS); // The return type.
2513
2514 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2515 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2516 if (MaxRecurse && (LBO || RBO)) {
2517 // Analyze the case when either LHS or RHS is an add instruction.
2518 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2519 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2520 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2521 if (LBO && LBO->getOpcode() == Instruction::Add) {
2522 A = LBO->getOperand(0);
2523 B = LBO->getOperand(1);
2524 NoLHSWrapProblem =
2525 ICmpInst::isEquality(Pred) ||
2526 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2527 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2528 }
2529 if (RBO && RBO->getOpcode() == Instruction::Add) {
2530 C = RBO->getOperand(0);
2531 D = RBO->getOperand(1);
2532 NoRHSWrapProblem =
2533 ICmpInst::isEquality(Pred) ||
2534 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2535 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2536 }
2537
2538 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2539 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2540 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2541 Constant::getNullValue(RHS->getType()), Q,
2542 MaxRecurse - 1))
2543 return V;
2544
2545 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2546 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2547 if (Value *V =
2548 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2549 C == LHS ? D : C, Q, MaxRecurse - 1))
2550 return V;
2551
2552 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2553 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2554 NoRHSWrapProblem) {
2555 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2556 Value *Y, *Z;
2557 if (A == C) {
2558 // C + B == C + D -> B == D
2559 Y = B;
2560 Z = D;
2561 } else if (A == D) {
2562 // D + B == C + D -> B == C
2563 Y = B;
2564 Z = C;
2565 } else if (B == C) {
2566 // A + C == C + D -> A == D
2567 Y = A;
2568 Z = D;
2569 } else {
2570 assert(B == D);
2571 // A + D == C + D -> A == C
2572 Y = A;
2573 Z = C;
2574 }
2575 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2576 return V;
2577 }
2578 }
2579
2580 {
2581 Value *Y = nullptr;
2582 // icmp pred (or X, Y), X
2583 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2584 if (Pred == ICmpInst::ICMP_ULT)
2585 return getFalse(ITy);
2586 if (Pred == ICmpInst::ICMP_UGE)
2587 return getTrue(ITy);
2588
2589 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2590 bool RHSKnownNonNegative, RHSKnownNegative;
2591 bool YKnownNonNegative, YKnownNegative;
2592 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002593 Q.AC, Q.CxtI, Q.DT);
2594 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002595 Q.CxtI, Q.DT);
2596 if (RHSKnownNonNegative && YKnownNegative)
2597 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2598 if (RHSKnownNegative || YKnownNonNegative)
2599 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2600 }
2601 }
2602 // icmp pred X, (or X, Y)
2603 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2604 if (Pred == ICmpInst::ICMP_ULE)
2605 return getTrue(ITy);
2606 if (Pred == ICmpInst::ICMP_UGT)
2607 return getFalse(ITy);
2608
2609 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2610 bool LHSKnownNonNegative, LHSKnownNegative;
2611 bool YKnownNonNegative, YKnownNegative;
2612 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002613 Q.AC, Q.CxtI, Q.DT);
2614 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002615 Q.CxtI, Q.DT);
2616 if (LHSKnownNonNegative && YKnownNegative)
2617 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2618 if (LHSKnownNegative || YKnownNonNegative)
2619 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2620 }
2621 }
2622 }
2623
2624 // icmp pred (and X, Y), X
2625 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2626 m_And(m_Specific(RHS), m_Value())))) {
2627 if (Pred == ICmpInst::ICMP_UGT)
2628 return getFalse(ITy);
2629 if (Pred == ICmpInst::ICMP_ULE)
2630 return getTrue(ITy);
2631 }
2632 // icmp pred X, (and X, Y)
2633 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2634 m_And(m_Specific(LHS), m_Value())))) {
2635 if (Pred == ICmpInst::ICMP_UGE)
2636 return getTrue(ITy);
2637 if (Pred == ICmpInst::ICMP_ULT)
2638 return getFalse(ITy);
2639 }
2640
2641 // 0 - (zext X) pred C
2642 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2643 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2644 if (RHSC->getValue().isStrictlyPositive()) {
2645 if (Pred == ICmpInst::ICMP_SLT)
2646 return ConstantInt::getTrue(RHSC->getContext());
2647 if (Pred == ICmpInst::ICMP_SGE)
2648 return ConstantInt::getFalse(RHSC->getContext());
2649 if (Pred == ICmpInst::ICMP_EQ)
2650 return ConstantInt::getFalse(RHSC->getContext());
2651 if (Pred == ICmpInst::ICMP_NE)
2652 return ConstantInt::getTrue(RHSC->getContext());
2653 }
2654 if (RHSC->getValue().isNonNegative()) {
2655 if (Pred == ICmpInst::ICMP_SLE)
2656 return ConstantInt::getTrue(RHSC->getContext());
2657 if (Pred == ICmpInst::ICMP_SGT)
2658 return ConstantInt::getFalse(RHSC->getContext());
2659 }
2660 }
2661 }
2662
2663 // icmp pred (urem X, Y), Y
2664 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2665 bool KnownNonNegative, KnownNegative;
2666 switch (Pred) {
2667 default:
2668 break;
2669 case ICmpInst::ICMP_SGT:
2670 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002671 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2672 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002673 if (!KnownNonNegative)
2674 break;
2675 LLVM_FALLTHROUGH;
2676 case ICmpInst::ICMP_EQ:
2677 case ICmpInst::ICMP_UGT:
2678 case ICmpInst::ICMP_UGE:
2679 return getFalse(ITy);
2680 case ICmpInst::ICMP_SLT:
2681 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002682 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2683 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002684 if (!KnownNonNegative)
2685 break;
2686 LLVM_FALLTHROUGH;
2687 case ICmpInst::ICMP_NE:
2688 case ICmpInst::ICMP_ULT:
2689 case ICmpInst::ICMP_ULE:
2690 return getTrue(ITy);
2691 }
2692 }
2693
2694 // icmp pred X, (urem Y, X)
2695 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2696 bool KnownNonNegative, KnownNegative;
2697 switch (Pred) {
2698 default:
2699 break;
2700 case ICmpInst::ICMP_SGT:
2701 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002702 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2703 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002704 if (!KnownNonNegative)
2705 break;
2706 LLVM_FALLTHROUGH;
2707 case ICmpInst::ICMP_NE:
2708 case ICmpInst::ICMP_UGT:
2709 case ICmpInst::ICMP_UGE:
2710 return getTrue(ITy);
2711 case ICmpInst::ICMP_SLT:
2712 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002713 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2714 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002715 if (!KnownNonNegative)
2716 break;
2717 LLVM_FALLTHROUGH;
2718 case ICmpInst::ICMP_EQ:
2719 case ICmpInst::ICMP_ULT:
2720 case ICmpInst::ICMP_ULE:
2721 return getFalse(ITy);
2722 }
2723 }
2724
2725 // x >> y <=u x
2726 // x udiv y <=u x.
2727 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2728 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2729 // icmp pred (X op Y), X
2730 if (Pred == ICmpInst::ICMP_UGT)
2731 return getFalse(ITy);
2732 if (Pred == ICmpInst::ICMP_ULE)
2733 return getTrue(ITy);
2734 }
2735
2736 // x >=u x >> y
2737 // x >=u x udiv y.
2738 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2739 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2740 // icmp pred X, (X op Y)
2741 if (Pred == ICmpInst::ICMP_ULT)
2742 return getFalse(ITy);
2743 if (Pred == ICmpInst::ICMP_UGE)
2744 return getTrue(ITy);
2745 }
2746
2747 // handle:
2748 // CI2 << X == CI
2749 // CI2 << X != CI
2750 //
2751 // where CI2 is a power of 2 and CI isn't
2752 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2753 const APInt *CI2Val, *CIVal = &CI->getValue();
2754 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2755 CI2Val->isPowerOf2()) {
2756 if (!CIVal->isPowerOf2()) {
2757 // CI2 << X can equal zero in some circumstances,
2758 // this simplification is unsafe if CI is zero.
2759 //
2760 // We know it is safe if:
2761 // - The shift is nsw, we can't shift out the one bit.
2762 // - The shift is nuw, we can't shift out the one bit.
2763 // - CI2 is one
2764 // - CI isn't zero
2765 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2766 *CI2Val == 1 || !CI->isZero()) {
2767 if (Pred == ICmpInst::ICMP_EQ)
2768 return ConstantInt::getFalse(RHS->getContext());
2769 if (Pred == ICmpInst::ICMP_NE)
2770 return ConstantInt::getTrue(RHS->getContext());
2771 }
2772 }
2773 if (CIVal->isSignBit() && *CI2Val == 1) {
2774 if (Pred == ICmpInst::ICMP_UGT)
2775 return ConstantInt::getFalse(RHS->getContext());
2776 if (Pred == ICmpInst::ICMP_ULE)
2777 return ConstantInt::getTrue(RHS->getContext());
2778 }
2779 }
2780 }
2781
2782 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2783 LBO->getOperand(1) == RBO->getOperand(1)) {
2784 switch (LBO->getOpcode()) {
2785 default:
2786 break;
2787 case Instruction::UDiv:
2788 case Instruction::LShr:
2789 if (ICmpInst::isSigned(Pred))
2790 break;
2791 LLVM_FALLTHROUGH;
2792 case Instruction::SDiv:
2793 case Instruction::AShr:
2794 if (!LBO->isExact() || !RBO->isExact())
2795 break;
2796 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2797 RBO->getOperand(0), Q, MaxRecurse - 1))
2798 return V;
2799 break;
2800 case Instruction::Shl: {
2801 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2802 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2803 if (!NUW && !NSW)
2804 break;
2805 if (!NSW && ICmpInst::isSigned(Pred))
2806 break;
2807 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2808 RBO->getOperand(0), Q, MaxRecurse - 1))
2809 return V;
2810 break;
2811 }
2812 }
2813 }
2814 return nullptr;
2815}
2816
Sanjay Patel35289c62016-12-10 17:40:47 +00002817/// Simplify integer comparisons where at least one operand of the compare
2818/// matches an integer min/max idiom.
2819static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2820 Value *RHS, const Query &Q,
2821 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002822 Type *ITy = GetCompareTy(LHS); // The return type.
2823 Value *A, *B;
2824 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2825 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2826
2827 // Signed variants on "max(a,b)>=a -> true".
2828 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2829 if (A != RHS)
2830 std::swap(A, B); // smax(A, B) pred A.
2831 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2832 // We analyze this as smax(A, B) pred A.
2833 P = Pred;
2834 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2835 (A == LHS || B == LHS)) {
2836 if (A != LHS)
2837 std::swap(A, B); // A pred smax(A, B).
2838 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2839 // We analyze this as smax(A, B) swapped-pred A.
2840 P = CmpInst::getSwappedPredicate(Pred);
2841 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2842 (A == RHS || B == RHS)) {
2843 if (A != RHS)
2844 std::swap(A, B); // smin(A, B) pred A.
2845 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2846 // We analyze this as smax(-A, -B) swapped-pred -A.
2847 // Note that we do not need to actually form -A or -B thanks to EqP.
2848 P = CmpInst::getSwappedPredicate(Pred);
2849 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2850 (A == LHS || B == LHS)) {
2851 if (A != LHS)
2852 std::swap(A, B); // A pred smin(A, B).
2853 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2854 // We analyze this as smax(-A, -B) pred -A.
2855 // Note that we do not need to actually form -A or -B thanks to EqP.
2856 P = Pred;
2857 }
2858 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2859 // Cases correspond to "max(A, B) p A".
2860 switch (P) {
2861 default:
2862 break;
2863 case CmpInst::ICMP_EQ:
2864 case CmpInst::ICMP_SLE:
2865 // Equivalent to "A EqP B". This may be the same as the condition tested
2866 // in the max/min; if so, we can just return that.
2867 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2868 return V;
2869 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2870 return V;
2871 // Otherwise, see if "A EqP B" simplifies.
2872 if (MaxRecurse)
2873 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2874 return V;
2875 break;
2876 case CmpInst::ICMP_NE:
2877 case CmpInst::ICMP_SGT: {
2878 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2879 // Equivalent to "A InvEqP B". This may be the same as the condition
2880 // tested in the max/min; if so, we can just return that.
2881 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2882 return V;
2883 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2884 return V;
2885 // Otherwise, see if "A InvEqP B" simplifies.
2886 if (MaxRecurse)
2887 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2888 return V;
2889 break;
2890 }
2891 case CmpInst::ICMP_SGE:
2892 // Always true.
2893 return getTrue(ITy);
2894 case CmpInst::ICMP_SLT:
2895 // Always false.
2896 return getFalse(ITy);
2897 }
2898 }
2899
2900 // Unsigned variants on "max(a,b)>=a -> true".
2901 P = CmpInst::BAD_ICMP_PREDICATE;
2902 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2903 if (A != RHS)
2904 std::swap(A, B); // umax(A, B) pred A.
2905 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2906 // We analyze this as umax(A, B) pred A.
2907 P = Pred;
2908 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2909 (A == LHS || B == LHS)) {
2910 if (A != LHS)
2911 std::swap(A, B); // A pred umax(A, B).
2912 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2913 // We analyze this as umax(A, B) swapped-pred A.
2914 P = CmpInst::getSwappedPredicate(Pred);
2915 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2916 (A == RHS || B == RHS)) {
2917 if (A != RHS)
2918 std::swap(A, B); // umin(A, B) pred A.
2919 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2920 // We analyze this as umax(-A, -B) swapped-pred -A.
2921 // Note that we do not need to actually form -A or -B thanks to EqP.
2922 P = CmpInst::getSwappedPredicate(Pred);
2923 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2924 (A == LHS || B == LHS)) {
2925 if (A != LHS)
2926 std::swap(A, B); // A pred umin(A, B).
2927 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2928 // We analyze this as umax(-A, -B) pred -A.
2929 // Note that we do not need to actually form -A or -B thanks to EqP.
2930 P = Pred;
2931 }
2932 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2933 // Cases correspond to "max(A, B) p A".
2934 switch (P) {
2935 default:
2936 break;
2937 case CmpInst::ICMP_EQ:
2938 case CmpInst::ICMP_ULE:
2939 // Equivalent to "A EqP B". This may be the same as the condition tested
2940 // in the max/min; if so, we can just return that.
2941 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2942 return V;
2943 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2944 return V;
2945 // Otherwise, see if "A EqP B" simplifies.
2946 if (MaxRecurse)
2947 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2948 return V;
2949 break;
2950 case CmpInst::ICMP_NE:
2951 case CmpInst::ICMP_UGT: {
2952 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2953 // Equivalent to "A InvEqP B". This may be the same as the condition
2954 // tested in the max/min; if so, we can just return that.
2955 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2956 return V;
2957 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2958 return V;
2959 // Otherwise, see if "A InvEqP B" simplifies.
2960 if (MaxRecurse)
2961 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2962 return V;
2963 break;
2964 }
2965 case CmpInst::ICMP_UGE:
2966 // Always true.
2967 return getTrue(ITy);
2968 case CmpInst::ICMP_ULT:
2969 // Always false.
2970 return getFalse(ITy);
2971 }
2972 }
2973
2974 // Variants on "max(x,y) >= min(x,z)".
2975 Value *C, *D;
2976 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2977 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2978 (A == C || A == D || B == C || B == D)) {
2979 // max(x, ?) pred min(x, ?).
2980 if (Pred == CmpInst::ICMP_SGE)
2981 // Always true.
2982 return getTrue(ITy);
2983 if (Pred == CmpInst::ICMP_SLT)
2984 // Always false.
2985 return getFalse(ITy);
2986 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2987 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2988 (A == C || A == D || B == C || B == D)) {
2989 // min(x, ?) pred max(x, ?).
2990 if (Pred == CmpInst::ICMP_SLE)
2991 // Always true.
2992 return getTrue(ITy);
2993 if (Pred == CmpInst::ICMP_SGT)
2994 // Always false.
2995 return getFalse(ITy);
2996 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2997 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2998 (A == C || A == D || B == C || B == D)) {
2999 // max(x, ?) pred min(x, ?).
3000 if (Pred == CmpInst::ICMP_UGE)
3001 // Always true.
3002 return getTrue(ITy);
3003 if (Pred == CmpInst::ICMP_ULT)
3004 // Always false.
3005 return getFalse(ITy);
3006 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3007 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3008 (A == C || A == D || B == C || B == D)) {
3009 // min(x, ?) pred max(x, ?).
3010 if (Pred == CmpInst::ICMP_ULE)
3011 // Always true.
3012 return getTrue(ITy);
3013 if (Pred == CmpInst::ICMP_UGT)
3014 // Always false.
3015 return getFalse(ITy);
3016 }
3017
3018 return nullptr;
3019}
3020
Sanjay Patel472cc782016-01-11 22:14:42 +00003021/// Given operands for an ICmpInst, see if we can fold the result.
3022/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003023static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003024 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003025 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003026 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003027
Chris Lattnera71e9d62009-11-10 00:55:12 +00003028 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003029 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003030 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003031
3032 // If we have a constant, make sure it is on the RHS.
3033 std::swap(LHS, RHS);
3034 Pred = CmpInst::getSwappedPredicate(Pred);
3035 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003036
Chris Lattner229907c2011-07-18 04:54:35 +00003037 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003038
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003039 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003040 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3041 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003042 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003043 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003044
Sanjay Pateldc65a272016-12-03 17:30:22 +00003045 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3046 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003047
Sanjay Pateldc65a272016-12-03 17:30:22 +00003048 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3049 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003050
Sanjay Patel67bde282016-08-22 23:12:02 +00003051 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3052 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003053
Chen Li7452d952015-09-26 03:26:47 +00003054 // If both operands have range metadata, use the metadata
3055 // to simplify the comparison.
3056 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3057 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3058 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3059
3060 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3061 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003062 auto RHS_CR = getConstantRangeFromMetadata(
3063 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3064 auto LHS_CR = getConstantRangeFromMetadata(
3065 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003066
3067 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3068 if (Satisfied_CR.contains(LHS_CR))
3069 return ConstantInt::getTrue(RHS->getContext());
3070
3071 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3072 CmpInst::getInversePredicate(Pred), RHS_CR);
3073 if (InversedSatisfied_CR.contains(LHS_CR))
3074 return ConstantInt::getFalse(RHS->getContext());
3075 }
3076 }
3077
Duncan Sands8fb2c382011-01-20 13:21:55 +00003078 // Compare of cast, for example (zext X) != 0 -> X != 0
3079 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3080 Instruction *LI = cast<CastInst>(LHS);
3081 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003082 Type *SrcTy = SrcOp->getType();
3083 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003084
3085 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3086 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003087 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3088 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003089 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3090 // Transfer the cast to the constant.
3091 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3092 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003093 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003094 return V;
3095 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3096 if (RI->getOperand(0)->getType() == SrcTy)
3097 // Compare without the cast.
3098 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003099 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003100 return V;
3101 }
3102 }
3103
3104 if (isa<ZExtInst>(LHS)) {
3105 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3106 // same type.
3107 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3108 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3109 // Compare X and Y. Note that signed predicates become unsigned.
3110 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003111 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003112 MaxRecurse-1))
3113 return V;
3114 }
3115 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3116 // too. If not, then try to deduce the result of the comparison.
3117 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3118 // Compute the constant that would happen if we truncated to SrcTy then
3119 // reextended to DstTy.
3120 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3121 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3122
3123 // If the re-extended constant didn't change then this is effectively
3124 // also a case of comparing two zero-extended values.
3125 if (RExt == CI && MaxRecurse)
3126 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003127 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003128 return V;
3129
3130 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3131 // there. Use this to work out the result of the comparison.
3132 if (RExt != CI) {
3133 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003134 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003135 // LHS <u RHS.
3136 case ICmpInst::ICMP_EQ:
3137 case ICmpInst::ICMP_UGT:
3138 case ICmpInst::ICMP_UGE:
3139 return ConstantInt::getFalse(CI->getContext());
3140
3141 case ICmpInst::ICMP_NE:
3142 case ICmpInst::ICMP_ULT:
3143 case ICmpInst::ICMP_ULE:
3144 return ConstantInt::getTrue(CI->getContext());
3145
3146 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3147 // is non-negative then LHS <s RHS.
3148 case ICmpInst::ICMP_SGT:
3149 case ICmpInst::ICMP_SGE:
3150 return CI->getValue().isNegative() ?
3151 ConstantInt::getTrue(CI->getContext()) :
3152 ConstantInt::getFalse(CI->getContext());
3153
3154 case ICmpInst::ICMP_SLT:
3155 case ICmpInst::ICMP_SLE:
3156 return CI->getValue().isNegative() ?
3157 ConstantInt::getFalse(CI->getContext()) :
3158 ConstantInt::getTrue(CI->getContext());
3159 }
3160 }
3161 }
3162 }
3163
3164 if (isa<SExtInst>(LHS)) {
3165 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3166 // same type.
3167 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3168 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3169 // Compare X and Y. Note that the predicate does not change.
3170 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003171 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003172 return V;
3173 }
3174 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3175 // too. If not, then try to deduce the result of the comparison.
3176 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3177 // Compute the constant that would happen if we truncated to SrcTy then
3178 // reextended to DstTy.
3179 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3180 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3181
3182 // If the re-extended constant didn't change then this is effectively
3183 // also a case of comparing two sign-extended values.
3184 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003185 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003186 return V;
3187
3188 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3189 // bits there. Use this to work out the result of the comparison.
3190 if (RExt != CI) {
3191 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003192 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003193 case ICmpInst::ICMP_EQ:
3194 return ConstantInt::getFalse(CI->getContext());
3195 case ICmpInst::ICMP_NE:
3196 return ConstantInt::getTrue(CI->getContext());
3197
3198 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3199 // LHS >s RHS.
3200 case ICmpInst::ICMP_SGT:
3201 case ICmpInst::ICMP_SGE:
3202 return CI->getValue().isNegative() ?
3203 ConstantInt::getTrue(CI->getContext()) :
3204 ConstantInt::getFalse(CI->getContext());
3205 case ICmpInst::ICMP_SLT:
3206 case ICmpInst::ICMP_SLE:
3207 return CI->getValue().isNegative() ?
3208 ConstantInt::getFalse(CI->getContext()) :
3209 ConstantInt::getTrue(CI->getContext());
3210
3211 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3212 // LHS >u RHS.
3213 case ICmpInst::ICMP_UGT:
3214 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003215 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003216 if (MaxRecurse)
3217 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3218 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003219 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003220 return V;
3221 break;
3222 case ICmpInst::ICMP_ULT:
3223 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003224 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003225 if (MaxRecurse)
3226 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3227 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003228 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003229 return V;
3230 break;
3231 }
3232 }
3233 }
3234 }
3235 }
3236
James Molloy1d88d6f2015-10-22 13:18:42 +00003237 // icmp eq|ne X, Y -> false|true if X != Y
3238 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003239 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003240 LLVMContext &Ctx = LHS->getType()->getContext();
3241 return Pred == ICmpInst::ICMP_NE ?
3242 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3243 }
Junmo Park53470fc2016-04-05 21:14:31 +00003244
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003245 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3246 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003247
Sanjay Patel35289c62016-12-10 17:40:47 +00003248 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003249 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003250
Chandler Carruth8059c842012-03-25 21:28:14 +00003251 // Simplify comparisons of related pointers using a powerful, recursive
3252 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003253 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003254 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003255 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003256 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3257 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3258 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3259 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3260 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3261 Q.DL.getTypeSizeInBits(CRHS->getType()))
3262 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3263 CLHS->getPointerOperand(),
3264 CRHS->getPointerOperand()))
3265 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003266
Nick Lewycky3db143e2012-02-26 02:09:49 +00003267 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3268 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3269 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3270 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3271 (ICmpInst::isEquality(Pred) ||
3272 (GLHS->isInBounds() && GRHS->isInBounds() &&
3273 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3274 // The bases are equal and the indices are constant. Build a constant
3275 // expression GEP with the same indices and a null base pointer to see
3276 // what constant folding can make out of it.
3277 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3278 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003279 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3280 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003281
3282 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003283 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3284 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003285 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3286 }
3287 }
3288 }
3289
David Majnemer5854e9f2014-11-16 02:20:08 +00003290 // If a bit is known to be zero for A and known to be one for B,
3291 // then A and B cannot be equal.
3292 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003293 const APInt *RHSVal;
3294 if (match(RHS, m_APInt(RHSVal))) {
3295 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003296 APInt LHSKnownZero(BitWidth, 0);
3297 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003298 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003299 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003300 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3301 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3302 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003303 }
3304 }
3305
Duncan Sandsf532d312010-11-07 16:12:23 +00003306 // If the comparison is with the result of a select instruction, check whether
3307 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003308 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003309 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003310 return V;
3311
3312 // If the comparison is with the result of a phi instruction, check whether
3313 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003314 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003315 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003316 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003317
Craig Topper9f008862014-04-15 04:59:12 +00003318 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003319}
3320
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003321Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003322 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003323 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003324 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003325 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003326 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003327 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003328}
3329
Sanjay Patel472cc782016-01-11 22:14:42 +00003330/// Given operands for an FCmpInst, see if we can fold the result.
3331/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003332static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003333 FastMathFlags FMF, const Query &Q,
3334 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003335 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3336 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3337
Chris Lattnera71e9d62009-11-10 00:55:12 +00003338 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003339 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003340 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003341
Chris Lattnera71e9d62009-11-10 00:55:12 +00003342 // If we have a constant, make sure it is on the RHS.
3343 std::swap(LHS, RHS);
3344 Pred = CmpInst::getSwappedPredicate(Pred);
3345 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003346
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003347 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003348 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003349 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003350 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003351 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003352 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003353
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003354 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3355 if (FMF.noNaNs()) {
3356 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003357 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003358 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003359 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003360 }
3361
Mehdi Aminieb242a52015-03-09 03:20:25 +00003362 // fcmp pred x, undef and fcmp pred undef, x
3363 // fold to true if unordered, false if ordered
3364 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3365 // Choosing NaN for the undef will always make unordered comparison succeed
3366 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003367 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003368 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003369
3370 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003371 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003372 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003373 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003374 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003375 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003376 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003377
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003378 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003379 const ConstantFP *CFP = nullptr;
3380 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3381 if (RHS->getType()->isVectorTy())
3382 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3383 else
3384 CFP = dyn_cast<ConstantFP>(RHSC);
3385 }
3386 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003387 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003388 if (CFP->getValueAPF().isNaN()) {
3389 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003390 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003391 assert(FCmpInst::isUnordered(Pred) &&
3392 "Comparison must be either ordered or unordered!");
3393 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003394 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003395 }
3396 // Check whether the constant is an infinity.
3397 if (CFP->getValueAPF().isInfinity()) {
3398 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003399 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003400 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003401 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003402 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003403 case FCmpInst::FCMP_UGE:
3404 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003405 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003406 default:
3407 break;
3408 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003409 } else {
3410 switch (Pred) {
3411 case FCmpInst::FCMP_OGT:
3412 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003413 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003414 case FCmpInst::FCMP_ULE:
3415 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003416 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003417 default:
3418 break;
3419 }
3420 }
3421 }
3422 if (CFP->getValueAPF().isZero()) {
3423 switch (Pred) {
3424 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003425 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003426 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003427 break;
3428 case FCmpInst::FCMP_OLT:
3429 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003430 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003431 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003432 break;
3433 default:
3434 break;
3435 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003436 }
3437 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003438
Duncan Sandsa620bd12010-11-07 16:46:25 +00003439 // If the comparison is with the result of a select instruction, check whether
3440 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003441 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003442 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003443 return V;
3444
3445 // If the comparison is with the result of a phi instruction, check whether
3446 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003447 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003448 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003449 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003450
Craig Topper9f008862014-04-15 04:59:12 +00003451 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003452}
3453
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003454Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003455 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003456 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003457 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003458 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003459 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003460 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003461}
3462
Sanjay Patel472cc782016-01-11 22:14:42 +00003463/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003464static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3465 const Query &Q,
3466 unsigned MaxRecurse) {
3467 // Trivial replacement.
3468 if (V == Op)
3469 return RepOp;
3470
3471 auto *I = dyn_cast<Instruction>(V);
3472 if (!I)
3473 return nullptr;
3474
3475 // If this is a binary operator, try to simplify it with the replaced op.
3476 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3477 // Consider:
3478 // %cmp = icmp eq i32 %x, 2147483647
3479 // %add = add nsw i32 %x, 1
3480 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3481 //
3482 // We can't replace %sel with %add unless we strip away the flags.
3483 if (isa<OverflowingBinaryOperator>(B))
3484 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3485 return nullptr;
3486 if (isa<PossiblyExactOperator>(B))
3487 if (B->isExact())
3488 return nullptr;
3489
3490 if (MaxRecurse) {
3491 if (B->getOperand(0) == Op)
3492 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3493 MaxRecurse - 1);
3494 if (B->getOperand(1) == Op)
3495 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3496 MaxRecurse - 1);
3497 }
3498 }
3499
3500 // Same for CmpInsts.
3501 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3502 if (MaxRecurse) {
3503 if (C->getOperand(0) == Op)
3504 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3505 MaxRecurse - 1);
3506 if (C->getOperand(1) == Op)
3507 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3508 MaxRecurse - 1);
3509 }
3510 }
3511
3512 // TODO: We could hand off more cases to instsimplify here.
3513
3514 // If all operands are constant after substituting Op for RepOp then we can
3515 // constant fold the instruction.
3516 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3517 // Build a list of all constant operands.
3518 SmallVector<Constant *, 8> ConstOps;
3519 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3520 if (I->getOperand(i) == Op)
3521 ConstOps.push_back(CRepOp);
3522 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3523 ConstOps.push_back(COp);
3524 else
3525 break;
3526 }
3527
3528 // All operands were constants, fold it.
3529 if (ConstOps.size() == I->getNumOperands()) {
3530 if (CmpInst *C = dyn_cast<CmpInst>(I))
3531 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3532 ConstOps[1], Q.DL, Q.TLI);
3533
3534 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3535 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003536 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003537
Manuel Jacobe9024592016-01-21 06:33:22 +00003538 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003539 }
3540 }
3541
3542 return nullptr;
3543}
3544
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003545/// Try to simplify a select instruction when its condition operand is an
3546/// integer comparison where one operand of the compare is a constant.
3547static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3548 const APInt *Y, bool TrueWhenUnset) {
3549 const APInt *C;
3550
3551 // (X & Y) == 0 ? X & ~Y : X --> X
3552 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3553 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3554 *Y == ~*C)
3555 return TrueWhenUnset ? FalseVal : TrueVal;
3556
3557 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3558 // (X & Y) != 0 ? X : X & ~Y --> X
3559 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3560 *Y == ~*C)
3561 return TrueWhenUnset ? FalseVal : TrueVal;
3562
3563 if (Y->isPowerOf2()) {
3564 // (X & Y) == 0 ? X | Y : X --> X | Y
3565 // (X & Y) != 0 ? X | Y : X --> X
3566 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3567 *Y == *C)
3568 return TrueWhenUnset ? TrueVal : FalseVal;
3569
3570 // (X & Y) == 0 ? X : X | Y --> X
3571 // (X & Y) != 0 ? X : X | Y --> X | Y
3572 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3573 *Y == *C)
3574 return TrueWhenUnset ? TrueVal : FalseVal;
3575 }
3576
3577 return nullptr;
3578}
3579
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003580/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3581/// eq/ne.
3582static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3583 Value *FalseVal,
3584 bool TrueWhenUnset) {
3585 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003586 if (!BitWidth)
3587 return nullptr;
3588
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003589 APInt MinSignedValue;
3590 Value *X;
3591 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3592 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3593 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3594 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3595 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3596 } else {
3597 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3598 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3599 X = CmpLHS;
3600 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3601 }
3602
3603 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3604 TrueWhenUnset))
3605 return V;
3606
3607 return nullptr;
3608}
3609
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003610/// Try to simplify a select instruction when its condition operand is an
3611/// integer comparison.
3612static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3613 Value *FalseVal, const Query &Q,
3614 unsigned MaxRecurse) {
3615 ICmpInst::Predicate Pred;
3616 Value *CmpLHS, *CmpRHS;
3617 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3618 return nullptr;
3619
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003620 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3621 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003622 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3623 Value *X;
3624 const APInt *Y;
3625 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3626 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3627 Pred == ICmpInst::ICMP_EQ))
3628 return V;
3629 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003630 // Comparing signed-less-than 0 checks if the sign bit is set.
3631 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3632 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003633 return V;
3634 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003635 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3636 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3637 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003638 return V;
3639 }
3640
3641 if (CondVal->hasOneUse()) {
3642 const APInt *C;
3643 if (match(CmpRHS, m_APInt(C))) {
3644 // X < MIN ? T : F --> F
3645 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3646 return FalseVal;
3647 // X < MIN ? T : F --> F
3648 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3649 return FalseVal;
3650 // X > MAX ? T : F --> F
3651 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3652 return FalseVal;
3653 // X > MAX ? T : F --> F
3654 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3655 return FalseVal;
3656 }
3657 }
3658
3659 // If we have an equality comparison, then we know the value in one of the
3660 // arms of the select. See if substituting this value into the arm and
3661 // simplifying the result yields the same value as the other arm.
3662 if (Pred == ICmpInst::ICMP_EQ) {
3663 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3664 TrueVal ||
3665 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3666 TrueVal)
3667 return FalseVal;
3668 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3669 FalseVal ||
3670 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3671 FalseVal)
3672 return FalseVal;
3673 } else if (Pred == ICmpInst::ICMP_NE) {
3674 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3675 FalseVal ||
3676 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3677 FalseVal)
3678 return TrueVal;
3679 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3680 TrueVal ||
3681 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3682 TrueVal)
3683 return TrueVal;
3684 }
3685
3686 return nullptr;
3687}
3688
Sanjay Patel472cc782016-01-11 22:14:42 +00003689/// Given operands for a SelectInst, see if we can fold the result.
3690/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003691static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3692 Value *FalseVal, const Query &Q,
3693 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003694 // select true, X, Y -> X
3695 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003696 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3697 if (CB->isAllOnesValue())
3698 return TrueVal;
3699 if (CB->isNullValue())
3700 return FalseVal;
3701 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003702
Chris Lattnerc707fa92010-04-20 05:32:14 +00003703 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003704 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003705 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003706
Chris Lattnerc707fa92010-04-20 05:32:14 +00003707 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3708 if (isa<Constant>(TrueVal))
3709 return TrueVal;
3710 return FalseVal;
3711 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003712 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3713 return FalseVal;
3714 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3715 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003716
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003717 if (Value *V =
3718 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3719 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003720
Craig Topper9f008862014-04-15 04:59:12 +00003721 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003722}
3723
Duncan Sandsb8cee002012-03-13 11:42:19 +00003724Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003725 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003726 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003727 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003728 const Instruction *CxtI) {
3729 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003730 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003731}
3732
Sanjay Patel472cc782016-01-11 22:14:42 +00003733/// Given operands for an GetElementPtrInst, see if we can fold the result.
3734/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003735static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3736 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003737 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003738 unsigned AS =
3739 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003740
Chris Lattner8574aba2009-11-27 00:29:05 +00003741 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003742 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003743 return Ops[0];
3744
Nico Weber48c82402014-08-27 20:06:19 +00003745 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003746 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003747 Type *GEPTy = PointerType::get(LastType, AS);
3748 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3749 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3750
3751 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003752 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003753
Jay Foadb992a632011-07-19 15:07:52 +00003754 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003755 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003756 if (match(Ops[1], m_Zero()))
3757 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003758
David Blaikie4a2e73b2015-04-02 18:55:32 +00003759 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003760 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003761 Value *P;
3762 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003763 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003764 // getelementptr P, N -> P if P points to a type of zero size.
3765 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003766 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003767
3768 // The following transforms are only safe if the ptrtoint cast
3769 // doesn't truncate the pointers.
3770 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003771 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003772 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3773 if (match(P, m_Zero()))
3774 return Constant::getNullValue(GEPTy);
3775 Value *Temp;
3776 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003777 if (Temp->getType() == GEPTy)
3778 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003779 return nullptr;
3780 };
3781
3782 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3783 if (TyAllocSize == 1 &&
3784 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3785 if (Value *R = PtrToIntOrZero(P))
3786 return R;
3787
3788 // getelementptr V, (ashr (sub P, V), C) -> Q
3789 // if P points to a type of size 1 << C.
3790 if (match(Ops[1],
3791 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3792 m_ConstantInt(C))) &&
3793 TyAllocSize == 1ULL << C)
3794 if (Value *R = PtrToIntOrZero(P))
3795 return R;
3796
3797 // getelementptr V, (sdiv (sub P, V), C) -> Q
3798 // if P points to a type of size C.
3799 if (match(Ops[1],
3800 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3801 m_SpecificInt(TyAllocSize))))
3802 if (Value *R = PtrToIntOrZero(P))
3803 return R;
3804 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003805 }
3806 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003807
David Majnemerd1501372016-08-07 07:58:12 +00003808 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3809 all_of(Ops.slice(1).drop_back(1),
3810 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3811 unsigned PtrWidth =
3812 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3813 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3814 APInt BasePtrOffset(PtrWidth, 0);
3815 Value *StrippedBasePtr =
3816 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3817 BasePtrOffset);
3818
David Majnemer5c5df622016-08-16 06:13:46 +00003819 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003820 if (match(Ops.back(),
3821 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3822 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3823 return ConstantExpr::getIntToPtr(CI, GEPTy);
3824 }
David Majnemer5c5df622016-08-16 06:13:46 +00003825 // gep (gep V, C), (xor V, -1) -> C-1
3826 if (match(Ops.back(),
3827 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3828 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3829 return ConstantExpr::getIntToPtr(CI, GEPTy);
3830 }
David Majnemerd1501372016-08-07 07:58:12 +00003831 }
3832 }
3833
Chris Lattner8574aba2009-11-27 00:29:05 +00003834 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003835 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003836 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003837 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003838
David Blaikie4a2e73b2015-04-02 18:55:32 +00003839 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3840 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003841}
3842
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003843Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3844 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003845 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003846 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003847 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003848 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003849 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003850}
3851
Sanjay Patel472cc782016-01-11 22:14:42 +00003852/// Given operands for an InsertValueInst, see if we can fold the result.
3853/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003854static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3855 ArrayRef<unsigned> Idxs, const Query &Q,
3856 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003857 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3858 if (Constant *CVal = dyn_cast<Constant>(Val))
3859 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3860
3861 // insertvalue x, undef, n -> x
3862 if (match(Val, m_Undef()))
3863 return Agg;
3864
3865 // insertvalue x, (extractvalue y, n), n
3866 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003867 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3868 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003869 // insertvalue undef, (extractvalue y, n), n -> y
3870 if (match(Agg, m_Undef()))
3871 return EV->getAggregateOperand();
3872
3873 // insertvalue y, (extractvalue y, n), n -> y
3874 if (Agg == EV->getAggregateOperand())
3875 return Agg;
3876 }
3877
Craig Topper9f008862014-04-15 04:59:12 +00003878 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003879}
3880
Chandler Carruth66b31302015-01-04 12:03:27 +00003881Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003882 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003883 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003884 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003885 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003886 RecursionLimit);
3887}
3888
Sanjay Patel472cc782016-01-11 22:14:42 +00003889/// Given operands for an ExtractValueInst, see if we can fold the result.
3890/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003891static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3892 const Query &, unsigned) {
3893 if (auto *CAgg = dyn_cast<Constant>(Agg))
3894 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3895
3896 // extractvalue x, (insertvalue y, elt, n), n -> elt
3897 unsigned NumIdxs = Idxs.size();
3898 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3899 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3900 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3901 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3902 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3903 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3904 Idxs.slice(0, NumCommonIdxs)) {
3905 if (NumIdxs == NumInsertValueIdxs)
3906 return IVI->getInsertedValueOperand();
3907 break;
3908 }
3909 }
3910
3911 return nullptr;
3912}
3913
3914Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3915 const DataLayout &DL,
3916 const TargetLibraryInfo *TLI,
3917 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003918 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003919 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003920 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003921 RecursionLimit);
3922}
3923
Sanjay Patel472cc782016-01-11 22:14:42 +00003924/// Given operands for an ExtractElementInst, see if we can fold the result.
3925/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003926static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3927 unsigned) {
3928 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3929 if (auto *CIdx = dyn_cast<Constant>(Idx))
3930 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3931
3932 // The index is not relevant if our vector is a splat.
3933 if (auto *Splat = CVec->getSplatValue())
3934 return Splat;
3935
3936 if (isa<UndefValue>(Vec))
3937 return UndefValue::get(Vec->getType()->getVectorElementType());
3938 }
3939
3940 // If extracting a specified index from the vector, see if we can recursively
3941 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003942 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3943 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003944 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003945
3946 return nullptr;
3947}
3948
3949Value *llvm::SimplifyExtractElementInst(
3950 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003951 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3952 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00003953 RecursionLimit);
3954}
3955
Sanjay Patel472cc782016-01-11 22:14:42 +00003956/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003957static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003958 // If all of the PHI's incoming values are the same then replace the PHI node
3959 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003960 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003961 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003962 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003963 // If the incoming value is the phi node itself, it can safely be skipped.
3964 if (Incoming == PN) continue;
3965 if (isa<UndefValue>(Incoming)) {
3966 // Remember that we saw an undef value, but otherwise ignore them.
3967 HasUndefInput = true;
3968 continue;
3969 }
3970 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003971 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003972 CommonValue = Incoming;
3973 }
3974
3975 // If CommonValue is null then all of the incoming values were either undef or
3976 // equal to the phi node itself.
3977 if (!CommonValue)
3978 return UndefValue::get(PN->getType());
3979
3980 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3981 // instruction, we cannot return X as the result of the PHI node unless it
3982 // dominates the PHI block.
3983 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003984 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003985
3986 return CommonValue;
3987}
3988
David Majnemer6774d612016-07-26 17:58:05 +00003989static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
3990 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00003991 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00003992 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003993
David Majnemer6774d612016-07-26 17:58:05 +00003994 if (auto *CI = dyn_cast<CastInst>(Op)) {
3995 auto *Src = CI->getOperand(0);
3996 Type *SrcTy = Src->getType();
3997 Type *MidTy = CI->getType();
3998 Type *DstTy = Ty;
3999 if (Src->getType() == Ty) {
4000 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4001 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4002 Type *SrcIntPtrTy =
4003 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4004 Type *MidIntPtrTy =
4005 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4006 Type *DstIntPtrTy =
4007 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4008 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4009 SrcIntPtrTy, MidIntPtrTy,
4010 DstIntPtrTy) == Instruction::BitCast)
4011 return Src;
4012 }
4013 }
David Majnemera90a6212016-07-26 05:52:29 +00004014
4015 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004016 if (CastOpc == Instruction::BitCast)
4017 if (Op->getType() == Ty)
4018 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004019
4020 return nullptr;
4021}
4022
David Majnemer6774d612016-07-26 17:58:05 +00004023Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4024 const DataLayout &DL,
4025 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004026 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004027 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004028 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004029 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004030}
4031
Chris Lattnera71e9d62009-11-10 00:55:12 +00004032//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004033
Sanjay Patel472cc782016-01-11 22:14:42 +00004034/// Given operands for a BinaryOperator, see if we can fold the result.
4035/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004036static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004037 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004038 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004039 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004040 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004041 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004042 case Instruction::FAdd:
4043 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4044
Chris Lattner9e4aa022011-02-09 17:15:04 +00004045 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004046 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004047 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004048 case Instruction::FSub:
4049 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4050
Duncan Sandsb8cee002012-03-13 11:42:19 +00004051 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004052 case Instruction::FMul:
4053 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004054 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4055 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004056 case Instruction::FDiv:
4057 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004058 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4059 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004060 case Instruction::FRem:
4061 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004062 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004063 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004064 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004065 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004066 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004067 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004068 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
4069 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4070 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
4071 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004072 default:
4073 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004074 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4075 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004076
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004077 // If the operation is associative, try some generic simplifications.
4078 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004079 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004080 return V;
4081
Duncan Sandsb8cee002012-03-13 11:42:19 +00004082 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004083 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004084 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004085 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004086 return V;
4087
4088 // If the operation is with the result of a phi instruction, check whether
4089 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004090 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004091 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004092 return V;
4093
Craig Topper9f008862014-04-15 04:59:12 +00004094 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004095 }
4096}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004097
Sanjay Patel472cc782016-01-11 22:14:42 +00004098/// Given operands for a BinaryOperator, see if we can fold the result.
4099/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004100/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4101/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4102static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4103 const FastMathFlags &FMF, const Query &Q,
4104 unsigned MaxRecurse) {
4105 switch (Opcode) {
4106 case Instruction::FAdd:
4107 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4108 case Instruction::FSub:
4109 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4110 case Instruction::FMul:
4111 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004112 case Instruction::FDiv:
4113 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004114 default:
4115 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4116 }
4117}
4118
Duncan Sands7e800d62010-11-14 11:23:23 +00004119Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004120 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004121 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004122 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004123 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004124 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004125}
4126
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004127Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004128 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004129 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004130 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004131 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004132 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004133 RecursionLimit);
4134}
4135
Sanjay Patel472cc782016-01-11 22:14:42 +00004136/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004137static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004138 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004139 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004140 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004141 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004142}
4143
4144Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004145 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004146 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004147 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004148 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004149 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004150}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004151
Michael Ilseman54857292013-02-07 19:26:05 +00004152static bool IsIdempotent(Intrinsic::ID ID) {
4153 switch (ID) {
4154 default: return false;
4155
4156 // Unary idempotent: f(f(x)) = f(x)
4157 case Intrinsic::fabs:
4158 case Intrinsic::floor:
4159 case Intrinsic::ceil:
4160 case Intrinsic::trunc:
4161 case Intrinsic::rint:
4162 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004163 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004164 return true;
4165 }
4166}
4167
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004168static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4169 const DataLayout &DL) {
4170 GlobalValue *PtrSym;
4171 APInt PtrOffset;
4172 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4173 return nullptr;
4174
4175 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4176 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4177 Type *Int32PtrTy = Int32Ty->getPointerTo();
4178 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4179
4180 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4181 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4182 return nullptr;
4183
4184 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4185 if (OffsetInt % 4 != 0)
4186 return nullptr;
4187
4188 Constant *C = ConstantExpr::getGetElementPtr(
4189 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4190 ConstantInt::get(Int64Ty, OffsetInt / 4));
4191 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4192 if (!Loaded)
4193 return nullptr;
4194
4195 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4196 if (!LoadedCE)
4197 return nullptr;
4198
4199 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4200 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4201 if (!LoadedCE)
4202 return nullptr;
4203 }
4204
4205 if (LoadedCE->getOpcode() != Instruction::Sub)
4206 return nullptr;
4207
4208 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4209 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4210 return nullptr;
4211 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4212
4213 Constant *LoadedRHS = LoadedCE->getOperand(1);
4214 GlobalValue *LoadedRHSSym;
4215 APInt LoadedRHSOffset;
4216 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4217 DL) ||
4218 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4219 return nullptr;
4220
4221 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4222}
4223
David Majnemer17a95aa2016-07-14 06:58:37 +00004224static bool maskIsAllZeroOrUndef(Value *Mask) {
4225 auto *ConstMask = dyn_cast<Constant>(Mask);
4226 if (!ConstMask)
4227 return false;
4228 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4229 return true;
4230 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4231 ++I) {
4232 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4233 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4234 continue;
4235 return false;
4236 }
4237 return true;
4238}
4239
Michael Ilseman54857292013-02-07 19:26:05 +00004240template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004241static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004242 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004243 Intrinsic::ID IID = F->getIntrinsicID();
4244 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4245 Type *ReturnType = F->getReturnType();
4246
4247 // Binary Ops
4248 if (NumOperands == 2) {
4249 Value *LHS = *ArgBegin;
4250 Value *RHS = *(ArgBegin + 1);
4251 if (IID == Intrinsic::usub_with_overflow ||
4252 IID == Intrinsic::ssub_with_overflow) {
4253 // X - X -> { 0, false }
4254 if (LHS == RHS)
4255 return Constant::getNullValue(ReturnType);
4256
4257 // X - undef -> undef
4258 // undef - X -> undef
4259 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4260 return UndefValue::get(ReturnType);
4261 }
4262
4263 if (IID == Intrinsic::uadd_with_overflow ||
4264 IID == Intrinsic::sadd_with_overflow) {
4265 // X + undef -> undef
4266 if (isa<UndefValue>(RHS))
4267 return UndefValue::get(ReturnType);
4268 }
4269
4270 if (IID == Intrinsic::umul_with_overflow ||
4271 IID == Intrinsic::smul_with_overflow) {
4272 // X * 0 -> { 0, false }
4273 if (match(RHS, m_Zero()))
4274 return Constant::getNullValue(ReturnType);
4275
4276 // X * undef -> { 0, false }
4277 if (match(RHS, m_Undef()))
4278 return Constant::getNullValue(ReturnType);
4279 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004280
4281 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4282 isa<Constant>(RHS))
4283 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4284 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00004285 }
4286
David Majnemerd77a3b62016-07-13 23:32:53 +00004287 // Simplify calls to llvm.masked.load.*
4288 if (IID == Intrinsic::masked_load) {
David Majnemer17a95aa2016-07-14 06:58:37 +00004289 Value *MaskArg = ArgBegin[2];
4290 Value *PassthruArg = ArgBegin[3];
4291 // If the mask is all zeros or undef, the "passthru" argument is the result.
4292 if (maskIsAllZeroOrUndef(MaskArg))
4293 return PassthruArg;
David Majnemerd77a3b62016-07-13 23:32:53 +00004294 }
4295
Michael Ilseman54857292013-02-07 19:26:05 +00004296 // Perform idempotent optimizations
4297 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00004298 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004299
4300 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00004301 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00004302 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4303 if (II->getIntrinsicID() == IID)
4304 return II;
4305
Craig Topper9f008862014-04-15 04:59:12 +00004306 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004307}
4308
Chandler Carruth9dc35582012-12-28 11:30:55 +00004309template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004310static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004311 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004312 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004313 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4314 Ty = PTy->getElementType();
4315 FunctionType *FTy = cast<FunctionType>(Ty);
4316
Dan Gohman85977e62011-11-04 18:32:42 +00004317 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004318 // call null -> undef
4319 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004320 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004321
Chandler Carruthf6182152012-12-28 14:23:29 +00004322 Function *F = dyn_cast<Function>(V);
4323 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004324 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004325
David Majnemer15032582015-05-22 03:56:46 +00004326 if (F->isIntrinsic())
4327 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004328 return Ret;
4329
Chandler Carruthf6182152012-12-28 14:23:29 +00004330 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004331 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004332
4333 SmallVector<Constant *, 4> ConstantArgs;
4334 ConstantArgs.reserve(ArgEnd - ArgBegin);
4335 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4336 Constant *C = dyn_cast<Constant>(*I);
4337 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004338 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004339 ConstantArgs.push_back(C);
4340 }
4341
4342 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004343}
4344
Chandler Carruthf6182152012-12-28 14:23:29 +00004345Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004346 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004347 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004348 AssumptionCache *AC, const Instruction *CxtI) {
4349 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004350 RecursionLimit);
4351}
4352
Chandler Carruthf6182152012-12-28 14:23:29 +00004353Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004354 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004355 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004356 const Instruction *CxtI) {
4357 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004358 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004359}
4360
Sanjay Patel472cc782016-01-11 22:14:42 +00004361/// See if we can compute a simplified version of this instruction.
4362/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004363Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004364 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004365 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004366 Value *Result;
4367
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004368 switch (I->getOpcode()) {
4369 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004370 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004371 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004372 case Instruction::FAdd:
4373 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004374 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004375 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004376 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004377 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4378 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004379 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004380 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004381 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004382 case Instruction::FSub:
4383 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004384 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004385 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004386 case Instruction::Sub:
4387 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4388 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004389 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004390 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004391 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004392 case Instruction::FMul:
4393 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004394 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004395 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004396 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004397 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004398 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004399 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004400 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004401 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004402 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004403 break;
4404 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004405 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004406 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004407 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004408 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004409 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004410 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004411 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004412 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004413 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004414 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004415 break;
4416 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004417 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004418 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004419 break;
4420 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004421 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004422 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004423 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004424 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004425 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4426 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004427 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004428 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004429 break;
4430 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004431 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004432 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004433 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004434 break;
4435 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004436 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004437 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004438 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004439 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004440 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004441 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004442 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004443 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004444 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004445 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004446 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004447 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004448 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004449 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004450 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004451 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004452 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004453 Result =
4454 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004455 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004456 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004457 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004458 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4459 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004460 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004461 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004462 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004463 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004464 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004465 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004466 case Instruction::GetElementPtr: {
4467 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004468 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004469 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004470 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004471 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004472 case Instruction::InsertValue: {
4473 InsertValueInst *IV = cast<InsertValueInst>(I);
4474 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4475 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004476 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004477 break;
4478 }
David Majnemer25a796e2015-07-13 01:15:46 +00004479 case Instruction::ExtractValue: {
4480 auto *EVI = cast<ExtractValueInst>(I);
4481 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004482 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004483 break;
4484 }
David Majnemer599ca442015-07-13 01:15:53 +00004485 case Instruction::ExtractElement: {
4486 auto *EEI = cast<ExtractElementInst>(I);
4487 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004488 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004489 break;
4490 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004491 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004492 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004493 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004494 case Instruction::Call: {
4495 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004496 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004497 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004498 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004499 }
David Majnemer6774d612016-07-26 17:58:05 +00004500#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4501#include "llvm/IR/Instruction.def"
4502#undef HANDLE_CAST_INST
4503 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004504 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004505 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004506 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004507
Hal Finkelf2199b22015-10-23 20:37:08 +00004508 // In general, it is possible for computeKnownBits to determine all bits in a
4509 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004510 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004511 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4512 APInt KnownZero(BitWidth, 0);
4513 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004514 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
Hal Finkelf2199b22015-10-23 20:37:08 +00004515 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004516 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004517 }
4518
Duncan Sands64e41cf2010-11-17 08:35:29 +00004519 /// If called on unreachable code, the above logic may report that the
4520 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004521 /// detecting that case here, returning a safe value instead.
4522 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004523}
4524
Sanjay Patelf44bd382016-01-20 18:59:48 +00004525/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004526/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004527///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004528/// This is the common implementation of the recursive simplification routines.
4529/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4530/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4531/// instructions to process and attempt to simplify it using
4532/// InstructionSimplify.
4533///
4534/// This routine returns 'true' only when *it* simplifies something. The passed
4535/// in simplified value does not count toward this.
4536static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004537 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004538 const DominatorTree *DT,
4539 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004540 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004541 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004542 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004543
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004544 // If we have an explicit value to collapse to, do that round of the
4545 // simplification loop by hand initially.
4546 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004547 for (User *U : I->users())
4548 if (U != I)
4549 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004550
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004551 // Replace the instruction with its simplified value.
4552 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004553
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004554 // Gracefully handle edge cases where the instruction is not wired into any
4555 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004556 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4557 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004558 I->eraseFromParent();
4559 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004560 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004561 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004562
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004563 // Note that we must test the size on each iteration, the worklist can grow.
4564 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4565 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004566
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004567 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004568 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004569 if (!SimpleV)
4570 continue;
4571
4572 Simplified = true;
4573
4574 // Stash away all the uses of the old instruction so we can check them for
4575 // recursive simplifications after a RAUW. This is cheaper than checking all
4576 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004577 for (User *U : I->users())
4578 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004579
4580 // Replace the instruction with its simplified value.
4581 I->replaceAllUsesWith(SimpleV);
4582
4583 // Gracefully handle edge cases where the instruction is not wired into any
4584 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004585 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4586 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004587 I->eraseFromParent();
4588 }
4589 return Simplified;
4590}
4591
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004592bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004593 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004594 const DominatorTree *DT,
4595 AssumptionCache *AC) {
4596 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004597}
4598
4599bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004600 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004601 const DominatorTree *DT,
4602 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004603 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4604 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004605 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004606}