blob: e507e89735c5e43ff01cddcf42dc12f454abbad1 [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;
Chandler Carruth66b31302015-01-04 12:03:27 +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,
Chandler Carruth66b31302015-01-04 12:03:27 +000057 const DominatorTree *dt, AssumptionCache *ac = nullptr,
Hal Finkel60db0582014-09-07 18:57:58 +000058 const Instruction *cxti = nullptr)
Chandler Carruth66b31302015-01-04 12:03:27 +000059 : 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);
Duncan Sandsb8cee002012-03-13 11:42:19 +000070static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000072static Value *SimplifyCastInst(unsigned, Value *, Type *,
73 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000074
Sanjay Patel472cc782016-01-11 22:14:42 +000075/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000076/// a vector with every element false, as appropriate for the type.
77static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000078 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000079 "Expected i1 type or a vector of i1!");
80 return Constant::getNullValue(Ty);
81}
82
Sanjay Patel472cc782016-01-11 22:14:42 +000083/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000084/// a vector with every element true, as appropriate for the type.
85static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000086 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000087 "Expected i1 type or a vector of i1!");
88 return Constant::getAllOnesValue(Ty);
89}
90
Duncan Sands3d5692a2011-10-30 19:56:36 +000091/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
92static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
93 Value *RHS) {
94 CmpInst *Cmp = dyn_cast<CmpInst>(V);
95 if (!Cmp)
96 return false;
97 CmpInst::Predicate CPred = Cmp->getPredicate();
98 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
99 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
100 return true;
101 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
102 CRHS == LHS;
103}
104
Sanjay Patel472cc782016-01-11 22:14:42 +0000105/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000106static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
107 Instruction *I = dyn_cast<Instruction>(V);
108 if (!I)
109 // Arguments and constants dominate all instructions.
110 return true;
111
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000112 // If we are processing instructions (and/or basic blocks) that have not been
113 // fully added to a function, the parent nodes may still be null. Simply
114 // return the conservative answer in these cases.
115 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
116 return false;
117
Duncan Sands5ffc2982010-11-16 12:16:38 +0000118 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000119 if (DT) {
120 if (!DT->isReachableFromEntry(P->getParent()))
121 return true;
122 if (!DT->isReachableFromEntry(I->getParent()))
123 return false;
124 return DT->dominates(I, P);
125 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000126
David Majnemer8a1c45d2015-12-12 05:38:55 +0000127 // Otherwise, if the instruction is in the entry block and is not an invoke,
128 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000129 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000130 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000131 return true;
132
133 return false;
134}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000135
Sanjay Patel472cc782016-01-11 22:14:42 +0000136/// Simplify "A op (B op' C)" by distributing op over op', turning it into
137/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000138/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
139/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
140/// Returns the simplified value, or null if no simplification was performed.
141static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000142 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000143 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000144 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000145 // Recursion is always used, so bail out at once if we already hit the limit.
146 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000147 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148
149 // Check whether the expression has the form "(A op' B) op C".
150 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
151 if (Op0->getOpcode() == OpcodeToExpand) {
152 // It does! Try turning it into "(A op C) op' (B op C)".
153 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
154 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000155 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
156 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000157 // They do! Return "L op' R" if it simplifies or is already available.
158 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000159 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
160 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000161 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000162 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000163 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000164 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000165 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000166 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000168 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000169 }
170 }
171
172 // Check whether the expression has the form "A op (B op' C)".
173 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
174 if (Op1->getOpcode() == OpcodeToExpand) {
175 // It does! Try turning it into "(A op B) op' (A op C)".
176 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
177 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000178 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
179 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000180 // They do! Return "L op' R" if it simplifies or is already available.
181 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000182 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
183 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000184 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000185 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000186 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000187 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000188 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000191 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000192 }
193 }
194
Craig Topper9f008862014-04-15 04:59:12 +0000195 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000196}
197
Sanjay Patel472cc782016-01-11 22:14:42 +0000198/// Generic simplifications for associative binary operations.
199/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000200static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000201 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000202 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000203 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
204
205 // Recursion is always used, so bail out at once if we already hit the limit.
206 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000207 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000208
209 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
210 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
211
212 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
213 if (Op0 && Op0->getOpcode() == Opcode) {
214 Value *A = Op0->getOperand(0);
215 Value *B = Op0->getOperand(1);
216 Value *C = RHS;
217
218 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000219 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000220 // It does! Return "A op V" if it simplifies or is already available.
221 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000222 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000224 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000225 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000227 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000228 }
229 }
230
231 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
232 if (Op1 && Op1->getOpcode() == Opcode) {
233 Value *A = LHS;
234 Value *B = Op1->getOperand(0);
235 Value *C = Op1->getOperand(1);
236
237 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000238 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000239 // It does! Return "V op C" if it simplifies or is already available.
240 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000241 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000242 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000243 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000244 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000245 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000246 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000247 }
248 }
249
250 // The remaining transforms require commutativity as well as associativity.
251 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000252 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000253
254 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
255 if (Op0 && Op0->getOpcode() == Opcode) {
256 Value *A = Op0->getOperand(0);
257 Value *B = Op0->getOperand(1);
258 Value *C = RHS;
259
260 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000261 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000262 // It does! Return "V op B" if it simplifies or is already available.
263 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000264 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000265 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000266 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000267 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000269 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000270 }
271 }
272
273 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
274 if (Op1 && Op1->getOpcode() == Opcode) {
275 Value *A = LHS;
276 Value *B = Op1->getOperand(0);
277 Value *C = Op1->getOperand(1);
278
279 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000280 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000281 // It does! Return "B op V" if it simplifies or is already available.
282 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000283 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000284 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000285 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000286 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000288 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000289 }
290 }
291
Craig Topper9f008862014-04-15 04:59:12 +0000292 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000293}
294
Sanjay Patel472cc782016-01-11 22:14:42 +0000295/// In the case of a binary operation with a select instruction as an operand,
296/// try to simplify the binop by seeing whether evaluating it on both branches
297/// of the select results in the same value. Returns the common value if so,
298/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000299static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000300 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000301 // Recursion is always used, so bail out at once if we already hit the limit.
302 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000303 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000304
Duncan Sandsb0579e92010-11-10 13:00:08 +0000305 SelectInst *SI;
306 if (isa<SelectInst>(LHS)) {
307 SI = cast<SelectInst>(LHS);
308 } else {
309 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
310 SI = cast<SelectInst>(RHS);
311 }
312
313 // Evaluate the BinOp on the true and false branches of the select.
314 Value *TV;
315 Value *FV;
316 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000317 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
318 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000319 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000320 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
321 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000322 }
323
Duncan Sandse3c53952011-01-01 16:12:09 +0000324 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000325 // If they both failed to simplify then return null.
326 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000327 return TV;
328
329 // If one branch simplified to undef, return the other one.
330 if (TV && isa<UndefValue>(TV))
331 return FV;
332 if (FV && isa<UndefValue>(FV))
333 return TV;
334
335 // If applying the operation did not change the true and false select values,
336 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000337 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000338 return SI;
339
340 // If one branch simplified and the other did not, and the simplified
341 // value is equal to the unsimplified one, return the simplified value.
342 // For example, select (cond, X, X & Z) & Z -> X & Z.
343 if ((FV && !TV) || (TV && !FV)) {
344 // Check that the simplified value has the form "X op Y" where "op" is the
345 // same as the original operation.
346 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
347 if (Simplified && Simplified->getOpcode() == Opcode) {
348 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
349 // We already know that "op" is the same as for the simplified value. See
350 // if the operands match too. If so, return the simplified value.
351 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
352 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
353 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000354 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
355 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000356 return Simplified;
357 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000358 Simplified->getOperand(1) == UnsimplifiedLHS &&
359 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000360 return Simplified;
361 }
362 }
363
Craig Topper9f008862014-04-15 04:59:12 +0000364 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000365}
366
Sanjay Patel472cc782016-01-11 22:14:42 +0000367/// In the case of a comparison with a select instruction, try to simplify the
368/// comparison by seeing whether both branches of the select result in the same
369/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000370static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000371 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000372 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000373 // Recursion is always used, so bail out at once if we already hit the limit.
374 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000375 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000376
Duncan Sandsb0579e92010-11-10 13:00:08 +0000377 // Make sure the select is on the LHS.
378 if (!isa<SelectInst>(LHS)) {
379 std::swap(LHS, RHS);
380 Pred = CmpInst::getSwappedPredicate(Pred);
381 }
382 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
383 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000384 Value *Cond = SI->getCondition();
385 Value *TV = SI->getTrueValue();
386 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000387
Duncan Sands06504022011-02-03 09:37:39 +0000388 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000389 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000390 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000391 if (TCmp == Cond) {
392 // It not only simplified, it simplified to the select condition. Replace
393 // it with 'true'.
394 TCmp = getTrue(Cond->getType());
395 } else if (!TCmp) {
396 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
397 // condition then we can replace it with 'true'. Otherwise give up.
398 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000399 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000400 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000401 }
402
Duncan Sands3d5692a2011-10-30 19:56:36 +0000403 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000404 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000405 if (FCmp == Cond) {
406 // It not only simplified, it simplified to the select condition. Replace
407 // it with 'false'.
408 FCmp = getFalse(Cond->getType());
409 } else if (!FCmp) {
410 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
411 // condition then we can replace it with 'false'. Otherwise give up.
412 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000413 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000414 FCmp = getFalse(Cond->getType());
415 }
416
417 // If both sides simplified to the same value, then use it as the result of
418 // the original comparison.
419 if (TCmp == FCmp)
420 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000421
422 // The remaining cases only make sense if the select condition has the same
423 // type as the result of the comparison, so bail out if this is not so.
424 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000425 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000426 // If the false value simplified to false, then the result of the compare
427 // is equal to "Cond && TCmp". This also catches the case when the false
428 // value simplified to false and the true value to true, returning "Cond".
429 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000430 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000431 return V;
432 // If the true value simplified to true, then the result of the compare
433 // is equal to "Cond || FCmp".
434 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000435 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000436 return V;
437 // Finally, if the false value simplified to true and the true value to
438 // false, then the result of the compare is equal to "!Cond".
439 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
440 if (Value *V =
441 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000442 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000443 return V;
444
Craig Topper9f008862014-04-15 04:59:12 +0000445 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000446}
447
Sanjay Patel472cc782016-01-11 22:14:42 +0000448/// In the case of a binary operation with an operand that is a PHI instruction,
449/// try to simplify the binop by seeing whether evaluating it on the incoming
450/// phi values yields the same result for every value. If so returns the common
451/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000452static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000453 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000454 // Recursion is always used, so bail out at once if we already hit the limit.
455 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000456 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000457
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000458 PHINode *PI;
459 if (isa<PHINode>(LHS)) {
460 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000461 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000462 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000463 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000464 } else {
465 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
466 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000467 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000468 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000469 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 }
471
472 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000473 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000474 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000475 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000476 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000477 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000478 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
479 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480 // If the operation failed to simplify, or simplified to a different value
481 // to previously, then give up.
482 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000483 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000484 CommonValue = V;
485 }
486
487 return CommonValue;
488}
489
Sanjay Patel472cc782016-01-11 22:14:42 +0000490/// In the case of a comparison with a PHI instruction, try to simplify the
491/// comparison by seeing whether comparing with all of the incoming phi values
492/// yields the same result every time. If so returns the common result,
493/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000494static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000495 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000496 // Recursion is always used, so bail out at once if we already hit the limit.
497 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000498 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000499
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000500 // Make sure the phi is on the LHS.
501 if (!isa<PHINode>(LHS)) {
502 std::swap(LHS, RHS);
503 Pred = CmpInst::getSwappedPredicate(Pred);
504 }
505 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
506 PHINode *PI = cast<PHINode>(LHS);
507
Duncan Sands5ffc2982010-11-16 12:16:38 +0000508 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000509 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000510 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000511
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000513 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000514 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000515 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000516 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000517 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000518 // If the operation failed to simplify, or simplified to a different value
519 // to previously, then give up.
520 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000521 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000522 CommonValue = V;
523 }
524
525 return CommonValue;
526}
527
Sanjay Patel472cc782016-01-11 22:14:42 +0000528/// Given operands for an Add, see if we can fold the result.
529/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000530static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000531 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000532 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000533 if (Constant *CRHS = dyn_cast<Constant>(Op1))
534 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000535
Chris Lattner3d9823b2009-11-27 17:42:22 +0000536 // Canonicalize the constant to the RHS.
537 std::swap(Op0, Op1);
538 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000539
Duncan Sands0a2c41682010-12-15 14:07:39 +0000540 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000541 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000542 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000543
Duncan Sands0a2c41682010-12-15 14:07:39 +0000544 // X + 0 -> X
545 if (match(Op1, m_Zero()))
546 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000547
Duncan Sands0a2c41682010-12-15 14:07:39 +0000548 // X + (Y - X) -> Y
549 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000550 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000551 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000552 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
553 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000554 return Y;
555
556 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000557 if (match(Op0, m_Not(m_Specific(Op1))) ||
558 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000559 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000560
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000561 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000562 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000563 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000564 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000565
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000566 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000567 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000568 MaxRecurse))
569 return V;
570
Duncan Sandsb238de02010-11-19 09:20:39 +0000571 // Threading Add over selects and phi nodes is pointless, so don't bother.
572 // Threading over the select in "A + select(cond, B, C)" means evaluating
573 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
574 // only if B and C are equal. If B and C are equal then (since we assume
575 // that operands have already been simplified) "select(cond, B, C)" should
576 // have been simplified to the common value of B and C already. Analysing
577 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
578 // for threading over phi nodes.
579
Craig Topper9f008862014-04-15 04:59:12 +0000580 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000581}
582
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000583Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000584 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000585 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000586 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000587 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
588 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000589}
590
Chandler Carrutha0796552012-03-12 11:19:31 +0000591/// \brief Compute the base pointer and cumulative constant offsets for V.
592///
593/// This strips all constant offsets off of V, leaving it the base pointer, and
594/// accumulates the total constant offset applied in the returned constant. It
595/// returns 0 if V is not a pointer, and returns the constant '0' if there are
596/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000597///
598/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
599/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000601static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000602 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000603 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000604
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000606 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000607
608 // Even though we don't look through PHI nodes, we could be called on an
609 // instruction in an unreachable block, which may be on a cycle.
610 SmallPtrSet<Value *, 4> Visited;
611 Visited.insert(V);
612 do {
613 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000614 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000617 V = GEP->getPointerOperand();
618 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000619 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000620 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000621 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 break;
623 V = GA->getAliasee();
624 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000625 if (auto CS = CallSite(V))
626 if (Value *RV = CS.getReturnedArgOperand()) {
627 V = RV;
628 continue;
629 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000630 break;
631 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000632 assert(V->getType()->getScalarType()->isPointerTy() &&
633 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000634 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000635
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000636 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637 if (V->getType()->isVectorTy())
638 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
639 OffsetIntPtr);
640 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000641}
642
643/// \brief Compute the constant difference between two pointer values.
644/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
646 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000647 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000649
650 // If LHS and RHS are not related via constant offsets to the same base
651 // value, there is nothing we can do here.
652 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000653 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000654
655 // Otherwise, the difference of LHS - RHS can be computed as:
656 // LHS - RHS
657 // = (LHSOffset + Base) - (RHSOffset + Base)
658 // = LHSOffset - RHSOffset
659 return ConstantExpr::getSub(LHSOffset, RHSOffset);
660}
661
Sanjay Patel472cc782016-01-11 22:14:42 +0000662/// Given operands for a Sub, see if we can fold the result.
663/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000664static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000665 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000666 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000667 if (Constant *CRHS = dyn_cast<Constant>(Op1))
668 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000669
670 // X - undef -> undef
671 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000672 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000673 return UndefValue::get(Op0->getType());
674
675 // X - 0 -> X
676 if (match(Op1, m_Zero()))
677 return Op0;
678
679 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000680 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000681 return Constant::getNullValue(Op0->getType());
682
Sanjay Patelefd88852016-10-19 21:23:45 +0000683 // Is this a negation?
684 if (match(Op0, m_Zero())) {
685 // 0 - X -> 0 if the sub is NUW.
686 if (isNUW)
687 return Op0;
688
689 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
690 APInt KnownZero(BitWidth, 0);
691 APInt KnownOne(BitWidth, 0);
692 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
693 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
694 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
695 // Op1 must be 0 because negating the minimum signed value is undefined.
696 if (isNSW)
697 return Op0;
698
699 // 0 - X -> X if X is 0 or the minimum signed value.
700 return Op1;
701 }
702 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000703
Duncan Sands99589d02011-01-18 11:50:19 +0000704 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
705 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000706 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000707 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
708 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000709 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000710 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000711 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000712 // It does, we successfully reassociated!
713 ++NumReassoc;
714 return W;
715 }
716 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000717 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000718 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000719 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000720 // It does, we successfully reassociated!
721 ++NumReassoc;
722 return W;
723 }
724 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000725
Duncan Sands99589d02011-01-18 11:50:19 +0000726 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
727 // For example, X - (X + 1) -> -1
728 X = Op0;
729 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
730 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000731 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000732 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does, we successfully reassociated!
735 ++NumReassoc;
736 return W;
737 }
738 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000739 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000740 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000741 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000742 // It does, we successfully reassociated!
743 ++NumReassoc;
744 return W;
745 }
746 }
747
748 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
749 // For example, X - (X - Y) -> Y.
750 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000751 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
752 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000753 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000754 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000756 // It does, we successfully reassociated!
757 ++NumReassoc;
758 return W;
759 }
760
Duncan Sands395ac42d2012-03-13 14:07:05 +0000761 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
762 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
763 match(Op1, m_Trunc(m_Value(Y))))
764 if (X->getType() == Y->getType())
765 // See if "V === X - Y" simplifies.
766 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
767 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000768 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
769 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000770 // It does, return the simplified "trunc V".
771 return W;
772
773 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000774 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000775 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000776 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000777 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
778
Duncan Sands99589d02011-01-18 11:50:19 +0000779 // i1 sub -> xor.
780 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000781 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000782 return V;
783
Duncan Sands0a2c41682010-12-15 14:07:39 +0000784 // Threading Sub over selects and phi nodes is pointless, so don't bother.
785 // Threading over the select in "A - select(cond, B, C)" means evaluating
786 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
787 // only if B and C are equal. If B and C are equal then (since we assume
788 // that operands have already been simplified) "select(cond, B, C)" should
789 // have been simplified to the common value of B and C already. Analysing
790 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
791 // for threading over phi nodes.
792
Craig Topper9f008862014-04-15 04:59:12 +0000793 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000794}
795
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000796Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000797 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000798 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000799 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000800 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
801 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000802}
803
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000804/// Given operands for an FAdd, see if we can fold the result. If not, this
805/// returns null.
806static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
807 const Query &Q, unsigned MaxRecurse) {
808 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000809 if (Constant *CRHS = dyn_cast<Constant>(Op1))
810 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000811
812 // Canonicalize the constant to the RHS.
813 std::swap(Op0, Op1);
814 }
815
816 // fadd X, -0 ==> X
817 if (match(Op1, m_NegZero()))
818 return Op0;
819
820 // fadd X, 0 ==> X, when we know X is not -0
821 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000822 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000823 return Op0;
824
825 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
826 // where nnan and ninf have to occur at least once somewhere in this
827 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000828 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000829 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
830 SubOp = Op1;
831 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
832 SubOp = Op0;
833 if (SubOp) {
834 Instruction *FSub = cast<Instruction>(SubOp);
835 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
836 (FMF.noInfs() || FSub->hasNoInfs()))
837 return Constant::getNullValue(Op0->getType());
838 }
839
Craig Topper9f008862014-04-15 04:59:12 +0000840 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000841}
842
843/// Given operands for an FSub, see if we can fold the result. If not, this
844/// returns null.
845static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
846 const Query &Q, unsigned MaxRecurse) {
847 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000848 if (Constant *CRHS = dyn_cast<Constant>(Op1))
849 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000850 }
851
852 // fsub X, 0 ==> X
853 if (match(Op1, m_Zero()))
854 return Op0;
855
856 // fsub X, -0 ==> X, when we know X is not -0
857 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000858 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000859 return Op0;
860
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000861 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000862 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000863 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
864 return X;
865
866 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000867 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000868 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
869 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000870
Benjamin Kramer228680d2015-06-14 21:01:20 +0000871 // fsub nnan x, x ==> 0.0
872 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000873 return Constant::getNullValue(Op0->getType());
874
Craig Topper9f008862014-04-15 04:59:12 +0000875 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000876}
877
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000878/// Given the operands for an FMul, see if we can fold the result
879static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
880 FastMathFlags FMF,
881 const Query &Q,
882 unsigned MaxRecurse) {
883 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000884 if (Constant *CRHS = dyn_cast<Constant>(Op1))
885 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000886
887 // Canonicalize the constant to the RHS.
888 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000889 }
890
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000891 // fmul X, 1.0 ==> X
892 if (match(Op1, m_FPOne()))
893 return Op0;
894
895 // fmul nnan nsz X, 0 ==> 0
896 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
897 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000898
Craig Topper9f008862014-04-15 04:59:12 +0000899 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000900}
901
Sanjay Patel472cc782016-01-11 22:14:42 +0000902/// Given operands for a Mul, see if we can fold the result.
903/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000904static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
905 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000906 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000907 if (Constant *CRHS = dyn_cast<Constant>(Op1))
908 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000909
910 // Canonicalize the constant to the RHS.
911 std::swap(Op0, Op1);
912 }
913
914 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000915 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000916 return Constant::getNullValue(Op0->getType());
917
918 // X * 0 -> 0
919 if (match(Op1, m_Zero()))
920 return Op1;
921
922 // X * 1 -> X
923 if (match(Op1, m_One()))
924 return Op0;
925
Duncan Sandsb67edc62011-01-30 18:03:50 +0000926 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000927 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000928 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
929 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
930 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000931
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000932 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000933 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000934 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000935 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000936
937 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000938 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000939 MaxRecurse))
940 return V;
941
942 // Mul distributes over Add. Try some generic simplifications based on this.
943 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000944 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000945 return V;
946
947 // If the operation is with the result of a select instruction, check whether
948 // operating on either branch of the select always yields the same value.
949 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000950 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000951 MaxRecurse))
952 return V;
953
954 // If the operation is with the result of a phi instruction, check whether
955 // operating on all incoming values of the phi always yields the same value.
956 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000957 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000958 MaxRecurse))
959 return V;
960
Craig Topper9f008862014-04-15 04:59:12 +0000961 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000962}
963
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000964Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000966 const TargetLibraryInfo *TLI,
967 const DominatorTree *DT, AssumptionCache *AC,
968 const Instruction *CxtI) {
969 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000970 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000971}
972
973Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000974 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000975 const TargetLibraryInfo *TLI,
976 const DominatorTree *DT, AssumptionCache *AC,
977 const Instruction *CxtI) {
978 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000979 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000980}
981
Chandler Carruth66b31302015-01-04 12:03:27 +0000982Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000983 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000984 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000985 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000986 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000987 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000988 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000989}
990
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000991Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000992 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000993 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000994 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000995 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000996 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000997}
998
Sanjay Patel472cc782016-01-11 22:14:42 +0000999/// Given operands for an SDiv or UDiv, see if we can fold the result.
1000/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001001static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001002 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001003 if (Constant *C0 = dyn_cast<Constant>(Op0))
1004 if (Constant *C1 = dyn_cast<Constant>(Op1))
1005 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001006
Duncan Sands65995fa2011-01-28 18:50:50 +00001007 bool isSigned = Opcode == Instruction::SDiv;
1008
Duncan Sands771e82a2011-01-28 16:51:11 +00001009 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001010 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001011 return Op1;
1012
David Majnemer71dc8fb2014-12-10 07:52:18 +00001013 // X / 0 -> undef, we don't need to preserve faults!
1014 if (match(Op1, m_Zero()))
1015 return UndefValue::get(Op1->getType());
1016
Duncan Sands771e82a2011-01-28 16:51:11 +00001017 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001018 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001019 return Constant::getNullValue(Op0->getType());
1020
1021 // 0 / X -> 0, we don't need to preserve faults!
1022 if (match(Op0, m_Zero()))
1023 return Op0;
1024
1025 // X / 1 -> X
1026 if (match(Op1, m_One()))
1027 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001028
1029 if (Op0->getType()->isIntegerTy(1))
1030 // It can't be division by zero, hence it must be division by one.
1031 return Op0;
1032
1033 // X / X -> 1
1034 if (Op0 == Op1)
1035 return ConstantInt::get(Op0->getType(), 1);
1036
1037 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001038 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001039 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1040 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001041 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001042 // If the Mul knows it does not overflow, then we are good to go.
1043 if ((isSigned && Mul->hasNoSignedWrap()) ||
1044 (!isSigned && Mul->hasNoUnsignedWrap()))
1045 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001046 // If X has the form X = A / Y then X * Y cannot overflow.
1047 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1048 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1049 return X;
1050 }
1051
Duncan Sands65995fa2011-01-28 18:50:50 +00001052 // (X rem Y) / Y -> 0
1053 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1054 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1055 return Constant::getNullValue(Op0->getType());
1056
David Majnemercb9d5962014-10-11 10:20:01 +00001057 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1058 ConstantInt *C1, *C2;
1059 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1060 match(Op1, m_ConstantInt(C2))) {
1061 bool Overflow;
1062 C1->getValue().umul_ov(C2->getValue(), Overflow);
1063 if (Overflow)
1064 return Constant::getNullValue(Op0->getType());
1065 }
1066
Duncan Sands65995fa2011-01-28 18:50:50 +00001067 // If the operation is with the result of a select instruction, check whether
1068 // operating on either branch of the select always yields the same value.
1069 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001070 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001071 return V;
1072
1073 // If the operation is with the result of a phi instruction, check whether
1074 // operating on all incoming values of the phi always yields the same value.
1075 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001076 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001077 return V;
1078
Craig Topper9f008862014-04-15 04:59:12 +00001079 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001080}
1081
Sanjay Patel472cc782016-01-11 22:14:42 +00001082/// Given operands for an SDiv, see if we can fold the result.
1083/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001084static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1085 unsigned MaxRecurse) {
1086 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001087 return V;
1088
Craig Topper9f008862014-04-15 04:59:12 +00001089 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001090}
1091
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001092Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001093 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001094 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001095 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001096 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001097 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001098}
1099
Sanjay Patel472cc782016-01-11 22:14:42 +00001100/// Given operands for a UDiv, see if we can fold the result.
1101/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001102static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1103 unsigned MaxRecurse) {
1104 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001105 return V;
1106
Craig Topper9f008862014-04-15 04:59:12 +00001107 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001108}
1109
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001110Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001111 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001112 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001113 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001114 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001115 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001116}
1117
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001118static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1119 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001120 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001121 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001122 return Op0;
1123
1124 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001125 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001126 return Op1;
1127
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001128 // 0 / X -> 0
1129 // Requires that NaNs are off (X could be zero) and signed zeroes are
1130 // ignored (X could be positive or negative, so the output sign is unknown).
1131 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1132 return Op0;
1133
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001134 if (FMF.noNaNs()) {
1135 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001136 if (Op0 == Op1)
1137 return ConstantFP::get(Op0->getType(), 1.0);
1138
1139 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001140 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001141 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1142 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1143 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1144 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1145 BinaryOperator::getFNegArgument(Op1) == Op0))
1146 return ConstantFP::get(Op0->getType(), -1.0);
1147 }
1148
Craig Topper9f008862014-04-15 04:59:12 +00001149 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001150}
1151
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001152Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001153 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001154 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001155 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001156 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001157 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001158 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001159}
1160
Sanjay Patel472cc782016-01-11 22:14:42 +00001161/// Given operands for an SRem or URem, see if we can fold the result.
1162/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001163static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001164 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001165 if (Constant *C0 = dyn_cast<Constant>(Op0))
1166 if (Constant *C1 = dyn_cast<Constant>(Op1))
1167 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001168
Duncan Sandsa3e36992011-05-02 16:27:02 +00001169 // X % undef -> undef
1170 if (match(Op1, m_Undef()))
1171 return Op1;
1172
1173 // undef % X -> 0
1174 if (match(Op0, m_Undef()))
1175 return Constant::getNullValue(Op0->getType());
1176
1177 // 0 % X -> 0, we don't need to preserve faults!
1178 if (match(Op0, m_Zero()))
1179 return Op0;
1180
1181 // X % 0 -> undef, we don't need to preserve faults!
1182 if (match(Op1, m_Zero()))
1183 return UndefValue::get(Op0->getType());
1184
1185 // X % 1 -> 0
1186 if (match(Op1, m_One()))
1187 return Constant::getNullValue(Op0->getType());
1188
1189 if (Op0->getType()->isIntegerTy(1))
1190 // It can't be remainder by zero, hence it must be remainder by one.
1191 return Constant::getNullValue(Op0->getType());
1192
1193 // X % X -> 0
1194 if (Op0 == Op1)
1195 return Constant::getNullValue(Op0->getType());
1196
David Majnemerb435a422014-09-17 04:16:35 +00001197 // (X % Y) % Y -> X % Y
1198 if ((Opcode == Instruction::SRem &&
1199 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1200 (Opcode == Instruction::URem &&
1201 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001202 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001203
Duncan Sandsa3e36992011-05-02 16:27:02 +00001204 // If the operation is with the result of a select instruction, check whether
1205 // operating on either branch of the select always yields the same value.
1206 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001207 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001208 return V;
1209
1210 // If the operation is with the result of a phi instruction, check whether
1211 // operating on all incoming values of the phi always yields the same value.
1212 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001213 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001214 return V;
1215
Craig Topper9f008862014-04-15 04:59:12 +00001216 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001217}
1218
Sanjay Patel472cc782016-01-11 22:14:42 +00001219/// Given operands for an SRem, see if we can fold the result.
1220/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001221static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1222 unsigned MaxRecurse) {
1223 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001224 return V;
1225
Craig Topper9f008862014-04-15 04:59:12 +00001226 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001227}
1228
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001229Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001230 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001231 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001232 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001233 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001234 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001235}
1236
Sanjay Patel472cc782016-01-11 22:14:42 +00001237/// Given operands for a URem, see if we can fold the result.
1238/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001239static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001240 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001241 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001242 return V;
1243
Craig Topper9f008862014-04-15 04:59:12 +00001244 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001245}
1246
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001248 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001249 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001250 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001251 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001252 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001253}
1254
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001255static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1256 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001257 // undef % X -> undef (the undef could be a snan).
1258 if (match(Op0, m_Undef()))
1259 return Op0;
1260
1261 // X % undef -> undef
1262 if (match(Op1, m_Undef()))
1263 return Op1;
1264
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001265 // 0 % X -> 0
1266 // Requires that NaNs are off (X could be zero) and signed zeroes are
1267 // ignored (X could be positive or negative, so the output sign is unknown).
1268 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1269 return Op0;
1270
Craig Topper9f008862014-04-15 04:59:12 +00001271 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001272}
1273
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001274Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001275 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001276 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001277 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001278 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001279 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001280 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001281}
1282
Sanjay Patel472cc782016-01-11 22:14:42 +00001283/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001284static bool isUndefShift(Value *Amount) {
1285 Constant *C = dyn_cast<Constant>(Amount);
1286 if (!C)
1287 return false;
1288
1289 // X shift by undef -> undef because it may shift by the bitwidth.
1290 if (isa<UndefValue>(C))
1291 return true;
1292
1293 // Shifting by the bitwidth or more is undefined.
1294 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1295 if (CI->getValue().getLimitedValue() >=
1296 CI->getType()->getScalarSizeInBits())
1297 return true;
1298
1299 // If all lanes of a vector shift are undefined the whole shift is.
1300 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1301 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1302 if (!isUndefShift(C->getAggregateElement(I)))
1303 return false;
1304 return true;
1305 }
1306
1307 return false;
1308}
1309
Sanjay Patel472cc782016-01-11 22:14:42 +00001310/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1311/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001312static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001313 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001314 if (Constant *C0 = dyn_cast<Constant>(Op0))
1315 if (Constant *C1 = dyn_cast<Constant>(Op1))
1316 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001317
Duncan Sands571fd9a2011-01-14 14:44:12 +00001318 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001319 if (match(Op0, m_Zero()))
1320 return Op0;
1321
Duncan Sands571fd9a2011-01-14 14:44:12 +00001322 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001323 if (match(Op1, m_Zero()))
1324 return Op0;
1325
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001326 // Fold undefined shifts.
1327 if (isUndefShift(Op1))
1328 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001329
Duncan Sands571fd9a2011-01-14 14:44:12 +00001330 // If the operation is with the result of a select instruction, check whether
1331 // operating on either branch of the select always yields the same value.
1332 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001333 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001334 return V;
1335
1336 // If the operation is with the result of a phi instruction, check whether
1337 // operating on all incoming values of the phi always yields the same value.
1338 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001339 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001340 return V;
1341
Sanjay Patel6786bc52016-05-10 20:46:54 +00001342 // If any bits in the shift amount make that value greater than or equal to
1343 // the number of bits in the type, the shift is undefined.
1344 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1345 APInt KnownZero(BitWidth, 0);
1346 APInt KnownOne(BitWidth, 0);
1347 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1348 if (KnownOne.getLimitedValue() >= BitWidth)
1349 return UndefValue::get(Op0->getType());
1350
1351 // If all valid bits in the shift amount are known zero, the first operand is
1352 // unchanged.
1353 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1354 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1355 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1356 return Op0;
1357
Craig Topper9f008862014-04-15 04:59:12 +00001358 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001359}
1360
David Majnemerbf7550e2014-11-05 00:59:59 +00001361/// \brief Given operands for an Shl, LShr or AShr, see if we can
1362/// fold the result. If not, this returns null.
1363static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1364 bool isExact, const Query &Q,
1365 unsigned MaxRecurse) {
1366 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1367 return V;
1368
1369 // X >> X -> 0
1370 if (Op0 == Op1)
1371 return Constant::getNullValue(Op0->getType());
1372
David Majnemer65c52ae2014-12-17 01:54:33 +00001373 // undef >> X -> 0
1374 // undef >> X -> undef (if it's exact)
1375 if (match(Op0, m_Undef()))
1376 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1377
David Majnemerbf7550e2014-11-05 00:59:59 +00001378 // The low bit cannot be shifted out of an exact shift if it is set.
1379 if (isExact) {
1380 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1381 APInt Op0KnownZero(BitWidth, 0);
1382 APInt Op0KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00001383 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1384 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001385 if (Op0KnownOne[0])
1386 return Op0;
1387 }
1388
1389 return nullptr;
1390}
1391
Sanjay Patel472cc782016-01-11 22:14:42 +00001392/// Given operands for an Shl, see if we can fold the result.
1393/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001394static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001395 const Query &Q, unsigned MaxRecurse) {
1396 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001397 return V;
1398
1399 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001400 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001401 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001402 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001403
Chris Lattner9e4aa022011-02-09 17:15:04 +00001404 // (X >> A) << A -> X
1405 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001406 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001407 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001408 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001409}
1410
Chris Lattner9e4aa022011-02-09 17:15:04 +00001411Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001412 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001413 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001414 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001415 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001416 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001417}
1418
Sanjay Patel472cc782016-01-11 22:14:42 +00001419/// Given operands for an LShr, see if we can fold the result.
1420/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001421static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001422 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001423 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1424 MaxRecurse))
1425 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001426
Chris Lattner9e4aa022011-02-09 17:15:04 +00001427 // (X << A) >> A -> X
1428 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001429 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001430 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001431
Craig Topper9f008862014-04-15 04:59:12 +00001432 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001433}
1434
Chris Lattner9e4aa022011-02-09 17:15:04 +00001435Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001436 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001437 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001438 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001439 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001440 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001441 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001442}
1443
Sanjay Patel472cc782016-01-11 22:14:42 +00001444/// Given operands for an AShr, see if we can fold the result.
1445/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001446static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001447 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001448 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1449 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001450 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001451
1452 // all ones >>a X -> all ones
1453 if (match(Op0, m_AllOnes()))
1454 return Op0;
1455
Chris Lattner9e4aa022011-02-09 17:15:04 +00001456 // (X << A) >> A -> X
1457 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001458 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001459 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001460
Suyog Sarda68862412014-07-17 06:28:15 +00001461 // Arithmetic shifting an all-sign-bit value is a no-op.
Chandler Carruth66b31302015-01-04 12:03:27 +00001462 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001463 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1464 return Op0;
1465
Craig Topper9f008862014-04-15 04:59:12 +00001466 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001467}
1468
Chris Lattner9e4aa022011-02-09 17:15:04 +00001469Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001470 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001471 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001472 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001473 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001474 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001475 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001476}
1477
David Majnemer1af36e52014-12-06 10:51:40 +00001478static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1479 ICmpInst *UnsignedICmp, bool IsAnd) {
1480 Value *X, *Y;
1481
1482 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001483 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1484 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001485 return nullptr;
1486
1487 ICmpInst::Predicate UnsignedPred;
1488 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1489 ICmpInst::isUnsigned(UnsignedPred))
1490 ;
1491 else if (match(UnsignedICmp,
1492 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1493 ICmpInst::isUnsigned(UnsignedPred))
1494 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1495 else
1496 return nullptr;
1497
1498 // X < Y && Y != 0 --> X < Y
1499 // X < Y || Y != 0 --> Y != 0
1500 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1501 return IsAnd ? UnsignedICmp : ZeroICmp;
1502
1503 // X >= Y || Y != 0 --> true
1504 // X >= Y || Y == 0 --> X >= Y
1505 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1506 if (EqPred == ICmpInst::ICMP_NE)
1507 return getTrue(UnsignedICmp->getType());
1508 return UnsignedICmp;
1509 }
1510
David Majnemerd5b3aa42014-12-08 18:30:43 +00001511 // X < Y && Y == 0 --> false
1512 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1513 IsAnd)
1514 return getFalse(UnsignedICmp->getType());
1515
David Majnemer1af36e52014-12-06 10:51:40 +00001516 return nullptr;
1517}
1518
David Majnemera315bd82014-09-15 08:15:28 +00001519static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001520 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1521 return X;
1522
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001523 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001524 Type *ITy = Op0->getType();
1525 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001526 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001527 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001528 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1529 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1530 // Make a constant range that's the intersection of the two icmp ranges.
1531 // If the intersection is empty, we know that the result is false.
1532 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1533 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1534 if (Range0.intersectWith(Range1).isEmptySet())
1535 return getFalse(ITy);
1536 }
1537
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001538 // (icmp (add V, C0), C1) & (icmp V, C0)
1539 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001540 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001541
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001542 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001543 return nullptr;
1544
David Majnemera315bd82014-09-15 08:15:28 +00001545 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001546 if (AddInst->getOperand(1) != Op1->getOperand(1))
1547 return nullptr;
1548
David Majnemera315bd82014-09-15 08:15:28 +00001549 bool isNSW = AddInst->hasNoSignedWrap();
1550 bool isNUW = AddInst->hasNoUnsignedWrap();
1551
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001552 const APInt Delta = *C1 - *C0;
1553 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001554 if (Delta == 2) {
1555 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1556 return getFalse(ITy);
1557 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1558 return getFalse(ITy);
1559 }
1560 if (Delta == 1) {
1561 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1562 return getFalse(ITy);
1563 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1564 return getFalse(ITy);
1565 }
1566 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001567 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001568 if (Delta == 2)
1569 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1570 return getFalse(ITy);
1571 if (Delta == 1)
1572 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1573 return getFalse(ITy);
1574 }
1575
1576 return nullptr;
1577}
1578
Sanjay Patel472cc782016-01-11 22:14:42 +00001579/// Given operands for an And, see if we can fold the result.
1580/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001581static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001582 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001583 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001584 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1585 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001586
Chris Lattnera71e9d62009-11-10 00:55:12 +00001587 // Canonicalize the constant to the RHS.
1588 std::swap(Op0, Op1);
1589 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001590
Chris Lattnera71e9d62009-11-10 00:55:12 +00001591 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001592 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001593 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001594
Chris Lattnera71e9d62009-11-10 00:55:12 +00001595 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001596 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001597 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001598
Duncan Sandsc89ac072010-11-17 18:52:15 +00001599 // X & 0 = 0
1600 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001601 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001602
Duncan Sandsc89ac072010-11-17 18:52:15 +00001603 // X & -1 = X
1604 if (match(Op1, m_AllOnes()))
1605 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001606
Chris Lattnera71e9d62009-11-10 00:55:12 +00001607 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001608 if (match(Op0, m_Not(m_Specific(Op1))) ||
1609 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001610 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001611
Chris Lattnera71e9d62009-11-10 00:55:12 +00001612 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001613 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001614 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001615 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001616 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001617
Chris Lattnera71e9d62009-11-10 00:55:12 +00001618 // A & (A | ?) = A
1619 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001620 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001621 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001622
Duncan Sandsba286d72011-10-26 20:55:21 +00001623 // A & (-A) = A if A is a power of two or zero.
1624 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1625 match(Op1, m_Neg(m_Specific(Op0)))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001626 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1627 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001628 return Op0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001629 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1630 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001631 return Op1;
1632 }
1633
David Majnemera315bd82014-09-15 08:15:28 +00001634 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1635 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1636 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1637 return V;
1638 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1639 return V;
1640 }
1641 }
1642
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001643 // The compares may be hidden behind casts. Look through those and try the
1644 // same folds as above.
1645 auto *Cast0 = dyn_cast<CastInst>(Op0);
1646 auto *Cast1 = dyn_cast<CastInst>(Op1);
1647 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1648 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1649 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1650 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1651 if (Cmp0 && Cmp1) {
1652 Instruction::CastOps CastOpc = Cast0->getOpcode();
1653 Type *ResultType = Cast0->getType();
1654 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1655 return ConstantExpr::getCast(CastOpc, V, ResultType);
1656 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1657 return ConstantExpr::getCast(CastOpc, V, ResultType);
1658 }
1659 }
1660
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001661 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001662 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1663 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001664 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001665
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001666 // And distributes over Or. Try some generic simplifications based on this.
1667 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001668 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001669 return V;
1670
1671 // And distributes over Xor. Try some generic simplifications based on this.
1672 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001673 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001674 return V;
1675
Duncan Sandsb0579e92010-11-10 13:00:08 +00001676 // If the operation is with the result of a select instruction, check whether
1677 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001678 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001679 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1680 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001681 return V;
1682
1683 // If the operation is with the result of a phi instruction, check whether
1684 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001685 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001686 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001687 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001688 return V;
1689
Craig Topper9f008862014-04-15 04:59:12 +00001690 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001691}
1692
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001694 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001695 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001696 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001697 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001698 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001699}
1700
Sanjay Patel472cc782016-01-11 22:14:42 +00001701/// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1702/// contains all possible values.
David Majnemera315bd82014-09-15 08:15:28 +00001703static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001704 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1705 return X;
1706
Sanjay Patel220a8732016-09-28 14:27:21 +00001707 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001708 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001709 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001710 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001711 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001712 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001713
Sanjay Patel220a8732016-09-28 14:27:21 +00001714 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1715 return nullptr;
1716
1717 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1718 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001719 return nullptr;
1720
1721 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001722 bool isNSW = AddInst->hasNoSignedWrap();
1723 bool isNUW = AddInst->hasNoUnsignedWrap();
1724
Sanjay Patel220a8732016-09-28 14:27:21 +00001725 const APInt Delta = *C1 - *C0;
1726 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001727 if (Delta == 2) {
1728 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1729 return getTrue(ITy);
1730 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1731 return getTrue(ITy);
1732 }
1733 if (Delta == 1) {
1734 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1735 return getTrue(ITy);
1736 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1737 return getTrue(ITy);
1738 }
1739 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001740 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001741 if (Delta == 2)
1742 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1743 return getTrue(ITy);
1744 if (Delta == 1)
1745 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1746 return getTrue(ITy);
1747 }
1748
1749 return nullptr;
1750}
1751
Sanjay Patel472cc782016-01-11 22:14:42 +00001752/// Given operands for an Or, see if we can fold the result.
1753/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001754static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1755 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001756 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001757 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1758 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001759
Chris Lattnera71e9d62009-11-10 00:55:12 +00001760 // Canonicalize the constant to the RHS.
1761 std::swap(Op0, Op1);
1762 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001763
Chris Lattnera71e9d62009-11-10 00:55:12 +00001764 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001765 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001766 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001767
Chris Lattnera71e9d62009-11-10 00:55:12 +00001768 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001769 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001770 return Op0;
1771
Duncan Sandsc89ac072010-11-17 18:52:15 +00001772 // X | 0 = X
1773 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001774 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001775
Duncan Sandsc89ac072010-11-17 18:52:15 +00001776 // X | -1 = -1
1777 if (match(Op1, m_AllOnes()))
1778 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001779
Chris Lattnera71e9d62009-11-10 00:55:12 +00001780 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001781 if (match(Op0, m_Not(m_Specific(Op1))) ||
1782 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001783 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001784
Chris Lattnera71e9d62009-11-10 00:55:12 +00001785 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001786 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001787 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001788 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001789 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001790
Chris Lattnera71e9d62009-11-10 00:55:12 +00001791 // A | (A & ?) = A
1792 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001793 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001794 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001795
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001796 // ~(A & ?) | A = -1
1797 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1798 (A == Op1 || B == Op1))
1799 return Constant::getAllOnesValue(Op1->getType());
1800
1801 // A | ~(A & ?) = -1
1802 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1803 (A == Op0 || B == Op0))
1804 return Constant::getAllOnesValue(Op0->getType());
1805
David Majnemera315bd82014-09-15 08:15:28 +00001806 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1807 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1808 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1809 return V;
1810 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1811 return V;
1812 }
1813 }
1814
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001815 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001816 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1817 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001818 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001819
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001820 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001821 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1822 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001823 return V;
1824
Duncan Sandsb0579e92010-11-10 13:00:08 +00001825 // If the operation is with the result of a select instruction, check whether
1826 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001827 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001828 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001829 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001830 return V;
1831
Nick Lewycky8561a492014-06-19 03:51:46 +00001832 // (A & C)|(B & D)
1833 Value *C = nullptr, *D = nullptr;
1834 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1835 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1836 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1837 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1838 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1839 // (A & C1)|(B & C2)
1840 // If we have: ((V + N) & C1) | (V & C2)
1841 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1842 // replace with V+N.
1843 Value *V1, *V2;
1844 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1845 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1846 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001847 if (V1 == B &&
1848 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001849 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001850 if (V2 == B &&
1851 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001852 return A;
1853 }
1854 // Or commutes, try both ways.
1855 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1856 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1857 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001858 if (V1 == A &&
1859 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001860 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001861 if (V2 == A &&
1862 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001863 return B;
1864 }
1865 }
1866 }
1867
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001868 // If the operation is with the result of a phi instruction, check whether
1869 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001870 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001871 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001872 return V;
1873
Craig Topper9f008862014-04-15 04:59:12 +00001874 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001875}
1876
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001877Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001878 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001879 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001880 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001881 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001882 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001883}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001884
Sanjay Patel472cc782016-01-11 22:14:42 +00001885/// Given operands for a Xor, see if we can fold the result.
1886/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001887static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1888 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001889 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001890 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1891 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001892
1893 // Canonicalize the constant to the RHS.
1894 std::swap(Op0, Op1);
1895 }
1896
1897 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001898 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001899 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001900
1901 // A ^ 0 = A
1902 if (match(Op1, m_Zero()))
1903 return Op0;
1904
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001905 // A ^ A = 0
1906 if (Op0 == Op1)
1907 return Constant::getNullValue(Op0->getType());
1908
Duncan Sandsc89ac072010-11-17 18:52:15 +00001909 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001910 if (match(Op0, m_Not(m_Specific(Op1))) ||
1911 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001912 return Constant::getAllOnesValue(Op0->getType());
1913
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001914 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001915 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1916 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001917 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001918
Duncan Sandsb238de02010-11-19 09:20:39 +00001919 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1920 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1921 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1922 // only if B and C are equal. If B and C are equal then (since we assume
1923 // that operands have already been simplified) "select(cond, B, C)" should
1924 // have been simplified to the common value of B and C already. Analysing
1925 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1926 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001927
Craig Topper9f008862014-04-15 04:59:12 +00001928 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001929}
1930
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001931Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001932 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001933 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001934 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001935 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001936 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001937}
1938
Chris Lattner229907c2011-07-18 04:54:35 +00001939static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001940 return CmpInst::makeCmpResultType(Op->getType());
1941}
1942
Sanjay Patel472cc782016-01-11 22:14:42 +00001943/// Rummage around inside V looking for something equivalent to the comparison
1944/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1945/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001946static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1947 Value *LHS, Value *RHS) {
1948 SelectInst *SI = dyn_cast<SelectInst>(V);
1949 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001950 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001951 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1952 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001953 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001954 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1955 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1956 return Cmp;
1957 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1958 LHS == CmpRHS && RHS == CmpLHS)
1959 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001960 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001961}
1962
Dan Gohman9631d902013-02-01 00:49:06 +00001963// A significant optimization not implemented here is assuming that alloca
1964// addresses are not equal to incoming argument values. They don't *alias*,
1965// as we say, but that doesn't mean they aren't equal, so we take a
1966// conservative approach.
1967//
1968// This is inspired in part by C++11 5.10p1:
1969// "Two pointers of the same type compare equal if and only if they are both
1970// null, both point to the same function, or both represent the same
1971// address."
1972//
1973// This is pretty permissive.
1974//
1975// It's also partly due to C11 6.5.9p6:
1976// "Two pointers compare equal if and only if both are null pointers, both are
1977// pointers to the same object (including a pointer to an object and a
1978// subobject at its beginning) or function, both are pointers to one past the
1979// last element of the same array object, or one is a pointer to one past the
1980// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001981// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001982// object in the address space.)
1983//
1984// C11's version is more restrictive, however there's no reason why an argument
1985// couldn't be a one-past-the-end value for a stack object in the caller and be
1986// equal to the beginning of a stack object in the callee.
1987//
1988// If the C and C++ standards are ever made sufficiently restrictive in this
1989// area, it may be possible to update LLVM's semantics accordingly and reinstate
1990// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00001991static Constant *
1992computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1993 const DominatorTree *DT, CmpInst::Predicate Pred,
1994 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001995 // First, skip past any trivial no-ops.
1996 LHS = LHS->stripPointerCasts();
1997 RHS = RHS->stripPointerCasts();
1998
1999 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002000 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002001 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2002 return ConstantInt::get(GetCompareTy(LHS),
2003 !CmpInst::isTrueWhenEqual(Pred));
2004
Chandler Carruth8059c842012-03-25 21:28:14 +00002005 // We can only fold certain predicates on pointer comparisons.
2006 switch (Pred) {
2007 default:
Craig Topper9f008862014-04-15 04:59:12 +00002008 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002009
2010 // Equality comaprisons are easy to fold.
2011 case CmpInst::ICMP_EQ:
2012 case CmpInst::ICMP_NE:
2013 break;
2014
2015 // We can only handle unsigned relational comparisons because 'inbounds' on
2016 // a GEP only protects against unsigned wrapping.
2017 case CmpInst::ICMP_UGT:
2018 case CmpInst::ICMP_UGE:
2019 case CmpInst::ICMP_ULT:
2020 case CmpInst::ICMP_ULE:
2021 // However, we have to switch them to their signed variants to handle
2022 // negative indices from the base pointer.
2023 Pred = ICmpInst::getSignedPredicate(Pred);
2024 break;
2025 }
2026
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002027 // Strip off any constant offsets so that we can reason about them.
2028 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2029 // here and compare base addresses like AliasAnalysis does, however there are
2030 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2031 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2032 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002033 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2034 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002035
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002036 // If LHS and RHS are related via constant offsets to the same base
2037 // value, we can replace it with an icmp which just compares the offsets.
2038 if (LHS == RHS)
2039 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002040
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002041 // Various optimizations for (in)equality comparisons.
2042 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2043 // Different non-empty allocations that exist at the same time have
2044 // different addresses (if the program can tell). Global variables always
2045 // exist, so they always exist during the lifetime of each other and all
2046 // allocas. Two different allocas usually have different addresses...
2047 //
2048 // However, if there's an @llvm.stackrestore dynamically in between two
2049 // allocas, they may have the same address. It's tempting to reduce the
2050 // scope of the problem by only looking at *static* allocas here. That would
2051 // cover the majority of allocas while significantly reducing the likelihood
2052 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2053 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2054 // an entry block. Also, if we have a block that's not attached to a
2055 // function, we can't tell if it's "static" under the current definition.
2056 // Theoretically, this problem could be fixed by creating a new kind of
2057 // instruction kind specifically for static allocas. Such a new instruction
2058 // could be required to be at the top of the entry block, thus preventing it
2059 // from being subject to a @llvm.stackrestore. Instcombine could even
2060 // convert regular allocas into these special allocas. It'd be nifty.
2061 // However, until then, this problem remains open.
2062 //
2063 // So, we'll assume that two non-empty allocas have different addresses
2064 // for now.
2065 //
2066 // With all that, if the offsets are within the bounds of their allocations
2067 // (and not one-past-the-end! so we can't use inbounds!), and their
2068 // allocations aren't the same, the pointers are not equal.
2069 //
2070 // Note that it's not necessary to check for LHS being a global variable
2071 // address, due to canonicalization and constant folding.
2072 if (isa<AllocaInst>(LHS) &&
2073 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002074 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2075 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002076 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002077 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002078 getObjectSize(LHS, LHSSize, DL, TLI) &&
2079 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002080 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2081 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002082 if (!LHSOffsetValue.isNegative() &&
2083 !RHSOffsetValue.isNegative() &&
2084 LHSOffsetValue.ult(LHSSize) &&
2085 RHSOffsetValue.ult(RHSSize)) {
2086 return ConstantInt::get(GetCompareTy(LHS),
2087 !CmpInst::isTrueWhenEqual(Pred));
2088 }
2089 }
2090
2091 // Repeat the above check but this time without depending on DataLayout
2092 // or being able to compute a precise size.
2093 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2094 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2095 LHSOffset->isNullValue() &&
2096 RHSOffset->isNullValue())
2097 return ConstantInt::get(GetCompareTy(LHS),
2098 !CmpInst::isTrueWhenEqual(Pred));
2099 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002100
2101 // Even if an non-inbounds GEP occurs along the path we can still optimize
2102 // equality comparisons concerning the result. We avoid walking the whole
2103 // chain again by starting where the last calls to
2104 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002105 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2106 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002107 if (LHS == RHS)
2108 return ConstantExpr::getICmp(Pred,
2109 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2110 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002111
2112 // If one side of the equality comparison must come from a noalias call
2113 // (meaning a system memory allocation function), and the other side must
2114 // come from a pointer that cannot overlap with dynamically-allocated
2115 // memory within the lifetime of the current function (allocas, byval
2116 // arguments, globals), then determine the comparison result here.
2117 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2118 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2119 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2120
2121 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002122 auto IsNAC = [](ArrayRef<Value *> Objects) {
2123 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002124 };
2125
2126 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002127 // noalias calls. For allocas, we consider only static ones (dynamic
2128 // allocas might be transformed into calls to malloc not simultaneously
2129 // live with the compared-to allocation). For globals, we exclude symbols
2130 // that might be resolve lazily to symbols in another dynamically-loaded
2131 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002132 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2133 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002134 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2135 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2136 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2137 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002138 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002139 !GV->isThreadLocal();
2140 if (const Argument *A = dyn_cast<Argument>(V))
2141 return A->hasByValAttr();
2142 return false;
2143 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002144 };
2145
2146 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2147 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2148 return ConstantInt::get(GetCompareTy(LHS),
2149 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002150
2151 // Fold comparisons for non-escaping pointer even if the allocation call
2152 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2153 // dynamic allocation call could be either of the operands.
2154 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002155 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002156 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002157 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002158 MI = RHS;
2159 // FIXME: We should also fold the compare when the pointer escapes, but the
2160 // compare dominates the pointer escape
2161 if (MI && !PointerMayBeCaptured(MI, true, true))
2162 return ConstantInt::get(GetCompareTy(LHS),
2163 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002164 }
2165
2166 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002167 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002168}
Chris Lattner01990f02012-02-24 19:01:58 +00002169
Sanjay Pateldc65a272016-12-03 17:30:22 +00002170/// Fold an icmp when its operands have i1 scalar type.
2171static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2172 Value *RHS, const Query &Q) {
2173 Type *ITy = GetCompareTy(LHS); // The return type.
2174 Type *OpTy = LHS->getType(); // The operand type.
2175 if (!OpTy->getScalarType()->isIntegerTy(1))
2176 return nullptr;
2177
2178 switch (Pred) {
2179 default:
2180 break;
2181 case ICmpInst::ICMP_EQ:
2182 // X == 1 -> X
2183 if (match(RHS, m_One()))
2184 return LHS;
2185 break;
2186 case ICmpInst::ICMP_NE:
2187 // X != 0 -> X
2188 if (match(RHS, m_Zero()))
2189 return LHS;
2190 break;
2191 case ICmpInst::ICMP_UGT:
2192 // X >u 0 -> X
2193 if (match(RHS, m_Zero()))
2194 return LHS;
2195 break;
2196 case ICmpInst::ICMP_UGE:
2197 // X >=u 1 -> X
2198 if (match(RHS, m_One()))
2199 return LHS;
2200 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2201 return getTrue(ITy);
2202 break;
2203 case ICmpInst::ICMP_SGE:
2204 /// For signed comparison, the values for an i1 are 0 and -1
2205 /// respectively. This maps into a truth table of:
2206 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2207 /// 0 | 0 | 1 (0 >= 0) | 1
2208 /// 0 | 1 | 1 (0 >= -1) | 1
2209 /// 1 | 0 | 0 (-1 >= 0) | 0
2210 /// 1 | 1 | 1 (-1 >= -1) | 1
2211 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2212 return getTrue(ITy);
2213 break;
2214 case ICmpInst::ICMP_SLT:
2215 // X <s 0 -> X
2216 if (match(RHS, m_Zero()))
2217 return LHS;
2218 break;
2219 case ICmpInst::ICMP_SLE:
2220 // X <=s -1 -> X
2221 if (match(RHS, m_One()))
2222 return LHS;
2223 break;
2224 case ICmpInst::ICMP_ULE:
2225 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2226 return getTrue(ITy);
2227 break;
2228 }
2229
2230 return nullptr;
2231}
2232
2233/// Try hard to fold icmp with zero RHS because this is a common case.
2234static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2235 Value *RHS, const Query &Q) {
2236 if (!match(RHS, m_Zero()))
2237 return nullptr;
2238
2239 Type *ITy = GetCompareTy(LHS); // The return type.
2240 bool LHSKnownNonNegative, LHSKnownNegative;
2241 switch (Pred) {
2242 default:
2243 llvm_unreachable("Unknown ICmp predicate!");
2244 case ICmpInst::ICMP_ULT:
2245 return getFalse(ITy);
2246 case ICmpInst::ICMP_UGE:
2247 return getTrue(ITy);
2248 case ICmpInst::ICMP_EQ:
2249 case ICmpInst::ICMP_ULE:
2250 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2251 return getFalse(ITy);
2252 break;
2253 case ICmpInst::ICMP_NE:
2254 case ICmpInst::ICMP_UGT:
2255 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2256 return getTrue(ITy);
2257 break;
2258 case ICmpInst::ICMP_SLT:
2259 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2260 Q.CxtI, Q.DT);
2261 if (LHSKnownNegative)
2262 return getTrue(ITy);
2263 if (LHSKnownNonNegative)
2264 return getFalse(ITy);
2265 break;
2266 case ICmpInst::ICMP_SLE:
2267 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2268 Q.CxtI, Q.DT);
2269 if (LHSKnownNegative)
2270 return getTrue(ITy);
2271 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2272 return getFalse(ITy);
2273 break;
2274 case ICmpInst::ICMP_SGE:
2275 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2276 Q.CxtI, Q.DT);
2277 if (LHSKnownNegative)
2278 return getFalse(ITy);
2279 if (LHSKnownNonNegative)
2280 return getTrue(ITy);
2281 break;
2282 case ICmpInst::ICMP_SGT:
2283 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2284 Q.CxtI, Q.DT);
2285 if (LHSKnownNegative)
2286 return getFalse(ITy);
2287 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2288 return getTrue(ITy);
2289 break;
2290 }
2291
2292 return nullptr;
2293}
2294
Sanjay Patel67bde282016-08-22 23:12:02 +00002295static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2296 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002297 const APInt *C;
2298 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002299 return nullptr;
2300
2301 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002302 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002303 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002304 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002305 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002306 return ConstantInt::getTrue(GetCompareTy(RHS));
2307
Sanjay Patel67bde282016-08-22 23:12:02 +00002308 // Many binary operators with constant RHS have easy to compute constant
2309 // range. Use them to check whether the comparison is a tautology.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002310 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002311 APInt Lower = APInt(Width, 0);
2312 APInt Upper = APInt(Width, 0);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002313 const APInt *C2;
2314 if (match(LHS, m_URem(m_Value(), m_APInt(C2)))) {
2315 // 'urem x, C2' produces [0, C2).
2316 Upper = *C2;
2317 } else if (match(LHS, m_SRem(m_Value(), m_APInt(C2)))) {
2318 // 'srem x, C2' produces (-|C2|, |C2|).
2319 Upper = C2->abs();
Sanjay Patel67bde282016-08-22 23:12:02 +00002320 Lower = (-Upper) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002321 } else if (match(LHS, m_UDiv(m_APInt(C2), m_Value()))) {
2322 // 'udiv C2, x' produces [0, C2].
2323 Upper = *C2 + 1;
2324 } else if (match(LHS, m_UDiv(m_Value(), m_APInt(C2)))) {
2325 // 'udiv x, C2' produces [0, UINT_MAX / C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002326 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002327 if (*C2 != 0)
2328 Upper = NegOne.udiv(*C2) + 1;
2329 } else if (match(LHS, m_SDiv(m_APInt(C2), m_Value()))) {
2330 if (C2->isMinSignedValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002331 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002332 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002333 Upper = Lower.lshr(1) + 1;
2334 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002335 // 'sdiv C2, x' produces [-|C2|, |C2|].
2336 Upper = C2->abs() + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002337 Lower = (-Upper) + 1;
2338 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002339 } else if (match(LHS, m_SDiv(m_Value(), m_APInt(C2)))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002340 APInt IntMin = APInt::getSignedMinValue(Width);
2341 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002342 if (C2->isAllOnesValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002343 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002344 // where C2 != -1 and C2 != 0 and C2 != 1
Sanjay Patel67bde282016-08-22 23:12:02 +00002345 Lower = IntMin + 1;
2346 Upper = IntMax + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002347 } else if (C2->countLeadingZeros() < Width - 1) {
2348 // 'sdiv x, C2' produces [INT_MIN / C2, INT_MAX / C2]
2349 // where C2 != -1 and C2 != 0 and C2 != 1
2350 Lower = IntMin.sdiv(*C2);
2351 Upper = IntMax.sdiv(*C2);
Sanjay Patel67bde282016-08-22 23:12:02 +00002352 if (Lower.sgt(Upper))
2353 std::swap(Lower, Upper);
2354 Upper = Upper + 1;
2355 assert(Upper != Lower && "Upper part of range has wrapped!");
2356 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002357 } else if (match(LHS, m_NUWShl(m_APInt(C2), m_Value()))) {
2358 // 'shl nuw C2, x' produces [C2, C2 << CLZ(C2)]
2359 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002360 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002361 } else if (match(LHS, m_NSWShl(m_APInt(C2), m_Value()))) {
2362 if (C2->isNegative()) {
2363 // 'shl nsw C2, x' produces [C2 << CLO(C2)-1, C2]
2364 unsigned ShiftAmount = C2->countLeadingOnes() - 1;
2365 Lower = C2->shl(ShiftAmount);
2366 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002367 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002368 // 'shl nsw C2, x' produces [C2, C2 << CLZ(C2)-1]
2369 unsigned ShiftAmount = C2->countLeadingZeros() - 1;
2370 Lower = *C2;
2371 Upper = C2->shl(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002372 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002373 } else if (match(LHS, m_LShr(m_Value(), m_APInt(C2)))) {
2374 // 'lshr x, C2' produces [0, UINT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002375 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002376 if (C2->ult(Width))
2377 Upper = NegOne.lshr(*C2) + 1;
2378 } else if (match(LHS, m_LShr(m_APInt(C2), m_Value()))) {
2379 // 'lshr C2, x' produces [C2 >> (Width-1), C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002380 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002381 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2382 ShiftAmount = C2->countTrailingZeros();
2383 Lower = C2->lshr(ShiftAmount);
2384 Upper = *C2 + 1;
2385 } else if (match(LHS, m_AShr(m_Value(), m_APInt(C2)))) {
2386 // 'ashr x, C2' produces [INT_MIN >> C2, INT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002387 APInt IntMin = APInt::getSignedMinValue(Width);
2388 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002389 if (C2->ult(Width)) {
2390 Lower = IntMin.ashr(*C2);
2391 Upper = IntMax.ashr(*C2) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002392 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002393 } else if (match(LHS, m_AShr(m_APInt(C2), m_Value()))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002394 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002395 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2396 ShiftAmount = C2->countTrailingZeros();
2397 if (C2->isNegative()) {
2398 // 'ashr C2, x' produces [C2, C2 >> (Width-1)]
2399 Lower = *C2;
2400 Upper = C2->ashr(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002401 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002402 // 'ashr C2, x' produces [C2 >> (Width-1), C2]
2403 Lower = C2->ashr(ShiftAmount);
2404 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002405 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002406 } else if (match(LHS, m_Or(m_Value(), m_APInt(C2)))) {
2407 // 'or x, C2' produces [C2, UINT_MAX].
2408 Lower = *C2;
2409 } else if (match(LHS, m_And(m_Value(), m_APInt(C2)))) {
2410 // 'and x, C2' produces [0, C2].
2411 Upper = *C2 + 1;
2412 } else if (match(LHS, m_NUWAdd(m_Value(), m_APInt(C2)))) {
2413 // 'add nuw x, C2' produces [C2, UINT_MAX].
2414 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002415 }
2416
2417 ConstantRange LHS_CR =
2418 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2419
2420 if (auto *I = dyn_cast<Instruction>(LHS))
2421 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2422 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2423
2424 if (!LHS_CR.isFullSet()) {
2425 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002426 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002427 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002428 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002429 }
2430
2431 return nullptr;
2432}
2433
Sanjay Patel472cc782016-01-11 22:14:42 +00002434/// Given operands for an ICmpInst, see if we can fold the result.
2435/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002436static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002437 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00002438 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002439 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002440
Chris Lattnera71e9d62009-11-10 00:55:12 +00002441 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002442 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002443 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002444
2445 // If we have a constant, make sure it is on the RHS.
2446 std::swap(LHS, RHS);
2447 Pred = CmpInst::getSwappedPredicate(Pred);
2448 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002449
Chris Lattner229907c2011-07-18 04:54:35 +00002450 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002451
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002452 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002453 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2454 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002455 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002456 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002457
Sanjay Pateldc65a272016-12-03 17:30:22 +00002458 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
2459 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002460
Sanjay Pateldc65a272016-12-03 17:30:22 +00002461 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
2462 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00002463
Sanjay Patel67bde282016-08-22 23:12:02 +00002464 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
2465 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002466
Chen Li7452d952015-09-26 03:26:47 +00002467 // If both operands have range metadata, use the metadata
2468 // to simplify the comparison.
2469 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2470 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2471 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2472
2473 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2474 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002475 auto RHS_CR = getConstantRangeFromMetadata(
2476 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2477 auto LHS_CR = getConstantRangeFromMetadata(
2478 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00002479
2480 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2481 if (Satisfied_CR.contains(LHS_CR))
2482 return ConstantInt::getTrue(RHS->getContext());
2483
2484 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2485 CmpInst::getInversePredicate(Pred), RHS_CR);
2486 if (InversedSatisfied_CR.contains(LHS_CR))
2487 return ConstantInt::getFalse(RHS->getContext());
2488 }
2489 }
2490
Duncan Sands8fb2c382011-01-20 13:21:55 +00002491 // Compare of cast, for example (zext X) != 0 -> X != 0
2492 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2493 Instruction *LI = cast<CastInst>(LHS);
2494 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002495 Type *SrcTy = SrcOp->getType();
2496 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002497
2498 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2499 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002500 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2501 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002502 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2503 // Transfer the cast to the constant.
2504 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2505 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002506 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002507 return V;
2508 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2509 if (RI->getOperand(0)->getType() == SrcTy)
2510 // Compare without the cast.
2511 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002512 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002513 return V;
2514 }
2515 }
2516
2517 if (isa<ZExtInst>(LHS)) {
2518 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2519 // same type.
2520 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2521 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2522 // Compare X and Y. Note that signed predicates become unsigned.
2523 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002524 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002525 MaxRecurse-1))
2526 return V;
2527 }
2528 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2529 // too. If not, then try to deduce the result of the comparison.
2530 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2531 // Compute the constant that would happen if we truncated to SrcTy then
2532 // reextended to DstTy.
2533 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2534 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2535
2536 // If the re-extended constant didn't change then this is effectively
2537 // also a case of comparing two zero-extended values.
2538 if (RExt == CI && MaxRecurse)
2539 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002540 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002541 return V;
2542
2543 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2544 // there. Use this to work out the result of the comparison.
2545 if (RExt != CI) {
2546 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002547 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002548 // LHS <u RHS.
2549 case ICmpInst::ICMP_EQ:
2550 case ICmpInst::ICMP_UGT:
2551 case ICmpInst::ICMP_UGE:
2552 return ConstantInt::getFalse(CI->getContext());
2553
2554 case ICmpInst::ICMP_NE:
2555 case ICmpInst::ICMP_ULT:
2556 case ICmpInst::ICMP_ULE:
2557 return ConstantInt::getTrue(CI->getContext());
2558
2559 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2560 // is non-negative then LHS <s RHS.
2561 case ICmpInst::ICMP_SGT:
2562 case ICmpInst::ICMP_SGE:
2563 return CI->getValue().isNegative() ?
2564 ConstantInt::getTrue(CI->getContext()) :
2565 ConstantInt::getFalse(CI->getContext());
2566
2567 case ICmpInst::ICMP_SLT:
2568 case ICmpInst::ICMP_SLE:
2569 return CI->getValue().isNegative() ?
2570 ConstantInt::getFalse(CI->getContext()) :
2571 ConstantInt::getTrue(CI->getContext());
2572 }
2573 }
2574 }
2575 }
2576
2577 if (isa<SExtInst>(LHS)) {
2578 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2579 // same type.
2580 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2581 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2582 // Compare X and Y. Note that the predicate does not change.
2583 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002584 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002585 return V;
2586 }
2587 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2588 // too. If not, then try to deduce the result of the comparison.
2589 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2590 // Compute the constant that would happen if we truncated to SrcTy then
2591 // reextended to DstTy.
2592 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2593 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2594
2595 // If the re-extended constant didn't change then this is effectively
2596 // also a case of comparing two sign-extended values.
2597 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002598 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002599 return V;
2600
2601 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2602 // bits there. Use this to work out the result of the comparison.
2603 if (RExt != CI) {
2604 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002605 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002606 case ICmpInst::ICMP_EQ:
2607 return ConstantInt::getFalse(CI->getContext());
2608 case ICmpInst::ICMP_NE:
2609 return ConstantInt::getTrue(CI->getContext());
2610
2611 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2612 // LHS >s RHS.
2613 case ICmpInst::ICMP_SGT:
2614 case ICmpInst::ICMP_SGE:
2615 return CI->getValue().isNegative() ?
2616 ConstantInt::getTrue(CI->getContext()) :
2617 ConstantInt::getFalse(CI->getContext());
2618 case ICmpInst::ICMP_SLT:
2619 case ICmpInst::ICMP_SLE:
2620 return CI->getValue().isNegative() ?
2621 ConstantInt::getFalse(CI->getContext()) :
2622 ConstantInt::getTrue(CI->getContext());
2623
2624 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2625 // LHS >u RHS.
2626 case ICmpInst::ICMP_UGT:
2627 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002628 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002629 if (MaxRecurse)
2630 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2631 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002632 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002633 return V;
2634 break;
2635 case ICmpInst::ICMP_ULT:
2636 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002637 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002638 if (MaxRecurse)
2639 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2640 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002641 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002642 return V;
2643 break;
2644 }
2645 }
2646 }
2647 }
2648 }
2649
James Molloy1d88d6f2015-10-22 13:18:42 +00002650 // icmp eq|ne X, Y -> false|true if X != Y
2651 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2652 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2653 LLVMContext &Ctx = LHS->getType()->getContext();
2654 return Pred == ICmpInst::ICMP_NE ?
2655 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2656 }
Junmo Park53470fc2016-04-05 21:14:31 +00002657
Duncan Sandsd114ab32011-02-13 17:15:40 +00002658 // Special logic for binary operators.
2659 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2660 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2661 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002662 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002663 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002664 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2665 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2666 if (LBO && LBO->getOpcode() == Instruction::Add) {
2667 A = LBO->getOperand(0); B = LBO->getOperand(1);
2668 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2669 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2670 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2671 }
2672 if (RBO && RBO->getOpcode() == Instruction::Add) {
2673 C = RBO->getOperand(0); D = RBO->getOperand(1);
2674 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2675 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2676 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2677 }
2678
2679 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2680 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2681 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2682 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002683 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002684 return V;
2685
2686 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2687 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2688 if (Value *V = SimplifyICmpInst(Pred,
2689 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002690 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002691 return V;
2692
2693 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2694 if (A && C && (A == C || A == D || B == C || B == D) &&
2695 NoLHSWrapProblem && NoRHSWrapProblem) {
2696 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002697 Value *Y, *Z;
2698 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002699 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002700 Y = B;
2701 Z = D;
2702 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002703 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002704 Y = B;
2705 Z = C;
2706 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002707 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002708 Y = A;
2709 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002710 } else {
2711 assert(B == D);
2712 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002713 Y = A;
2714 Z = C;
2715 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002716 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002717 return V;
2718 }
2719 }
2720
Nick Lewycky762f8a82016-04-21 00:53:14 +00002721 {
2722 Value *Y = nullptr;
2723 // icmp pred (or X, Y), X
2724 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2725 if (Pred == ICmpInst::ICMP_ULT)
2726 return getFalse(ITy);
2727 if (Pred == ICmpInst::ICMP_UGE)
2728 return getTrue(ITy);
2729
2730 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2731 bool RHSKnownNonNegative, RHSKnownNegative;
2732 bool YKnownNonNegative, YKnownNegative;
2733 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2734 Q.AC, Q.CxtI, Q.DT);
2735 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2736 Q.CxtI, Q.DT);
2737 if (RHSKnownNonNegative && YKnownNegative)
2738 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2739 if (RHSKnownNegative || YKnownNonNegative)
2740 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2741 }
2742 }
2743 // icmp pred X, (or X, Y)
2744 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2745 if (Pred == ICmpInst::ICMP_ULE)
2746 return getTrue(ITy);
2747 if (Pred == ICmpInst::ICMP_UGT)
2748 return getFalse(ITy);
2749
2750 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2751 bool LHSKnownNonNegative, LHSKnownNegative;
2752 bool YKnownNonNegative, YKnownNegative;
2753 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2754 Q.AC, Q.CxtI, Q.DT);
2755 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2756 Q.CxtI, Q.DT);
2757 if (LHSKnownNonNegative && YKnownNegative)
2758 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2759 if (LHSKnownNegative || YKnownNonNegative)
2760 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2761 }
2762 }
David Majnemerbd9ce4e2014-11-25 02:55:48 +00002763 }
2764
2765 // icmp pred (and X, Y), X
2766 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2767 m_And(m_Specific(RHS), m_Value())))) {
2768 if (Pred == ICmpInst::ICMP_UGT)
2769 return getFalse(ITy);
2770 if (Pred == ICmpInst::ICMP_ULE)
2771 return getTrue(ITy);
2772 }
2773 // icmp pred X, (and X, Y)
2774 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2775 m_And(m_Specific(LHS), m_Value())))) {
2776 if (Pred == ICmpInst::ICMP_UGE)
2777 return getTrue(ITy);
2778 if (Pred == ICmpInst::ICMP_ULT)
2779 return getFalse(ITy);
2780 }
2781
David Majnemer2d6c0232014-05-14 20:16:28 +00002782 // 0 - (zext X) pred C
2783 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2784 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2785 if (RHSC->getValue().isStrictlyPositive()) {
2786 if (Pred == ICmpInst::ICMP_SLT)
2787 return ConstantInt::getTrue(RHSC->getContext());
2788 if (Pred == ICmpInst::ICMP_SGE)
2789 return ConstantInt::getFalse(RHSC->getContext());
2790 if (Pred == ICmpInst::ICMP_EQ)
2791 return ConstantInt::getFalse(RHSC->getContext());
2792 if (Pred == ICmpInst::ICMP_NE)
2793 return ConstantInt::getTrue(RHSC->getContext());
2794 }
2795 if (RHSC->getValue().isNonNegative()) {
2796 if (Pred == ICmpInst::ICMP_SLE)
2797 return ConstantInt::getTrue(RHSC->getContext());
2798 if (Pred == ICmpInst::ICMP_SGT)
2799 return ConstantInt::getFalse(RHSC->getContext());
2800 }
2801 }
2802 }
2803
Nick Lewycky35aeea92013-07-12 23:42:57 +00002804 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002805 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002806 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002807 switch (Pred) {
2808 default:
2809 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002810 case ICmpInst::ICMP_SGT:
2811 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002812 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2813 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002814 if (!KnownNonNegative)
2815 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002816 LLVM_FALLTHROUGH;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002817 case ICmpInst::ICMP_EQ:
2818 case ICmpInst::ICMP_UGT:
2819 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002820 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002821 case ICmpInst::ICMP_SLT:
2822 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002823 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2824 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002825 if (!KnownNonNegative)
2826 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002827 LLVM_FALLTHROUGH;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002828 case ICmpInst::ICMP_NE:
2829 case ICmpInst::ICMP_ULT:
2830 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002831 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002832 }
2833 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002834
2835 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002836 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2837 bool KnownNonNegative, KnownNegative;
2838 switch (Pred) {
2839 default:
2840 break;
2841 case ICmpInst::ICMP_SGT:
2842 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002843 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2844 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002845 if (!KnownNonNegative)
2846 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002847 LLVM_FALLTHROUGH;
Nick Lewycky774647d2011-03-09 08:20:06 +00002848 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002849 case ICmpInst::ICMP_UGT:
2850 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002851 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002852 case ICmpInst::ICMP_SLT:
2853 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002854 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2855 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002856 if (!KnownNonNegative)
2857 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002858 LLVM_FALLTHROUGH;
Nick Lewycky774647d2011-03-09 08:20:06 +00002859 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002860 case ICmpInst::ICMP_ULT:
2861 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002862 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002863 }
2864 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002865
David Majnemer3af5bf32016-01-21 18:55:54 +00002866 // x >> y <=u x
Duncan Sands92af0a82011-10-28 18:17:44 +00002867 // x udiv y <=u x.
David Majnemer3af5bf32016-01-21 18:55:54 +00002868 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2869 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2870 // icmp pred (X op Y), X
Duncan Sands92af0a82011-10-28 18:17:44 +00002871 if (Pred == ICmpInst::ICMP_UGT)
2872 return getFalse(ITy);
2873 if (Pred == ICmpInst::ICMP_ULE)
2874 return getTrue(ITy);
2875 }
2876
Sanjoy Das01969212016-10-26 19:18:43 +00002877 // x >=u x >> y
2878 // x >=u x udiv y.
2879 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2880 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2881 // icmp pred X, (X op Y)
2882 if (Pred == ICmpInst::ICMP_ULT)
2883 return getFalse(ITy);
2884 if (Pred == ICmpInst::ICMP_UGE)
2885 return getTrue(ITy);
2886 }
2887
David Majnemer76d06bc2014-08-28 03:34:28 +00002888 // handle:
2889 // CI2 << X == CI
2890 // CI2 << X != CI
2891 //
2892 // where CI2 is a power of 2 and CI isn't
2893 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2894 const APInt *CI2Val, *CIVal = &CI->getValue();
2895 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2896 CI2Val->isPowerOf2()) {
2897 if (!CIVal->isPowerOf2()) {
2898 // CI2 << X can equal zero in some circumstances,
2899 // this simplification is unsafe if CI is zero.
2900 //
2901 // We know it is safe if:
2902 // - The shift is nsw, we can't shift out the one bit.
2903 // - The shift is nuw, we can't shift out the one bit.
2904 // - CI2 is one
2905 // - CI isn't zero
2906 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2907 *CI2Val == 1 || !CI->isZero()) {
2908 if (Pred == ICmpInst::ICMP_EQ)
2909 return ConstantInt::getFalse(RHS->getContext());
2910 if (Pred == ICmpInst::ICMP_NE)
2911 return ConstantInt::getTrue(RHS->getContext());
2912 }
2913 }
2914 if (CIVal->isSignBit() && *CI2Val == 1) {
2915 if (Pred == ICmpInst::ICMP_UGT)
2916 return ConstantInt::getFalse(RHS->getContext());
2917 if (Pred == ICmpInst::ICMP_ULE)
2918 return ConstantInt::getTrue(RHS->getContext());
2919 }
2920 }
2921 }
2922
Nick Lewycky9719a712011-03-05 05:19:11 +00002923 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2924 LBO->getOperand(1) == RBO->getOperand(1)) {
2925 switch (LBO->getOpcode()) {
2926 default: break;
2927 case Instruction::UDiv:
2928 case Instruction::LShr:
2929 if (ICmpInst::isSigned(Pred))
2930 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002931 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00002932 case Instruction::SDiv:
2933 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002934 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002935 break;
2936 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002937 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002938 return V;
2939 break;
2940 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002941 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002942 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2943 if (!NUW && !NSW)
2944 break;
2945 if (!NSW && ICmpInst::isSigned(Pred))
2946 break;
2947 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002948 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002949 return V;
2950 break;
2951 }
2952 }
2953 }
2954
Duncan Sands0a9c1242011-05-03 19:53:10 +00002955 // Simplify comparisons involving max/min.
2956 Value *A, *B;
2957 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002958 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002959
Duncan Sandsa2287852011-05-04 16:05:05 +00002960 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002961 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2962 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002963 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002964 // We analyze this as smax(A, B) pred A.
2965 P = Pred;
2966 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2967 (A == LHS || B == LHS)) {
2968 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002969 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002970 // We analyze this as smax(A, B) swapped-pred A.
2971 P = CmpInst::getSwappedPredicate(Pred);
2972 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2973 (A == RHS || B == RHS)) {
2974 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002975 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002976 // We analyze this as smax(-A, -B) swapped-pred -A.
2977 // Note that we do not need to actually form -A or -B thanks to EqP.
2978 P = CmpInst::getSwappedPredicate(Pred);
2979 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2980 (A == LHS || B == LHS)) {
2981 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002982 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002983 // We analyze this as smax(-A, -B) pred -A.
2984 // Note that we do not need to actually form -A or -B thanks to EqP.
2985 P = Pred;
2986 }
2987 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2988 // Cases correspond to "max(A, B) p A".
2989 switch (P) {
2990 default:
2991 break;
2992 case CmpInst::ICMP_EQ:
2993 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002994 // Equivalent to "A EqP B". This may be the same as the condition tested
2995 // in the max/min; if so, we can just return that.
2996 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2997 return V;
2998 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2999 return V;
3000 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003001 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003002 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003003 return V;
3004 break;
3005 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003006 case CmpInst::ICMP_SGT: {
3007 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3008 // Equivalent to "A InvEqP B". This may be the same as the condition
3009 // tested in the max/min; if so, we can just return that.
3010 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3011 return V;
3012 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3013 return V;
3014 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003015 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003016 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003017 return V;
3018 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003019 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003020 case CmpInst::ICMP_SGE:
3021 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003022 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003023 case CmpInst::ICMP_SLT:
3024 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003025 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003026 }
3027 }
3028
Duncan Sandsa2287852011-05-04 16:05:05 +00003029 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003030 P = CmpInst::BAD_ICMP_PREDICATE;
3031 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3032 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003033 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003034 // We analyze this as umax(A, B) pred A.
3035 P = Pred;
3036 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3037 (A == LHS || B == LHS)) {
3038 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003039 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003040 // We analyze this as umax(A, B) swapped-pred A.
3041 P = CmpInst::getSwappedPredicate(Pred);
3042 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3043 (A == RHS || B == RHS)) {
3044 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003045 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003046 // We analyze this as umax(-A, -B) swapped-pred -A.
3047 // Note that we do not need to actually form -A or -B thanks to EqP.
3048 P = CmpInst::getSwappedPredicate(Pred);
3049 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3050 (A == LHS || B == LHS)) {
3051 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003052 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003053 // We analyze this as umax(-A, -B) pred -A.
3054 // Note that we do not need to actually form -A or -B thanks to EqP.
3055 P = Pred;
3056 }
3057 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3058 // Cases correspond to "max(A, B) p A".
3059 switch (P) {
3060 default:
3061 break;
3062 case CmpInst::ICMP_EQ:
3063 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003064 // Equivalent to "A EqP B". This may be the same as the condition tested
3065 // in the max/min; if so, we can just return that.
3066 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3067 return V;
3068 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3069 return V;
3070 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003071 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003072 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003073 return V;
3074 break;
3075 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003076 case CmpInst::ICMP_UGT: {
3077 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3078 // Equivalent to "A InvEqP B". This may be the same as the condition
3079 // tested in the max/min; if so, we can just return that.
3080 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3081 return V;
3082 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3083 return V;
3084 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003085 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003086 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003087 return V;
3088 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003089 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003090 case CmpInst::ICMP_UGE:
3091 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003092 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003093 case CmpInst::ICMP_ULT:
3094 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003095 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003096 }
3097 }
3098
Duncan Sandsa2287852011-05-04 16:05:05 +00003099 // Variants on "max(x,y) >= min(x,z)".
3100 Value *C, *D;
3101 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3102 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3103 (A == C || A == D || B == C || B == D)) {
3104 // max(x, ?) pred min(x, ?).
3105 if (Pred == CmpInst::ICMP_SGE)
3106 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003107 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003108 if (Pred == CmpInst::ICMP_SLT)
3109 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003110 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003111 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3112 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3113 (A == C || A == D || B == C || B == D)) {
3114 // min(x, ?) pred max(x, ?).
3115 if (Pred == CmpInst::ICMP_SLE)
3116 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003117 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003118 if (Pred == CmpInst::ICMP_SGT)
3119 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003120 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003121 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3122 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3123 (A == C || A == D || B == C || B == D)) {
3124 // max(x, ?) pred min(x, ?).
3125 if (Pred == CmpInst::ICMP_UGE)
3126 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003127 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003128 if (Pred == CmpInst::ICMP_ULT)
3129 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003130 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003131 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3132 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3133 (A == C || A == D || B == C || B == D)) {
3134 // min(x, ?) pred max(x, ?).
3135 if (Pred == CmpInst::ICMP_ULE)
3136 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003137 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003138 if (Pred == CmpInst::ICMP_UGT)
3139 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003140 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003141 }
3142
Chandler Carruth8059c842012-03-25 21:28:14 +00003143 // Simplify comparisons of related pointers using a powerful, recursive
3144 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003145 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003146 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003147 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003148 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3149 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3150 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3151 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3152 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3153 Q.DL.getTypeSizeInBits(CRHS->getType()))
3154 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3155 CLHS->getPointerOperand(),
3156 CRHS->getPointerOperand()))
3157 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003158
Nick Lewycky3db143e2012-02-26 02:09:49 +00003159 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3160 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3161 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3162 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3163 (ICmpInst::isEquality(Pred) ||
3164 (GLHS->isInBounds() && GRHS->isInBounds() &&
3165 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3166 // The bases are equal and the indices are constant. Build a constant
3167 // expression GEP with the same indices and a null base pointer to see
3168 // what constant folding can make out of it.
3169 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3170 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003171 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3172 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003173
3174 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003175 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3176 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003177 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3178 }
3179 }
3180 }
3181
David Majnemer5854e9f2014-11-16 02:20:08 +00003182 // If a bit is known to be zero for A and known to be one for B,
3183 // then A and B cannot be equal.
3184 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003185 const APInt *RHSVal;
3186 if (match(RHS, m_APInt(RHSVal))) {
3187 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003188 APInt LHSKnownZero(BitWidth, 0);
3189 APInt LHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003190 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003191 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003192 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3193 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3194 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003195 }
3196 }
3197
Duncan Sandsf532d312010-11-07 16:12:23 +00003198 // If the comparison is with the result of a select instruction, check whether
3199 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003200 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003201 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003202 return V;
3203
3204 // If the comparison is with the result of a phi instruction, check whether
3205 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003206 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003207 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003208 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003209
Craig Topper9f008862014-04-15 04:59:12 +00003210 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003211}
3212
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003213Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003214 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003215 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003216 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003217 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003218 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003219 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003220}
3221
Sanjay Patel472cc782016-01-11 22:14:42 +00003222/// Given operands for an FCmpInst, see if we can fold the result.
3223/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003224static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003225 FastMathFlags FMF, const Query &Q,
3226 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003227 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3228 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3229
Chris Lattnera71e9d62009-11-10 00:55:12 +00003230 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003231 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003232 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003233
Chris Lattnera71e9d62009-11-10 00:55:12 +00003234 // If we have a constant, make sure it is on the RHS.
3235 std::swap(LHS, RHS);
3236 Pred = CmpInst::getSwappedPredicate(Pred);
3237 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003238
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003239 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003240 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003241 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003242 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003243 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003244 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003245
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003246 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3247 if (FMF.noNaNs()) {
3248 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003249 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003250 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003251 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003252 }
3253
Mehdi Aminieb242a52015-03-09 03:20:25 +00003254 // fcmp pred x, undef and fcmp pred undef, x
3255 // fold to true if unordered, false if ordered
3256 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3257 // Choosing NaN for the undef will always make unordered comparison succeed
3258 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003259 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003260 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003261
3262 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003263 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003264 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003265 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003266 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003267 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003268 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003269
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003270 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003271 const ConstantFP *CFP = nullptr;
3272 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3273 if (RHS->getType()->isVectorTy())
3274 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3275 else
3276 CFP = dyn_cast<ConstantFP>(RHSC);
3277 }
3278 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003279 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003280 if (CFP->getValueAPF().isNaN()) {
3281 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003282 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003283 assert(FCmpInst::isUnordered(Pred) &&
3284 "Comparison must be either ordered or unordered!");
3285 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003286 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003287 }
3288 // Check whether the constant is an infinity.
3289 if (CFP->getValueAPF().isInfinity()) {
3290 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003291 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003292 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003293 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003294 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003295 case FCmpInst::FCMP_UGE:
3296 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003297 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003298 default:
3299 break;
3300 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003301 } else {
3302 switch (Pred) {
3303 case FCmpInst::FCMP_OGT:
3304 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003305 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003306 case FCmpInst::FCMP_ULE:
3307 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003308 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003309 default:
3310 break;
3311 }
3312 }
3313 }
3314 if (CFP->getValueAPF().isZero()) {
3315 switch (Pred) {
3316 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003317 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003318 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003319 break;
3320 case FCmpInst::FCMP_OLT:
3321 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003322 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003323 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003324 break;
3325 default:
3326 break;
3327 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003328 }
3329 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003330
Duncan Sandsa620bd12010-11-07 16:46:25 +00003331 // If the comparison is with the result of a select instruction, check whether
3332 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003333 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003334 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003335 return V;
3336
3337 // If the comparison is with the result of a phi instruction, check whether
3338 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003339 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003340 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003341 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003342
Craig Topper9f008862014-04-15 04:59:12 +00003343 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003344}
3345
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003346Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003347 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003348 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003349 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003350 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003351 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3352 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003353}
3354
Sanjay Patel472cc782016-01-11 22:14:42 +00003355/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003356static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3357 const Query &Q,
3358 unsigned MaxRecurse) {
3359 // Trivial replacement.
3360 if (V == Op)
3361 return RepOp;
3362
3363 auto *I = dyn_cast<Instruction>(V);
3364 if (!I)
3365 return nullptr;
3366
3367 // If this is a binary operator, try to simplify it with the replaced op.
3368 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3369 // Consider:
3370 // %cmp = icmp eq i32 %x, 2147483647
3371 // %add = add nsw i32 %x, 1
3372 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3373 //
3374 // We can't replace %sel with %add unless we strip away the flags.
3375 if (isa<OverflowingBinaryOperator>(B))
3376 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3377 return nullptr;
3378 if (isa<PossiblyExactOperator>(B))
3379 if (B->isExact())
3380 return nullptr;
3381
3382 if (MaxRecurse) {
3383 if (B->getOperand(0) == Op)
3384 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3385 MaxRecurse - 1);
3386 if (B->getOperand(1) == Op)
3387 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3388 MaxRecurse - 1);
3389 }
3390 }
3391
3392 // Same for CmpInsts.
3393 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3394 if (MaxRecurse) {
3395 if (C->getOperand(0) == Op)
3396 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3397 MaxRecurse - 1);
3398 if (C->getOperand(1) == Op)
3399 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3400 MaxRecurse - 1);
3401 }
3402 }
3403
3404 // TODO: We could hand off more cases to instsimplify here.
3405
3406 // If all operands are constant after substituting Op for RepOp then we can
3407 // constant fold the instruction.
3408 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3409 // Build a list of all constant operands.
3410 SmallVector<Constant *, 8> ConstOps;
3411 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3412 if (I->getOperand(i) == Op)
3413 ConstOps.push_back(CRepOp);
3414 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3415 ConstOps.push_back(COp);
3416 else
3417 break;
3418 }
3419
3420 // All operands were constants, fold it.
3421 if (ConstOps.size() == I->getNumOperands()) {
3422 if (CmpInst *C = dyn_cast<CmpInst>(I))
3423 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3424 ConstOps[1], Q.DL, Q.TLI);
3425
3426 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3427 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003428 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003429
Manuel Jacobe9024592016-01-21 06:33:22 +00003430 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003431 }
3432 }
3433
3434 return nullptr;
3435}
3436
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003437/// Try to simplify a select instruction when its condition operand is an
3438/// integer comparison where one operand of the compare is a constant.
3439static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3440 const APInt *Y, bool TrueWhenUnset) {
3441 const APInt *C;
3442
3443 // (X & Y) == 0 ? X & ~Y : X --> X
3444 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3445 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3446 *Y == ~*C)
3447 return TrueWhenUnset ? FalseVal : TrueVal;
3448
3449 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3450 // (X & Y) != 0 ? X : X & ~Y --> X
3451 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3452 *Y == ~*C)
3453 return TrueWhenUnset ? FalseVal : TrueVal;
3454
3455 if (Y->isPowerOf2()) {
3456 // (X & Y) == 0 ? X | Y : X --> X | Y
3457 // (X & Y) != 0 ? X | Y : X --> X
3458 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3459 *Y == *C)
3460 return TrueWhenUnset ? TrueVal : FalseVal;
3461
3462 // (X & Y) == 0 ? X : X | Y --> X
3463 // (X & Y) != 0 ? X : X | Y --> X | Y
3464 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3465 *Y == *C)
3466 return TrueWhenUnset ? TrueVal : FalseVal;
3467 }
3468
3469 return nullptr;
3470}
3471
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003472/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3473/// eq/ne.
3474static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3475 Value *FalseVal,
3476 bool TrueWhenUnset) {
3477 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003478 if (!BitWidth)
3479 return nullptr;
3480
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003481 APInt MinSignedValue;
3482 Value *X;
3483 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3484 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3485 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3486 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3487 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3488 } else {
3489 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3490 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3491 X = CmpLHS;
3492 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3493 }
3494
3495 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3496 TrueWhenUnset))
3497 return V;
3498
3499 return nullptr;
3500}
3501
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003502/// Try to simplify a select instruction when its condition operand is an
3503/// integer comparison.
3504static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3505 Value *FalseVal, const Query &Q,
3506 unsigned MaxRecurse) {
3507 ICmpInst::Predicate Pred;
3508 Value *CmpLHS, *CmpRHS;
3509 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3510 return nullptr;
3511
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003512 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3513 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003514 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3515 Value *X;
3516 const APInt *Y;
3517 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3518 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3519 Pred == ICmpInst::ICMP_EQ))
3520 return V;
3521 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003522 // Comparing signed-less-than 0 checks if the sign bit is set.
3523 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3524 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003525 return V;
3526 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003527 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3528 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3529 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003530 return V;
3531 }
3532
3533 if (CondVal->hasOneUse()) {
3534 const APInt *C;
3535 if (match(CmpRHS, m_APInt(C))) {
3536 // X < MIN ? T : F --> F
3537 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3538 return FalseVal;
3539 // X < MIN ? T : F --> F
3540 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3541 return FalseVal;
3542 // X > MAX ? T : F --> F
3543 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3544 return FalseVal;
3545 // X > MAX ? T : F --> F
3546 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3547 return FalseVal;
3548 }
3549 }
3550
3551 // If we have an equality comparison, then we know the value in one of the
3552 // arms of the select. See if substituting this value into the arm and
3553 // simplifying the result yields the same value as the other arm.
3554 if (Pred == ICmpInst::ICMP_EQ) {
3555 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3556 TrueVal ||
3557 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3558 TrueVal)
3559 return FalseVal;
3560 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3561 FalseVal ||
3562 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3563 FalseVal)
3564 return FalseVal;
3565 } else if (Pred == ICmpInst::ICMP_NE) {
3566 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3567 FalseVal ||
3568 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3569 FalseVal)
3570 return TrueVal;
3571 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3572 TrueVal ||
3573 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3574 TrueVal)
3575 return TrueVal;
3576 }
3577
3578 return nullptr;
3579}
3580
Sanjay Patel472cc782016-01-11 22:14:42 +00003581/// Given operands for a SelectInst, see if we can fold the result.
3582/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003583static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3584 Value *FalseVal, const Query &Q,
3585 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003586 // select true, X, Y -> X
3587 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003588 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3589 if (CB->isAllOnesValue())
3590 return TrueVal;
3591 if (CB->isNullValue())
3592 return FalseVal;
3593 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003594
Chris Lattnerc707fa92010-04-20 05:32:14 +00003595 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003596 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003597 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003598
Chris Lattnerc707fa92010-04-20 05:32:14 +00003599 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3600 if (isa<Constant>(TrueVal))
3601 return TrueVal;
3602 return FalseVal;
3603 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003604 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3605 return FalseVal;
3606 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3607 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003608
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003609 if (Value *V =
3610 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3611 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003612
Craig Topper9f008862014-04-15 04:59:12 +00003613 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003614}
3615
Duncan Sandsb8cee002012-03-13 11:42:19 +00003616Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003617 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003618 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003619 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003620 const Instruction *CxtI) {
3621 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Chandler Carruth66b31302015-01-04 12:03:27 +00003622 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003623}
3624
Sanjay Patel472cc782016-01-11 22:14:42 +00003625/// Given operands for an GetElementPtrInst, see if we can fold the result.
3626/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003627static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3628 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003629 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003630 unsigned AS =
3631 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003632
Chris Lattner8574aba2009-11-27 00:29:05 +00003633 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003634 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003635 return Ops[0];
3636
Nico Weber48c82402014-08-27 20:06:19 +00003637 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003638 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003639 Type *GEPTy = PointerType::get(LastType, AS);
3640 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3641 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3642
3643 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003644 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003645
Jay Foadb992a632011-07-19 15:07:52 +00003646 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003647 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003648 if (match(Ops[1], m_Zero()))
3649 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003650
David Blaikie4a2e73b2015-04-02 18:55:32 +00003651 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003652 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003653 Value *P;
3654 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003655 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003656 // getelementptr P, N -> P if P points to a type of zero size.
3657 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003658 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003659
3660 // The following transforms are only safe if the ptrtoint cast
3661 // doesn't truncate the pointers.
3662 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003663 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003664 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3665 if (match(P, m_Zero()))
3666 return Constant::getNullValue(GEPTy);
3667 Value *Temp;
3668 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003669 if (Temp->getType() == GEPTy)
3670 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003671 return nullptr;
3672 };
3673
3674 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3675 if (TyAllocSize == 1 &&
3676 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3677 if (Value *R = PtrToIntOrZero(P))
3678 return R;
3679
3680 // getelementptr V, (ashr (sub P, V), C) -> Q
3681 // if P points to a type of size 1 << C.
3682 if (match(Ops[1],
3683 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3684 m_ConstantInt(C))) &&
3685 TyAllocSize == 1ULL << C)
3686 if (Value *R = PtrToIntOrZero(P))
3687 return R;
3688
3689 // getelementptr V, (sdiv (sub P, V), C) -> Q
3690 // if P points to a type of size C.
3691 if (match(Ops[1],
3692 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3693 m_SpecificInt(TyAllocSize))))
3694 if (Value *R = PtrToIntOrZero(P))
3695 return R;
3696 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003697 }
3698 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003699
David Majnemerd1501372016-08-07 07:58:12 +00003700 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3701 all_of(Ops.slice(1).drop_back(1),
3702 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3703 unsigned PtrWidth =
3704 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3705 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3706 APInt BasePtrOffset(PtrWidth, 0);
3707 Value *StrippedBasePtr =
3708 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3709 BasePtrOffset);
3710
David Majnemer5c5df622016-08-16 06:13:46 +00003711 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003712 if (match(Ops.back(),
3713 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3714 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3715 return ConstantExpr::getIntToPtr(CI, GEPTy);
3716 }
David Majnemer5c5df622016-08-16 06:13:46 +00003717 // gep (gep V, C), (xor V, -1) -> C-1
3718 if (match(Ops.back(),
3719 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3720 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3721 return ConstantExpr::getIntToPtr(CI, GEPTy);
3722 }
David Majnemerd1501372016-08-07 07:58:12 +00003723 }
3724 }
3725
Chris Lattner8574aba2009-11-27 00:29:05 +00003726 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003727 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003728 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003729 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003730
David Blaikie4a2e73b2015-04-02 18:55:32 +00003731 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3732 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003733}
3734
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003735Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3736 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003737 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003738 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003739 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003740 return ::SimplifyGEPInst(SrcTy, Ops,
3741 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003742}
3743
Sanjay Patel472cc782016-01-11 22:14:42 +00003744/// Given operands for an InsertValueInst, see if we can fold the result.
3745/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003746static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3747 ArrayRef<unsigned> Idxs, const Query &Q,
3748 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003749 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3750 if (Constant *CVal = dyn_cast<Constant>(Val))
3751 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3752
3753 // insertvalue x, undef, n -> x
3754 if (match(Val, m_Undef()))
3755 return Agg;
3756
3757 // insertvalue x, (extractvalue y, n), n
3758 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003759 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3760 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003761 // insertvalue undef, (extractvalue y, n), n -> y
3762 if (match(Agg, m_Undef()))
3763 return EV->getAggregateOperand();
3764
3765 // insertvalue y, (extractvalue y, n), n -> y
3766 if (Agg == EV->getAggregateOperand())
3767 return Agg;
3768 }
3769
Craig Topper9f008862014-04-15 04:59:12 +00003770 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003771}
3772
Chandler Carruth66b31302015-01-04 12:03:27 +00003773Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003774 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003775 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3776 const Instruction *CxtI) {
3777 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003778 RecursionLimit);
3779}
3780
Sanjay Patel472cc782016-01-11 22:14:42 +00003781/// Given operands for an ExtractValueInst, see if we can fold the result.
3782/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003783static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3784 const Query &, unsigned) {
3785 if (auto *CAgg = dyn_cast<Constant>(Agg))
3786 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3787
3788 // extractvalue x, (insertvalue y, elt, n), n -> elt
3789 unsigned NumIdxs = Idxs.size();
3790 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3791 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3792 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3793 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3794 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3795 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3796 Idxs.slice(0, NumCommonIdxs)) {
3797 if (NumIdxs == NumInsertValueIdxs)
3798 return IVI->getInsertedValueOperand();
3799 break;
3800 }
3801 }
3802
3803 return nullptr;
3804}
3805
3806Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3807 const DataLayout &DL,
3808 const TargetLibraryInfo *TLI,
3809 const DominatorTree *DT,
3810 AssumptionCache *AC,
3811 const Instruction *CxtI) {
3812 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3813 RecursionLimit);
3814}
3815
Sanjay Patel472cc782016-01-11 22:14:42 +00003816/// Given operands for an ExtractElementInst, see if we can fold the result.
3817/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003818static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3819 unsigned) {
3820 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3821 if (auto *CIdx = dyn_cast<Constant>(Idx))
3822 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3823
3824 // The index is not relevant if our vector is a splat.
3825 if (auto *Splat = CVec->getSplatValue())
3826 return Splat;
3827
3828 if (isa<UndefValue>(Vec))
3829 return UndefValue::get(Vec->getType()->getVectorElementType());
3830 }
3831
3832 // If extracting a specified index from the vector, see if we can recursively
3833 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003834 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3835 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003836 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003837
3838 return nullptr;
3839}
3840
3841Value *llvm::SimplifyExtractElementInst(
3842 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3843 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3844 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3845 RecursionLimit);
3846}
3847
Sanjay Patel472cc782016-01-11 22:14:42 +00003848/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003849static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003850 // If all of the PHI's incoming values are the same then replace the PHI node
3851 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003852 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003853 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003854 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003855 // If the incoming value is the phi node itself, it can safely be skipped.
3856 if (Incoming == PN) continue;
3857 if (isa<UndefValue>(Incoming)) {
3858 // Remember that we saw an undef value, but otherwise ignore them.
3859 HasUndefInput = true;
3860 continue;
3861 }
3862 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003863 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003864 CommonValue = Incoming;
3865 }
3866
3867 // If CommonValue is null then all of the incoming values were either undef or
3868 // equal to the phi node itself.
3869 if (!CommonValue)
3870 return UndefValue::get(PN->getType());
3871
3872 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3873 // instruction, we cannot return X as the result of the PHI node unless it
3874 // dominates the PHI block.
3875 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003876 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003877
3878 return CommonValue;
3879}
3880
David Majnemer6774d612016-07-26 17:58:05 +00003881static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
3882 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00003883 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00003884 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003885
David Majnemer6774d612016-07-26 17:58:05 +00003886 if (auto *CI = dyn_cast<CastInst>(Op)) {
3887 auto *Src = CI->getOperand(0);
3888 Type *SrcTy = Src->getType();
3889 Type *MidTy = CI->getType();
3890 Type *DstTy = Ty;
3891 if (Src->getType() == Ty) {
3892 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
3893 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
3894 Type *SrcIntPtrTy =
3895 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
3896 Type *MidIntPtrTy =
3897 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
3898 Type *DstIntPtrTy =
3899 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
3900 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
3901 SrcIntPtrTy, MidIntPtrTy,
3902 DstIntPtrTy) == Instruction::BitCast)
3903 return Src;
3904 }
3905 }
David Majnemera90a6212016-07-26 05:52:29 +00003906
3907 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00003908 if (CastOpc == Instruction::BitCast)
3909 if (Op->getType() == Ty)
3910 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00003911
3912 return nullptr;
3913}
3914
David Majnemer6774d612016-07-26 17:58:05 +00003915Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
3916 const DataLayout &DL,
3917 const TargetLibraryInfo *TLI,
3918 const DominatorTree *DT, AssumptionCache *AC,
3919 const Instruction *CxtI) {
3920 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3921 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00003922}
3923
Chris Lattnera71e9d62009-11-10 00:55:12 +00003924//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003925
Sanjay Patel472cc782016-01-11 22:14:42 +00003926/// Given operands for a BinaryOperator, see if we can fold the result.
3927/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003928static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003929 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003930 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003931 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003932 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003933 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003934 case Instruction::FAdd:
3935 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3936
Chris Lattner9e4aa022011-02-09 17:15:04 +00003937 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003938 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003939 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003940 case Instruction::FSub:
3941 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3942
Duncan Sandsb8cee002012-03-13 11:42:19 +00003943 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003944 case Instruction::FMul:
3945 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003946 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3947 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003948 case Instruction::FDiv:
3949 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003950 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3951 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003952 case Instruction::FRem:
3953 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003954 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003955 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003956 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003957 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003958 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003959 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003960 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3961 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3962 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3963 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003964 default:
3965 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00003966 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3967 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00003968
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003969 // If the operation is associative, try some generic simplifications.
3970 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003971 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003972 return V;
3973
Duncan Sandsb8cee002012-03-13 11:42:19 +00003974 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003975 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003976 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003977 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003978 return V;
3979
3980 // If the operation is with the result of a phi instruction, check whether
3981 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003982 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003983 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003984 return V;
3985
Craig Topper9f008862014-04-15 04:59:12 +00003986 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003987 }
3988}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003989
Sanjay Patel472cc782016-01-11 22:14:42 +00003990/// Given operands for a BinaryOperator, see if we can fold the result.
3991/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003992/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3993/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3994static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3995 const FastMathFlags &FMF, const Query &Q,
3996 unsigned MaxRecurse) {
3997 switch (Opcode) {
3998 case Instruction::FAdd:
3999 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4000 case Instruction::FSub:
4001 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4002 case Instruction::FMul:
4003 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4004 default:
4005 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4006 }
4007}
4008
Duncan Sands7e800d62010-11-14 11:23:23 +00004009Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004010 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004011 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004012 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00004013 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004014 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004015}
4016
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004017Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004018 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004019 const TargetLibraryInfo *TLI,
4020 const DominatorTree *DT, AssumptionCache *AC,
4021 const Instruction *CxtI) {
4022 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
4023 RecursionLimit);
4024}
4025
Sanjay Patel472cc782016-01-11 22:14:42 +00004026/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004027static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004028 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004029 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004030 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004031 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004032}
4033
4034Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004035 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004036 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004037 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00004038 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004039 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004040}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004041
Michael Ilseman54857292013-02-07 19:26:05 +00004042static bool IsIdempotent(Intrinsic::ID ID) {
4043 switch (ID) {
4044 default: return false;
4045
4046 // Unary idempotent: f(f(x)) = f(x)
4047 case Intrinsic::fabs:
4048 case Intrinsic::floor:
4049 case Intrinsic::ceil:
4050 case Intrinsic::trunc:
4051 case Intrinsic::rint:
4052 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004053 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004054 return true;
4055 }
4056}
4057
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004058static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4059 const DataLayout &DL) {
4060 GlobalValue *PtrSym;
4061 APInt PtrOffset;
4062 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4063 return nullptr;
4064
4065 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4066 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4067 Type *Int32PtrTy = Int32Ty->getPointerTo();
4068 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4069
4070 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4071 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4072 return nullptr;
4073
4074 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4075 if (OffsetInt % 4 != 0)
4076 return nullptr;
4077
4078 Constant *C = ConstantExpr::getGetElementPtr(
4079 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4080 ConstantInt::get(Int64Ty, OffsetInt / 4));
4081 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4082 if (!Loaded)
4083 return nullptr;
4084
4085 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4086 if (!LoadedCE)
4087 return nullptr;
4088
4089 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4090 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4091 if (!LoadedCE)
4092 return nullptr;
4093 }
4094
4095 if (LoadedCE->getOpcode() != Instruction::Sub)
4096 return nullptr;
4097
4098 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4099 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4100 return nullptr;
4101 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4102
4103 Constant *LoadedRHS = LoadedCE->getOperand(1);
4104 GlobalValue *LoadedRHSSym;
4105 APInt LoadedRHSOffset;
4106 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4107 DL) ||
4108 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4109 return nullptr;
4110
4111 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4112}
4113
David Majnemer17a95aa2016-07-14 06:58:37 +00004114static bool maskIsAllZeroOrUndef(Value *Mask) {
4115 auto *ConstMask = dyn_cast<Constant>(Mask);
4116 if (!ConstMask)
4117 return false;
4118 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4119 return true;
4120 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4121 ++I) {
4122 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4123 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4124 continue;
4125 return false;
4126 }
4127 return true;
4128}
4129
Michael Ilseman54857292013-02-07 19:26:05 +00004130template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004131static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004132 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004133 Intrinsic::ID IID = F->getIntrinsicID();
4134 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4135 Type *ReturnType = F->getReturnType();
4136
4137 // Binary Ops
4138 if (NumOperands == 2) {
4139 Value *LHS = *ArgBegin;
4140 Value *RHS = *(ArgBegin + 1);
4141 if (IID == Intrinsic::usub_with_overflow ||
4142 IID == Intrinsic::ssub_with_overflow) {
4143 // X - X -> { 0, false }
4144 if (LHS == RHS)
4145 return Constant::getNullValue(ReturnType);
4146
4147 // X - undef -> undef
4148 // undef - X -> undef
4149 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4150 return UndefValue::get(ReturnType);
4151 }
4152
4153 if (IID == Intrinsic::uadd_with_overflow ||
4154 IID == Intrinsic::sadd_with_overflow) {
4155 // X + undef -> undef
4156 if (isa<UndefValue>(RHS))
4157 return UndefValue::get(ReturnType);
4158 }
4159
4160 if (IID == Intrinsic::umul_with_overflow ||
4161 IID == Intrinsic::smul_with_overflow) {
4162 // X * 0 -> { 0, false }
4163 if (match(RHS, m_Zero()))
4164 return Constant::getNullValue(ReturnType);
4165
4166 // X * undef -> { 0, false }
4167 if (match(RHS, m_Undef()))
4168 return Constant::getNullValue(ReturnType);
4169 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004170
4171 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4172 isa<Constant>(RHS))
4173 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4174 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00004175 }
4176
David Majnemerd77a3b62016-07-13 23:32:53 +00004177 // Simplify calls to llvm.masked.load.*
4178 if (IID == Intrinsic::masked_load) {
David Majnemer17a95aa2016-07-14 06:58:37 +00004179 Value *MaskArg = ArgBegin[2];
4180 Value *PassthruArg = ArgBegin[3];
4181 // If the mask is all zeros or undef, the "passthru" argument is the result.
4182 if (maskIsAllZeroOrUndef(MaskArg))
4183 return PassthruArg;
David Majnemerd77a3b62016-07-13 23:32:53 +00004184 }
4185
Michael Ilseman54857292013-02-07 19:26:05 +00004186 // Perform idempotent optimizations
4187 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00004188 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004189
4190 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00004191 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00004192 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4193 if (II->getIntrinsicID() == IID)
4194 return II;
4195
Craig Topper9f008862014-04-15 04:59:12 +00004196 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004197}
4198
Chandler Carruth9dc35582012-12-28 11:30:55 +00004199template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004200static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004201 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004202 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004203 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4204 Ty = PTy->getElementType();
4205 FunctionType *FTy = cast<FunctionType>(Ty);
4206
Dan Gohman85977e62011-11-04 18:32:42 +00004207 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004208 // call null -> undef
4209 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004210 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004211
Chandler Carruthf6182152012-12-28 14:23:29 +00004212 Function *F = dyn_cast<Function>(V);
4213 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004214 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004215
David Majnemer15032582015-05-22 03:56:46 +00004216 if (F->isIntrinsic())
4217 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004218 return Ret;
4219
Chandler Carruthf6182152012-12-28 14:23:29 +00004220 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004221 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004222
4223 SmallVector<Constant *, 4> ConstantArgs;
4224 ConstantArgs.reserve(ArgEnd - ArgBegin);
4225 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4226 Constant *C = dyn_cast<Constant>(*I);
4227 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004228 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004229 ConstantArgs.push_back(C);
4230 }
4231
4232 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004233}
4234
Chandler Carruthf6182152012-12-28 14:23:29 +00004235Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004236 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004237 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4238 AssumptionCache *AC, const Instruction *CxtI) {
4239 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004240 RecursionLimit);
4241}
4242
Chandler Carruthf6182152012-12-28 14:23:29 +00004243Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004244 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004245 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004246 const Instruction *CxtI) {
4247 return ::SimplifyCall(V, Args.begin(), Args.end(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004248 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004249}
4250
Sanjay Patel472cc782016-01-11 22:14:42 +00004251/// See if we can compute a simplified version of this instruction.
4252/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004253Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004254 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004255 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004256 Value *Result;
4257
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004258 switch (I->getOpcode()) {
4259 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004260 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004261 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004262 case Instruction::FAdd:
4263 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004264 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004265 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004266 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004267 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4268 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004269 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4270 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004271 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004272 case Instruction::FSub:
4273 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004274 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004275 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004276 case Instruction::Sub:
4277 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4278 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004279 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4280 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004281 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004282 case Instruction::FMul:
4283 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004284 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004285 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004286 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004287 Result =
4288 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004289 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004290 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004291 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4292 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004293 break;
4294 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004295 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4296 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004297 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004298 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004299 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4300 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004301 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004302 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004303 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4304 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004305 break;
4306 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004307 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4308 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004309 break;
4310 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004311 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4312 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004313 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004314 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004315 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4316 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004317 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4318 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004319 break;
4320 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004321 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004322 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4323 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004324 break;
4325 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004326 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004327 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4328 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004329 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004330 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004331 Result =
4332 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004333 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004334 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004335 Result =
4336 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004337 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004338 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004339 Result =
4340 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004341 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004342 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004343 Result =
4344 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4345 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004346 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004347 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004348 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4349 I->getOperand(0), I->getOperand(1),
4350 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004351 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004352 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004353 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004354 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004355 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004356 case Instruction::GetElementPtr: {
4357 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004358 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4359 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004360 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004361 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004362 case Instruction::InsertValue: {
4363 InsertValueInst *IV = cast<InsertValueInst>(I);
4364 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4365 IV->getInsertedValueOperand(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004366 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004367 break;
4368 }
David Majnemer25a796e2015-07-13 01:15:46 +00004369 case Instruction::ExtractValue: {
4370 auto *EVI = cast<ExtractValueInst>(I);
4371 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4372 EVI->getIndices(), DL, TLI, DT, AC, I);
4373 break;
4374 }
David Majnemer599ca442015-07-13 01:15:53 +00004375 case Instruction::ExtractElement: {
4376 auto *EEI = cast<ExtractElementInst>(I);
4377 Result = SimplifyExtractElementInst(
4378 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4379 break;
4380 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004381 case Instruction::PHI:
Chandler Carruth66b31302015-01-04 12:03:27 +00004382 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004383 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004384 case Instruction::Call: {
4385 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004386 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4387 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004388 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004389 }
David Majnemer6774d612016-07-26 17:58:05 +00004390#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4391#include "llvm/IR/Instruction.def"
4392#undef HANDLE_CAST_INST
4393 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
4394 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004395 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004396 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004397
Hal Finkelf2199b22015-10-23 20:37:08 +00004398 // In general, it is possible for computeKnownBits to determine all bits in a
4399 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004400 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004401 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4402 APInt KnownZero(BitWidth, 0);
4403 APInt KnownOne(BitWidth, 0);
4404 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4405 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004406 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004407 }
4408
Duncan Sands64e41cf2010-11-17 08:35:29 +00004409 /// If called on unreachable code, the above logic may report that the
4410 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004411 /// detecting that case here, returning a safe value instead.
4412 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004413}
4414
Sanjay Patelf44bd382016-01-20 18:59:48 +00004415/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004416/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004417///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004418/// This is the common implementation of the recursive simplification routines.
4419/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4420/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4421/// instructions to process and attempt to simplify it using
4422/// InstructionSimplify.
4423///
4424/// This routine returns 'true' only when *it* simplifies something. The passed
4425/// in simplified value does not count toward this.
4426static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004427 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004428 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004429 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004430 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004431 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004432 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004433
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004434 // If we have an explicit value to collapse to, do that round of the
4435 // simplification loop by hand initially.
4436 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004437 for (User *U : I->users())
4438 if (U != I)
4439 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004440
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004441 // Replace the instruction with its simplified value.
4442 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004443
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004444 // Gracefully handle edge cases where the instruction is not wired into any
4445 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004446 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4447 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004448 I->eraseFromParent();
4449 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004450 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004451 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004452
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004453 // Note that we must test the size on each iteration, the worklist can grow.
4454 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4455 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004456
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004457 // See if this instruction simplifies.
Chandler Carruth66b31302015-01-04 12:03:27 +00004458 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004459 if (!SimpleV)
4460 continue;
4461
4462 Simplified = true;
4463
4464 // Stash away all the uses of the old instruction so we can check them for
4465 // recursive simplifications after a RAUW. This is cheaper than checking all
4466 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004467 for (User *U : I->users())
4468 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004469
4470 // Replace the instruction with its simplified value.
4471 I->replaceAllUsesWith(SimpleV);
4472
4473 // Gracefully handle edge cases where the instruction is not wired into any
4474 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004475 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4476 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004477 I->eraseFromParent();
4478 }
4479 return Simplified;
4480}
4481
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004482bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004483 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004484 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004485 AssumptionCache *AC) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004486 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004487}
4488
4489bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004490 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004491 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004492 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004493 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4494 assert(SimpleV && "Must provide a simplified value.");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004495 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004496}