blob: c7e1724ac9bcaf82c706693da2e171d7e6d4030e [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);
Duncan Sands395ac42d2012-03-13 14:07:05 +000072static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000073
Sanjay Patel472cc782016-01-11 22:14:42 +000074/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000075/// a vector with every element false, as appropriate for the type.
76static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000077 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000078 "Expected i1 type or a vector of i1!");
79 return Constant::getNullValue(Ty);
80}
81
Sanjay Patel472cc782016-01-11 22:14:42 +000082/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000083/// a vector with every element true, as appropriate for the type.
84static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000085 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000086 "Expected i1 type or a vector of i1!");
87 return Constant::getAllOnesValue(Ty);
88}
89
Duncan Sands3d5692a2011-10-30 19:56:36 +000090/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
91static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
92 Value *RHS) {
93 CmpInst *Cmp = dyn_cast<CmpInst>(V);
94 if (!Cmp)
95 return false;
96 CmpInst::Predicate CPred = Cmp->getPredicate();
97 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
99 return true;
100 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
101 CRHS == LHS;
102}
103
Sanjay Patel472cc782016-01-11 22:14:42 +0000104/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000105static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106 Instruction *I = dyn_cast<Instruction>(V);
107 if (!I)
108 // Arguments and constants dominate all instructions.
109 return true;
110
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000111 // If we are processing instructions (and/or basic blocks) that have not been
112 // fully added to a function, the parent nodes may still be null. Simply
113 // return the conservative answer in these cases.
114 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
115 return false;
116
Duncan Sands5ffc2982010-11-16 12:16:38 +0000117 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000118 if (DT) {
119 if (!DT->isReachableFromEntry(P->getParent()))
120 return true;
121 if (!DT->isReachableFromEntry(I->getParent()))
122 return false;
123 return DT->dominates(I, P);
124 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000125
David Majnemer8a1c45d2015-12-12 05:38:55 +0000126 // Otherwise, if the instruction is in the entry block and is not an invoke,
127 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000128 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000129 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000130 return true;
131
132 return false;
133}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000134
Sanjay Patel472cc782016-01-11 22:14:42 +0000135/// Simplify "A op (B op' C)" by distributing op over op', turning it into
136/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000137/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139/// Returns the simplified value, or null if no simplification was performed.
140static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000141 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000142 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000143 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000144 // Recursion is always used, so bail out at once if we already hit the limit.
145 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000146 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000147
148 // Check whether the expression has the form "(A op' B) op C".
149 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
150 if (Op0->getOpcode() == OpcodeToExpand) {
151 // It does! Try turning it into "(A op C) op' (B op C)".
152 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
153 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000154 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
155 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000156 // They do! Return "L op' R" if it simplifies or is already available.
157 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000158 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
159 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000160 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000161 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000162 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000163 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000164 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000165 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000166 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000167 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000168 }
169 }
170
171 // Check whether the expression has the form "A op (B op' C)".
172 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
173 if (Op1->getOpcode() == OpcodeToExpand) {
174 // It does! Try turning it into "(A op B) op' (A op C)".
175 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
176 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000177 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
178 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000179 // They do! Return "L op' R" if it simplifies or is already available.
180 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000181 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
182 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000183 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000184 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000185 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000186 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000187 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000188 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000190 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000191 }
192 }
193
Craig Topper9f008862014-04-15 04:59:12 +0000194 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000195}
196
Sanjay Patel472cc782016-01-11 22:14:42 +0000197/// Generic simplifications for associative binary operations.
198/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000199static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000200 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000201 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000202 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
203
204 // Recursion is always used, so bail out at once if we already hit the limit.
205 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000206 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000207
208 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
209 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
210
211 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
212 if (Op0 && Op0->getOpcode() == Opcode) {
213 Value *A = Op0->getOperand(0);
214 Value *B = Op0->getOperand(1);
215 Value *C = RHS;
216
217 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000218 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000219 // It does! Return "A op V" if it simplifies or is already available.
220 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000221 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000222 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000223 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000224 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000225 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000226 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000227 }
228 }
229
230 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
231 if (Op1 && Op1->getOpcode() == Opcode) {
232 Value *A = LHS;
233 Value *B = Op1->getOperand(0);
234 Value *C = Op1->getOperand(1);
235
236 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000237 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000238 // It does! Return "V op C" if it simplifies or is already available.
239 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000240 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000241 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000242 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000243 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000244 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000245 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000246 }
247 }
248
249 // The remaining transforms require commutativity as well as associativity.
250 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000251 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000252
253 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
254 if (Op0 && Op0->getOpcode() == Opcode) {
255 Value *A = Op0->getOperand(0);
256 Value *B = Op0->getOperand(1);
257 Value *C = RHS;
258
259 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000260 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000261 // It does! Return "V op B" if it simplifies or is already available.
262 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000263 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000264 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000265 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000266 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000267 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000268 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000269 }
270 }
271
272 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
273 if (Op1 && Op1->getOpcode() == Opcode) {
274 Value *A = LHS;
275 Value *B = Op1->getOperand(0);
276 Value *C = Op1->getOperand(1);
277
278 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000279 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280 // It does! Return "B op V" if it simplifies or is already available.
281 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000282 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000284 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000285 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000287 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000288 }
289 }
290
Craig Topper9f008862014-04-15 04:59:12 +0000291 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292}
293
Sanjay Patel472cc782016-01-11 22:14:42 +0000294/// In the case of a binary operation with a select instruction as an operand,
295/// try to simplify the binop by seeing whether evaluating it on both branches
296/// of the select results in the same value. Returns the common value if so,
297/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000298static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000299 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000300 // Recursion is always used, so bail out at once if we already hit the limit.
301 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000302 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000303
Duncan Sandsb0579e92010-11-10 13:00:08 +0000304 SelectInst *SI;
305 if (isa<SelectInst>(LHS)) {
306 SI = cast<SelectInst>(LHS);
307 } else {
308 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309 SI = cast<SelectInst>(RHS);
310 }
311
312 // Evaluate the BinOp on the true and false branches of the select.
313 Value *TV;
314 Value *FV;
315 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000316 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000318 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000319 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000321 }
322
Duncan Sandse3c53952011-01-01 16:12:09 +0000323 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000324 // If they both failed to simplify then return null.
325 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000326 return TV;
327
328 // If one branch simplified to undef, return the other one.
329 if (TV && isa<UndefValue>(TV))
330 return FV;
331 if (FV && isa<UndefValue>(FV))
332 return TV;
333
334 // If applying the operation did not change the true and false select values,
335 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000336 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000337 return SI;
338
339 // If one branch simplified and the other did not, and the simplified
340 // value is equal to the unsimplified one, return the simplified value.
341 // For example, select (cond, X, X & Z) & Z -> X & Z.
342 if ((FV && !TV) || (TV && !FV)) {
343 // Check that the simplified value has the form "X op Y" where "op" is the
344 // same as the original operation.
345 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346 if (Simplified && Simplified->getOpcode() == Opcode) {
347 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348 // We already know that "op" is the same as for the simplified value. See
349 // if the operands match too. If so, return the simplified value.
350 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000353 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355 return Simplified;
356 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000357 Simplified->getOperand(1) == UnsimplifiedLHS &&
358 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000359 return Simplified;
360 }
361 }
362
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000364}
365
Sanjay Patel472cc782016-01-11 22:14:42 +0000366/// In the case of a comparison with a select instruction, try to simplify the
367/// comparison by seeing whether both branches of the select result in the same
368/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000369static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000370 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000371 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000372 // Recursion is always used, so bail out at once if we already hit the limit.
373 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000374 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000375
Duncan Sandsb0579e92010-11-10 13:00:08 +0000376 // Make sure the select is on the LHS.
377 if (!isa<SelectInst>(LHS)) {
378 std::swap(LHS, RHS);
379 Pred = CmpInst::getSwappedPredicate(Pred);
380 }
381 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000383 Value *Cond = SI->getCondition();
384 Value *TV = SI->getTrueValue();
385 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000386
Duncan Sands06504022011-02-03 09:37:39 +0000387 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000388 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000389 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000390 if (TCmp == Cond) {
391 // It not only simplified, it simplified to the select condition. Replace
392 // it with 'true'.
393 TCmp = getTrue(Cond->getType());
394 } else if (!TCmp) {
395 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
396 // condition then we can replace it with 'true'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000398 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000400 }
401
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000403 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000404 if (FCmp == Cond) {
405 // It not only simplified, it simplified to the select condition. Replace
406 // it with 'false'.
407 FCmp = getFalse(Cond->getType());
408 } else if (!FCmp) {
409 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
410 // condition then we can replace it with 'false'. Otherwise give up.
411 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000412 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000413 FCmp = getFalse(Cond->getType());
414 }
415
416 // If both sides simplified to the same value, then use it as the result of
417 // the original comparison.
418 if (TCmp == FCmp)
419 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000420
421 // The remaining cases only make sense if the select condition has the same
422 // type as the result of the comparison, so bail out if this is not so.
423 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000424 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000425 // If the false value simplified to false, then the result of the compare
426 // is equal to "Cond && TCmp". This also catches the case when the false
427 // value simplified to false and the true value to true, returning "Cond".
428 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000429 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000430 return V;
431 // If the true value simplified to true, then the result of the compare
432 // is equal to "Cond || FCmp".
433 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000434 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000435 return V;
436 // Finally, if the false value simplified to true and the true value to
437 // false, then the result of the compare is equal to "!Cond".
438 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
439 if (Value *V =
440 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000441 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000442 return V;
443
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000445}
446
Sanjay Patel472cc782016-01-11 22:14:42 +0000447/// In the case of a binary operation with an operand that is a PHI instruction,
448/// try to simplify the binop by seeing whether evaluating it on the incoming
449/// phi values yields the same result for every value. If so returns the common
450/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000451static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000452 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000453 // Recursion is always used, so bail out at once if we already hit the limit.
454 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000456
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000457 PHINode *PI;
458 if (isa<PHINode>(LHS)) {
459 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000460 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000461 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000462 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000463 } else {
464 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
465 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000466 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000467 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000468 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000469 }
470
471 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000472 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000473 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000474 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000475 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000476 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000477 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
478 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000479 // If the operation failed to simplify, or simplified to a different value
480 // to previously, then give up.
481 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000482 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000483 CommonValue = V;
484 }
485
486 return CommonValue;
487}
488
Sanjay Patel472cc782016-01-11 22:14:42 +0000489/// In the case of a comparison with a PHI instruction, try to simplify the
490/// comparison by seeing whether comparing with all of the incoming phi values
491/// yields the same result every time. If so returns the common result,
492/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000493static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000494 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000495 // Recursion is always used, so bail out at once if we already hit the limit.
496 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000497 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000498
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000499 // Make sure the phi is on the LHS.
500 if (!isa<PHINode>(LHS)) {
501 std::swap(LHS, RHS);
502 Pred = CmpInst::getSwappedPredicate(Pred);
503 }
504 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
505 PHINode *PI = cast<PHINode>(LHS);
506
Duncan Sands5ffc2982010-11-16 12:16:38 +0000507 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000508 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000509 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000510
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000511 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000512 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000513 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000514 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000515 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000516 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000517 // If the operation failed to simplify, or simplified to a different value
518 // to previously, then give up.
519 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000520 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000521 CommonValue = V;
522 }
523
524 return CommonValue;
525}
526
Sanjay Patel472cc782016-01-11 22:14:42 +0000527/// Given operands for an Add, see if we can fold the result.
528/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000529static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000530 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000531 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000532 if (Constant *CRHS = dyn_cast<Constant>(Op1))
533 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000534
Chris Lattner3d9823b2009-11-27 17:42:22 +0000535 // Canonicalize the constant to the RHS.
536 std::swap(Op0, Op1);
537 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000540 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000541 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + 0 -> X
544 if (match(Op1, m_Zero()))
545 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + (Y - X) -> Y
548 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000549 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000550 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000553 return Y;
554
555 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000556 if (match(Op0, m_Not(m_Specific(Op1))) ||
557 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000558 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000559
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000560 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000561 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000562 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000563 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000564
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000565 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000566 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000567 MaxRecurse))
568 return V;
569
Duncan Sandsb238de02010-11-19 09:20:39 +0000570 // Threading Add over selects and phi nodes is pointless, so don't bother.
571 // Threading over the select in "A + select(cond, B, C)" means evaluating
572 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573 // only if B and C are equal. If B and C are equal then (since we assume
574 // that operands have already been simplified) "select(cond, B, C)" should
575 // have been simplified to the common value of B and C already. Analysing
576 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
577 // for threading over phi nodes.
578
Craig Topper9f008862014-04-15 04:59:12 +0000579 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000580}
581
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000582Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000583 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000584 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000585 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
587 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000588}
589
Chandler Carrutha0796552012-03-12 11:19:31 +0000590/// \brief Compute the base pointer and cumulative constant offsets for V.
591///
592/// This strips all constant offsets off of V, leaving it the base pointer, and
593/// accumulates the total constant offset applied in the returned constant. It
594/// returns 0 if V is not a pointer, and returns the constant '0' if there are
595/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000596///
597/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000601 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000602 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000603
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000605 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000606
607 // Even though we don't look through PHI nodes, we could be called on an
608 // instruction in an unreachable block, which may be on a cycle.
609 SmallPtrSet<Value *, 4> Visited;
610 Visited.insert(V);
611 do {
612 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000613 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000614 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000615 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 V = GEP->getPointerOperand();
617 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000618 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000620 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000621 break;
622 V = GA->getAliasee();
623 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000624 if (auto CS = CallSite(V))
625 if (Value *RV = CS.getReturnedArgOperand()) {
626 V = RV;
627 continue;
628 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000629 break;
630 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000631 assert(V->getType()->getScalarType()->isPointerTy() &&
632 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000633 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000634
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000635 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636 if (V->getType()->isVectorTy())
637 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
638 OffsetIntPtr);
639 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000640}
641
642/// \brief Compute the constant difference between two pointer values.
643/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
645 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000646 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000648
649 // If LHS and RHS are not related via constant offsets to the same base
650 // value, there is nothing we can do here.
651 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000652 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000653
654 // Otherwise, the difference of LHS - RHS can be computed as:
655 // LHS - RHS
656 // = (LHSOffset + Base) - (RHSOffset + Base)
657 // = LHSOffset - RHSOffset
658 return ConstantExpr::getSub(LHSOffset, RHSOffset);
659}
660
Sanjay Patel472cc782016-01-11 22:14:42 +0000661/// Given operands for a Sub, see if we can fold the result.
662/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000663static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000664 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000665 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000666 if (Constant *CRHS = dyn_cast<Constant>(Op1))
667 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000668
669 // X - undef -> undef
670 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000671 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000672 return UndefValue::get(Op0->getType());
673
674 // X - 0 -> X
675 if (match(Op1, m_Zero()))
676 return Op0;
677
678 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000679 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000680 return Constant::getNullValue(Op0->getType());
681
David Majnemer4efa9ff2014-11-22 07:15:16 +0000682 // 0 - X -> 0 if the sub is NUW.
683 if (isNUW && match(Op0, m_Zero()))
684 return Op0;
David Majnemercd4fbcd2014-07-31 04:49:18 +0000685
Duncan Sands99589d02011-01-18 11:50:19 +0000686 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
687 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000688 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000689 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
690 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000691 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000692 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000693 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000694 // It does, we successfully reassociated!
695 ++NumReassoc;
696 return W;
697 }
698 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000699 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000700 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000701 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000702 // It does, we successfully reassociated!
703 ++NumReassoc;
704 return W;
705 }
706 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000707
Duncan Sands99589d02011-01-18 11:50:19 +0000708 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
709 // For example, X - (X + 1) -> -1
710 X = Op0;
711 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
712 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000713 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000714 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000715 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000716 // It does, we successfully reassociated!
717 ++NumReassoc;
718 return W;
719 }
720 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000721 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000722 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000723 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000724 // It does, we successfully reassociated!
725 ++NumReassoc;
726 return W;
727 }
728 }
729
730 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
731 // For example, X - (X - Y) -> Y.
732 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000733 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
734 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000736 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000737 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000738 // It does, we successfully reassociated!
739 ++NumReassoc;
740 return W;
741 }
742
Duncan Sands395ac42d2012-03-13 14:07:05 +0000743 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
744 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
745 match(Op1, m_Trunc(m_Value(Y))))
746 if (X->getType() == Y->getType())
747 // See if "V === X - Y" simplifies.
748 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
749 // It does! Now see if "trunc V" simplifies.
750 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
751 // It does, return the simplified "trunc V".
752 return W;
753
754 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000755 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000756 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000757 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000758 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
759
Duncan Sands99589d02011-01-18 11:50:19 +0000760 // i1 sub -> xor.
761 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000762 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000763 return V;
764
Duncan Sands0a2c41682010-12-15 14:07:39 +0000765 // Threading Sub over selects and phi nodes is pointless, so don't bother.
766 // Threading over the select in "A - select(cond, B, C)" means evaluating
767 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
768 // only if B and C are equal. If B and C are equal then (since we assume
769 // that operands have already been simplified) "select(cond, B, C)" should
770 // have been simplified to the common value of B and C already. Analysing
771 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
772 // for threading over phi nodes.
773
Craig Topper9f008862014-04-15 04:59:12 +0000774 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000775}
776
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000777Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000778 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000779 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000780 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000781 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
782 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000783}
784
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000785/// Given operands for an FAdd, see if we can fold the result. If not, this
786/// returns null.
787static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
788 const Query &Q, unsigned MaxRecurse) {
789 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000790 if (Constant *CRHS = dyn_cast<Constant>(Op1))
791 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000792
793 // Canonicalize the constant to the RHS.
794 std::swap(Op0, Op1);
795 }
796
797 // fadd X, -0 ==> X
798 if (match(Op1, m_NegZero()))
799 return Op0;
800
801 // fadd X, 0 ==> X, when we know X is not -0
802 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000803 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000804 return Op0;
805
806 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
807 // where nnan and ninf have to occur at least once somewhere in this
808 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000809 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000810 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
811 SubOp = Op1;
812 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
813 SubOp = Op0;
814 if (SubOp) {
815 Instruction *FSub = cast<Instruction>(SubOp);
816 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
817 (FMF.noInfs() || FSub->hasNoInfs()))
818 return Constant::getNullValue(Op0->getType());
819 }
820
Craig Topper9f008862014-04-15 04:59:12 +0000821 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000822}
823
824/// Given operands for an FSub, see if we can fold the result. If not, this
825/// returns null.
826static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
827 const Query &Q, unsigned MaxRecurse) {
828 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000829 if (Constant *CRHS = dyn_cast<Constant>(Op1))
830 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000831 }
832
833 // fsub X, 0 ==> X
834 if (match(Op1, m_Zero()))
835 return Op0;
836
837 // fsub X, -0 ==> X, when we know X is not -0
838 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000839 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000840 return Op0;
841
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000842 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000843 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000844 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
845 return X;
846
847 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000848 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000849 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
850 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000851
Benjamin Kramer228680d2015-06-14 21:01:20 +0000852 // fsub nnan x, x ==> 0.0
853 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000854 return Constant::getNullValue(Op0->getType());
855
Craig Topper9f008862014-04-15 04:59:12 +0000856 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000857}
858
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000859/// Given the operands for an FMul, see if we can fold the result
860static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
861 FastMathFlags FMF,
862 const Query &Q,
863 unsigned MaxRecurse) {
864 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000865 if (Constant *CRHS = dyn_cast<Constant>(Op1))
866 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000867
868 // Canonicalize the constant to the RHS.
869 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000870 }
871
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872 // fmul X, 1.0 ==> X
873 if (match(Op1, m_FPOne()))
874 return Op0;
875
876 // fmul nnan nsz X, 0 ==> 0
877 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
878 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000879
Craig Topper9f008862014-04-15 04:59:12 +0000880 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000881}
882
Sanjay Patel472cc782016-01-11 22:14:42 +0000883/// Given operands for a Mul, see if we can fold the result.
884/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000885static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000887 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000888 if (Constant *CRHS = dyn_cast<Constant>(Op1))
889 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000890
891 // Canonicalize the constant to the RHS.
892 std::swap(Op0, Op1);
893 }
894
895 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000896 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000897 return Constant::getNullValue(Op0->getType());
898
899 // X * 0 -> 0
900 if (match(Op1, m_Zero()))
901 return Op1;
902
903 // X * 1 -> X
904 if (match(Op1, m_One()))
905 return Op0;
906
Duncan Sandsb67edc62011-01-30 18:03:50 +0000907 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000908 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000909 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
910 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
911 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000912
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000913 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000914 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000915 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000916 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000917
918 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000919 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000920 MaxRecurse))
921 return V;
922
923 // Mul distributes over Add. Try some generic simplifications based on this.
924 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000925 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000926 return V;
927
928 // If the operation is with the result of a select instruction, check whether
929 // operating on either branch of the select always yields the same value.
930 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000931 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000932 MaxRecurse))
933 return V;
934
935 // If the operation is with the result of a phi instruction, check whether
936 // operating on all incoming values of the phi always yields the same value.
937 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000938 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000939 MaxRecurse))
940 return V;
941
Craig Topper9f008862014-04-15 04:59:12 +0000942 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000943}
944
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000945Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000946 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000947 const TargetLibraryInfo *TLI,
948 const DominatorTree *DT, AssumptionCache *AC,
949 const Instruction *CxtI) {
950 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000951 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000952}
953
954Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000955 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000956 const TargetLibraryInfo *TLI,
957 const DominatorTree *DT, AssumptionCache *AC,
958 const Instruction *CxtI) {
959 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000960 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000961}
962
Chandler Carruth66b31302015-01-04 12:03:27 +0000963Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000964 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000965 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000966 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000967 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000968 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000969 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000970}
971
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000973 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000974 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000975 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000976 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000977 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000978}
979
Sanjay Patel472cc782016-01-11 22:14:42 +0000980/// Given operands for an SDiv or UDiv, see if we can fold the result.
981/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000982static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000983 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000984 if (Constant *C0 = dyn_cast<Constant>(Op0))
985 if (Constant *C1 = dyn_cast<Constant>(Op1))
986 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +0000987
Duncan Sands65995fa2011-01-28 18:50:50 +0000988 bool isSigned = Opcode == Instruction::SDiv;
989
Duncan Sands771e82a2011-01-28 16:51:11 +0000990 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000991 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000992 return Op1;
993
David Majnemer71dc8fb2014-12-10 07:52:18 +0000994 // X / 0 -> undef, we don't need to preserve faults!
995 if (match(Op1, m_Zero()))
996 return UndefValue::get(Op1->getType());
997
Duncan Sands771e82a2011-01-28 16:51:11 +0000998 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000999 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001000 return Constant::getNullValue(Op0->getType());
1001
1002 // 0 / X -> 0, we don't need to preserve faults!
1003 if (match(Op0, m_Zero()))
1004 return Op0;
1005
1006 // X / 1 -> X
1007 if (match(Op1, m_One()))
1008 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001009
1010 if (Op0->getType()->isIntegerTy(1))
1011 // It can't be division by zero, hence it must be division by one.
1012 return Op0;
1013
1014 // X / X -> 1
1015 if (Op0 == Op1)
1016 return ConstantInt::get(Op0->getType(), 1);
1017
1018 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001019 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001020 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1021 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001022 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001023 // If the Mul knows it does not overflow, then we are good to go.
1024 if ((isSigned && Mul->hasNoSignedWrap()) ||
1025 (!isSigned && Mul->hasNoUnsignedWrap()))
1026 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001027 // If X has the form X = A / Y then X * Y cannot overflow.
1028 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1029 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1030 return X;
1031 }
1032
Duncan Sands65995fa2011-01-28 18:50:50 +00001033 // (X rem Y) / Y -> 0
1034 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1035 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1036 return Constant::getNullValue(Op0->getType());
1037
David Majnemercb9d5962014-10-11 10:20:01 +00001038 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1039 ConstantInt *C1, *C2;
1040 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1041 match(Op1, m_ConstantInt(C2))) {
1042 bool Overflow;
1043 C1->getValue().umul_ov(C2->getValue(), Overflow);
1044 if (Overflow)
1045 return Constant::getNullValue(Op0->getType());
1046 }
1047
Duncan Sands65995fa2011-01-28 18:50:50 +00001048 // If the operation is with the result of a select instruction, check whether
1049 // operating on either branch of the select always yields the same value.
1050 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001051 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001052 return V;
1053
1054 // If the operation is with the result of a phi instruction, check whether
1055 // operating on all incoming values of the phi always yields the same value.
1056 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001057 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001058 return V;
1059
Craig Topper9f008862014-04-15 04:59:12 +00001060 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001061}
1062
Sanjay Patel472cc782016-01-11 22:14:42 +00001063/// Given operands for an SDiv, see if we can fold the result.
1064/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001065static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1066 unsigned MaxRecurse) {
1067 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001068 return V;
1069
Craig Topper9f008862014-04-15 04:59:12 +00001070 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001071}
1072
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001073Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001074 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001075 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001076 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001077 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001078 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001079}
1080
Sanjay Patel472cc782016-01-11 22:14:42 +00001081/// Given operands for a UDiv, see if we can fold the result.
1082/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001083static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1084 unsigned MaxRecurse) {
1085 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001086 return V;
1087
Craig Topper9f008862014-04-15 04:59:12 +00001088 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001089}
1090
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001091Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001092 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001093 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001094 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001095 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001096 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001097}
1098
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001099static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1100 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001101 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001102 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001103 return Op0;
1104
1105 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001106 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001107 return Op1;
1108
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001109 // 0 / X -> 0
1110 // Requires that NaNs are off (X could be zero) and signed zeroes are
1111 // ignored (X could be positive or negative, so the output sign is unknown).
1112 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1113 return Op0;
1114
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001115 if (FMF.noNaNs()) {
1116 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001117 if (Op0 == Op1)
1118 return ConstantFP::get(Op0->getType(), 1.0);
1119
1120 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001121 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001122 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1123 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1124 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1125 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1126 BinaryOperator::getFNegArgument(Op1) == Op0))
1127 return ConstantFP::get(Op0->getType(), -1.0);
1128 }
1129
Craig Topper9f008862014-04-15 04:59:12 +00001130 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001131}
1132
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001133Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001134 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001135 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001136 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001137 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001138 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001139 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001140}
1141
Sanjay Patel472cc782016-01-11 22:14:42 +00001142/// Given operands for an SRem or URem, see if we can fold the result.
1143/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001144static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001145 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001146 if (Constant *C0 = dyn_cast<Constant>(Op0))
1147 if (Constant *C1 = dyn_cast<Constant>(Op1))
1148 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001149
Duncan Sandsa3e36992011-05-02 16:27:02 +00001150 // X % undef -> undef
1151 if (match(Op1, m_Undef()))
1152 return Op1;
1153
1154 // undef % X -> 0
1155 if (match(Op0, m_Undef()))
1156 return Constant::getNullValue(Op0->getType());
1157
1158 // 0 % X -> 0, we don't need to preserve faults!
1159 if (match(Op0, m_Zero()))
1160 return Op0;
1161
1162 // X % 0 -> undef, we don't need to preserve faults!
1163 if (match(Op1, m_Zero()))
1164 return UndefValue::get(Op0->getType());
1165
1166 // X % 1 -> 0
1167 if (match(Op1, m_One()))
1168 return Constant::getNullValue(Op0->getType());
1169
1170 if (Op0->getType()->isIntegerTy(1))
1171 // It can't be remainder by zero, hence it must be remainder by one.
1172 return Constant::getNullValue(Op0->getType());
1173
1174 // X % X -> 0
1175 if (Op0 == Op1)
1176 return Constant::getNullValue(Op0->getType());
1177
David Majnemerb435a422014-09-17 04:16:35 +00001178 // (X % Y) % Y -> X % Y
1179 if ((Opcode == Instruction::SRem &&
1180 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1181 (Opcode == Instruction::URem &&
1182 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001183 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001184
Duncan Sandsa3e36992011-05-02 16:27:02 +00001185 // If the operation is with the result of a select instruction, check whether
1186 // operating on either branch of the select always yields the same value.
1187 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001188 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001189 return V;
1190
1191 // If the operation is with the result of a phi instruction, check whether
1192 // operating on all incoming values of the phi always yields the same value.
1193 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001194 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001195 return V;
1196
Craig Topper9f008862014-04-15 04:59:12 +00001197 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001198}
1199
Sanjay Patel472cc782016-01-11 22:14:42 +00001200/// Given operands for an SRem, see if we can fold the result.
1201/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001202static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1203 unsigned MaxRecurse) {
1204 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001205 return V;
1206
Craig Topper9f008862014-04-15 04:59:12 +00001207 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001208}
1209
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001210Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001211 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001212 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001213 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001214 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001215 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001216}
1217
Sanjay Patel472cc782016-01-11 22:14:42 +00001218/// Given operands for a URem, see if we can fold the result.
1219/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001220static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001221 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001222 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001223 return V;
1224
Craig Topper9f008862014-04-15 04:59:12 +00001225 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001226}
1227
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001228Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001229 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001230 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001231 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001232 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001233 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001234}
1235
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001236static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1237 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001238 // undef % X -> undef (the undef could be a snan).
1239 if (match(Op0, m_Undef()))
1240 return Op0;
1241
1242 // X % undef -> undef
1243 if (match(Op1, m_Undef()))
1244 return Op1;
1245
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001246 // 0 % X -> 0
1247 // Requires that NaNs are off (X could be zero) and signed zeroes are
1248 // ignored (X could be positive or negative, so the output sign is unknown).
1249 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1250 return Op0;
1251
Craig Topper9f008862014-04-15 04:59:12 +00001252 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001253}
1254
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001255Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001257 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001258 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001259 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001260 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001261 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001262}
1263
Sanjay Patel472cc782016-01-11 22:14:42 +00001264/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001265static bool isUndefShift(Value *Amount) {
1266 Constant *C = dyn_cast<Constant>(Amount);
1267 if (!C)
1268 return false;
1269
1270 // X shift by undef -> undef because it may shift by the bitwidth.
1271 if (isa<UndefValue>(C))
1272 return true;
1273
1274 // Shifting by the bitwidth or more is undefined.
1275 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1276 if (CI->getValue().getLimitedValue() >=
1277 CI->getType()->getScalarSizeInBits())
1278 return true;
1279
1280 // If all lanes of a vector shift are undefined the whole shift is.
1281 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1282 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1283 if (!isUndefShift(C->getAggregateElement(I)))
1284 return false;
1285 return true;
1286 }
1287
1288 return false;
1289}
1290
Sanjay Patel472cc782016-01-11 22:14:42 +00001291/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1292/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001293static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001294 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001295 if (Constant *C0 = dyn_cast<Constant>(Op0))
1296 if (Constant *C1 = dyn_cast<Constant>(Op1))
1297 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001298
Duncan Sands571fd9a2011-01-14 14:44:12 +00001299 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001300 if (match(Op0, m_Zero()))
1301 return Op0;
1302
Duncan Sands571fd9a2011-01-14 14:44:12 +00001303 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001304 if (match(Op1, m_Zero()))
1305 return Op0;
1306
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001307 // Fold undefined shifts.
1308 if (isUndefShift(Op1))
1309 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001310
Duncan Sands571fd9a2011-01-14 14:44:12 +00001311 // If the operation is with the result of a select instruction, check whether
1312 // operating on either branch of the select always yields the same value.
1313 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001314 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001315 return V;
1316
1317 // If the operation is with the result of a phi instruction, check whether
1318 // operating on all incoming values of the phi always yields the same value.
1319 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001320 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001321 return V;
1322
Sanjay Patel6786bc52016-05-10 20:46:54 +00001323 // If any bits in the shift amount make that value greater than or equal to
1324 // the number of bits in the type, the shift is undefined.
1325 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1326 APInt KnownZero(BitWidth, 0);
1327 APInt KnownOne(BitWidth, 0);
1328 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1329 if (KnownOne.getLimitedValue() >= BitWidth)
1330 return UndefValue::get(Op0->getType());
1331
1332 // If all valid bits in the shift amount are known zero, the first operand is
1333 // unchanged.
1334 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1335 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1336 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1337 return Op0;
1338
Craig Topper9f008862014-04-15 04:59:12 +00001339 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001340}
1341
David Majnemerbf7550e2014-11-05 00:59:59 +00001342/// \brief Given operands for an Shl, LShr or AShr, see if we can
1343/// fold the result. If not, this returns null.
1344static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1345 bool isExact, const Query &Q,
1346 unsigned MaxRecurse) {
1347 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1348 return V;
1349
1350 // X >> X -> 0
1351 if (Op0 == Op1)
1352 return Constant::getNullValue(Op0->getType());
1353
David Majnemer65c52ae2014-12-17 01:54:33 +00001354 // undef >> X -> 0
1355 // undef >> X -> undef (if it's exact)
1356 if (match(Op0, m_Undef()))
1357 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1358
David Majnemerbf7550e2014-11-05 00:59:59 +00001359 // The low bit cannot be shifted out of an exact shift if it is set.
1360 if (isExact) {
1361 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1362 APInt Op0KnownZero(BitWidth, 0);
1363 APInt Op0KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00001364 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1365 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001366 if (Op0KnownOne[0])
1367 return Op0;
1368 }
1369
1370 return nullptr;
1371}
1372
Sanjay Patel472cc782016-01-11 22:14:42 +00001373/// Given operands for an Shl, see if we can fold the result.
1374/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001375static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001376 const Query &Q, unsigned MaxRecurse) {
1377 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001378 return V;
1379
1380 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001381 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001382 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001383 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001384
Chris Lattner9e4aa022011-02-09 17:15:04 +00001385 // (X >> A) << A -> X
1386 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001387 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001388 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001389 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001390}
1391
Chris Lattner9e4aa022011-02-09 17:15:04 +00001392Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001393 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001394 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001395 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001396 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001397 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001398}
1399
Sanjay Patel472cc782016-01-11 22:14:42 +00001400/// Given operands for an LShr, see if we can fold the result.
1401/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001402static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001403 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001404 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1405 MaxRecurse))
1406 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001407
Chris Lattner9e4aa022011-02-09 17:15:04 +00001408 // (X << A) >> A -> X
1409 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001410 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001411 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001412
Craig Topper9f008862014-04-15 04:59:12 +00001413 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001414}
1415
Chris Lattner9e4aa022011-02-09 17:15:04 +00001416Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001417 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001418 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001419 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001420 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001421 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001422 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001423}
1424
Sanjay Patel472cc782016-01-11 22:14:42 +00001425/// Given operands for an AShr, see if we can fold the result.
1426/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001427static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001428 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001429 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1430 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001431 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001432
1433 // all ones >>a X -> all ones
1434 if (match(Op0, m_AllOnes()))
1435 return Op0;
1436
Chris Lattner9e4aa022011-02-09 17:15:04 +00001437 // (X << A) >> A -> X
1438 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001439 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001440 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001441
Suyog Sarda68862412014-07-17 06:28:15 +00001442 // Arithmetic shifting an all-sign-bit value is a no-op.
Chandler Carruth66b31302015-01-04 12:03:27 +00001443 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001444 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1445 return Op0;
1446
Craig Topper9f008862014-04-15 04:59:12 +00001447 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001448}
1449
Chris Lattner9e4aa022011-02-09 17:15:04 +00001450Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001451 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001452 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001453 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001454 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001455 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001456 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001457}
1458
David Majnemer1af36e52014-12-06 10:51:40 +00001459static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1460 ICmpInst *UnsignedICmp, bool IsAnd) {
1461 Value *X, *Y;
1462
1463 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001464 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1465 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001466 return nullptr;
1467
1468 ICmpInst::Predicate UnsignedPred;
1469 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1470 ICmpInst::isUnsigned(UnsignedPred))
1471 ;
1472 else if (match(UnsignedICmp,
1473 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1474 ICmpInst::isUnsigned(UnsignedPred))
1475 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1476 else
1477 return nullptr;
1478
1479 // X < Y && Y != 0 --> X < Y
1480 // X < Y || Y != 0 --> Y != 0
1481 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1482 return IsAnd ? UnsignedICmp : ZeroICmp;
1483
1484 // X >= Y || Y != 0 --> true
1485 // X >= Y || Y == 0 --> X >= Y
1486 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1487 if (EqPred == ICmpInst::ICMP_NE)
1488 return getTrue(UnsignedICmp->getType());
1489 return UnsignedICmp;
1490 }
1491
David Majnemerd5b3aa42014-12-08 18:30:43 +00001492 // X < Y && Y == 0 --> false
1493 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1494 IsAnd)
1495 return getFalse(UnsignedICmp->getType());
1496
David Majnemer1af36e52014-12-06 10:51:40 +00001497 return nullptr;
1498}
1499
David Majnemera315bd82014-09-15 08:15:28 +00001500static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001501 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001502 ICmpInst::Predicate Pred0, Pred1;
1503 ConstantInt *CI1, *CI2;
1504 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001505
1506 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1507 return X;
1508
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001509 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1510 const APInt *C0, *C1;
1511 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1512 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1513 // Make a constant range that's the intersection of the two icmp ranges.
1514 // If the intersection is empty, we know that the result is false.
1515 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1516 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1517 if (Range0.intersectWith(Range1).isEmptySet())
1518 return getFalse(ITy);
1519 }
1520
David Majnemera315bd82014-09-15 08:15:28 +00001521 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1522 m_ConstantInt(CI2))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001523 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001524
1525 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1526 return nullptr;
1527
David Majnemera315bd82014-09-15 08:15:28 +00001528 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1529 bool isNSW = AddInst->hasNoSignedWrap();
1530 bool isNUW = AddInst->hasNoUnsignedWrap();
1531
1532 const APInt &CI1V = CI1->getValue();
1533 const APInt &CI2V = CI2->getValue();
1534 const APInt Delta = CI2V - CI1V;
1535 if (CI1V.isStrictlyPositive()) {
1536 if (Delta == 2) {
1537 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1538 return getFalse(ITy);
1539 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1540 return getFalse(ITy);
1541 }
1542 if (Delta == 1) {
1543 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1544 return getFalse(ITy);
1545 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1546 return getFalse(ITy);
1547 }
1548 }
1549 if (CI1V.getBoolValue() && isNUW) {
1550 if (Delta == 2)
1551 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1552 return getFalse(ITy);
1553 if (Delta == 1)
1554 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1555 return getFalse(ITy);
1556 }
1557
1558 return nullptr;
1559}
1560
Sanjay Patel472cc782016-01-11 22:14:42 +00001561/// Given operands for an And, see if we can fold the result.
1562/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001563static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001564 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001565 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001566 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1567 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001568
Chris Lattnera71e9d62009-11-10 00:55:12 +00001569 // Canonicalize the constant to the RHS.
1570 std::swap(Op0, Op1);
1571 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001572
Chris Lattnera71e9d62009-11-10 00:55:12 +00001573 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001574 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001575 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001576
Chris Lattnera71e9d62009-11-10 00:55:12 +00001577 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001578 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001579 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001580
Duncan Sandsc89ac072010-11-17 18:52:15 +00001581 // X & 0 = 0
1582 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001583 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001584
Duncan Sandsc89ac072010-11-17 18:52:15 +00001585 // X & -1 = X
1586 if (match(Op1, m_AllOnes()))
1587 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001588
Chris Lattnera71e9d62009-11-10 00:55:12 +00001589 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001590 if (match(Op0, m_Not(m_Specific(Op1))) ||
1591 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001592 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001593
Chris Lattnera71e9d62009-11-10 00:55:12 +00001594 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001595 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001596 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001597 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001598 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001599
Chris Lattnera71e9d62009-11-10 00:55:12 +00001600 // A & (A | ?) = A
1601 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001602 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001603 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001604
Duncan Sandsba286d72011-10-26 20:55:21 +00001605 // A & (-A) = A if A is a power of two or zero.
1606 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1607 match(Op1, m_Neg(m_Specific(Op0)))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001608 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1609 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001610 return Op0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001611 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1612 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001613 return Op1;
1614 }
1615
David Majnemera315bd82014-09-15 08:15:28 +00001616 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1617 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1618 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1619 return V;
1620 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1621 return V;
1622 }
1623 }
1624
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001625 // The compares may be hidden behind casts. Look through those and try the
1626 // same folds as above.
1627 auto *Cast0 = dyn_cast<CastInst>(Op0);
1628 auto *Cast1 = dyn_cast<CastInst>(Op1);
1629 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1630 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1631 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1632 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1633 if (Cmp0 && Cmp1) {
1634 Instruction::CastOps CastOpc = Cast0->getOpcode();
1635 Type *ResultType = Cast0->getType();
1636 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1637 return ConstantExpr::getCast(CastOpc, V, ResultType);
1638 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1639 return ConstantExpr::getCast(CastOpc, V, ResultType);
1640 }
1641 }
1642
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001643 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001644 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1645 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001646 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001647
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001648 // And distributes over Or. Try some generic simplifications based on this.
1649 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001650 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001651 return V;
1652
1653 // And distributes over Xor. Try some generic simplifications based on this.
1654 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001655 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001656 return V;
1657
Duncan Sandsb0579e92010-11-10 13:00:08 +00001658 // If the operation is with the result of a select instruction, check whether
1659 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001660 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001661 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1662 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001663 return V;
1664
1665 // If the operation is with the result of a phi instruction, check whether
1666 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001667 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001668 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001669 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001670 return V;
1671
Craig Topper9f008862014-04-15 04:59:12 +00001672 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001673}
1674
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001675Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001676 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001677 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001678 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001679 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001680 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001681}
1682
Sanjay Patel472cc782016-01-11 22:14:42 +00001683/// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1684/// contains all possible values.
David Majnemera315bd82014-09-15 08:15:28 +00001685static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1686 ICmpInst::Predicate Pred0, Pred1;
1687 ConstantInt *CI1, *CI2;
1688 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001689
1690 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1691 return X;
1692
David Majnemera315bd82014-09-15 08:15:28 +00001693 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1694 m_ConstantInt(CI2))))
1695 return nullptr;
1696
1697 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1698 return nullptr;
1699
1700 Type *ITy = Op0->getType();
1701
1702 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1703 bool isNSW = AddInst->hasNoSignedWrap();
1704 bool isNUW = AddInst->hasNoUnsignedWrap();
1705
1706 const APInt &CI1V = CI1->getValue();
1707 const APInt &CI2V = CI2->getValue();
1708 const APInt Delta = CI2V - CI1V;
1709 if (CI1V.isStrictlyPositive()) {
1710 if (Delta == 2) {
1711 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1712 return getTrue(ITy);
1713 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1714 return getTrue(ITy);
1715 }
1716 if (Delta == 1) {
1717 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1718 return getTrue(ITy);
1719 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1720 return getTrue(ITy);
1721 }
1722 }
1723 if (CI1V.getBoolValue() && isNUW) {
1724 if (Delta == 2)
1725 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1726 return getTrue(ITy);
1727 if (Delta == 1)
1728 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1729 return getTrue(ITy);
1730 }
1731
1732 return nullptr;
1733}
1734
Sanjay Patel472cc782016-01-11 22:14:42 +00001735/// Given operands for an Or, see if we can fold the result.
1736/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001737static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1738 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001739 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001740 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1741 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001742
Chris Lattnera71e9d62009-11-10 00:55:12 +00001743 // Canonicalize the constant to the RHS.
1744 std::swap(Op0, Op1);
1745 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001746
Chris Lattnera71e9d62009-11-10 00:55:12 +00001747 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001748 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001749 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001750
Chris Lattnera71e9d62009-11-10 00:55:12 +00001751 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001752 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001753 return Op0;
1754
Duncan Sandsc89ac072010-11-17 18:52:15 +00001755 // X | 0 = X
1756 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001757 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001758
Duncan Sandsc89ac072010-11-17 18:52:15 +00001759 // X | -1 = -1
1760 if (match(Op1, m_AllOnes()))
1761 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001762
Chris Lattnera71e9d62009-11-10 00:55:12 +00001763 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001764 if (match(Op0, m_Not(m_Specific(Op1))) ||
1765 match(Op1, m_Not(m_Specific(Op0))))
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 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001769 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001770 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001771 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001772 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001773
Chris Lattnera71e9d62009-11-10 00:55:12 +00001774 // A | (A & ?) = A
1775 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001776 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001777 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001778
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001779 // ~(A & ?) | A = -1
1780 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781 (A == Op1 || B == Op1))
1782 return Constant::getAllOnesValue(Op1->getType());
1783
1784 // A | ~(A & ?) = -1
1785 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1786 (A == Op0 || B == Op0))
1787 return Constant::getAllOnesValue(Op0->getType());
1788
David Majnemera315bd82014-09-15 08:15:28 +00001789 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1790 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1791 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1792 return V;
1793 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1794 return V;
1795 }
1796 }
1797
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001798 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001799 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1800 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001801 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001802
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001803 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001804 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1805 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001806 return V;
1807
Duncan Sandsb0579e92010-11-10 13:00:08 +00001808 // If the operation is with the result of a select instruction, check whether
1809 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001810 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001811 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001812 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001813 return V;
1814
Nick Lewycky8561a492014-06-19 03:51:46 +00001815 // (A & C)|(B & D)
1816 Value *C = nullptr, *D = nullptr;
1817 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1819 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1821 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1822 // (A & C1)|(B & C2)
1823 // If we have: ((V + N) & C1) | (V & C2)
1824 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1825 // replace with V+N.
1826 Value *V1, *V2;
1827 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1828 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1829 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001830 if (V1 == B &&
1831 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001832 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001833 if (V2 == B &&
1834 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001835 return A;
1836 }
1837 // Or commutes, try both ways.
1838 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1839 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1840 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001841 if (V1 == A &&
1842 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001843 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001844 if (V2 == A &&
1845 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001846 return B;
1847 }
1848 }
1849 }
1850
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001851 // If the operation is with the result of a phi instruction, check whether
1852 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001853 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001854 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001855 return V;
1856
Craig Topper9f008862014-04-15 04:59:12 +00001857 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001858}
1859
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001861 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001862 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001863 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001864 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001865 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001866}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001867
Sanjay Patel472cc782016-01-11 22:14:42 +00001868/// Given operands for a Xor, see if we can fold the result.
1869/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001870static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1871 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001872 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001873 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1874 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001875
1876 // Canonicalize the constant to the RHS.
1877 std::swap(Op0, Op1);
1878 }
1879
1880 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001881 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001882 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001883
1884 // A ^ 0 = A
1885 if (match(Op1, m_Zero()))
1886 return Op0;
1887
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001888 // A ^ A = 0
1889 if (Op0 == Op1)
1890 return Constant::getNullValue(Op0->getType());
1891
Duncan Sandsc89ac072010-11-17 18:52:15 +00001892 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001893 if (match(Op0, m_Not(m_Specific(Op1))) ||
1894 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001895 return Constant::getAllOnesValue(Op0->getType());
1896
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001897 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001898 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1899 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001900 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001901
Duncan Sandsb238de02010-11-19 09:20:39 +00001902 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1903 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1904 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1905 // only if B and C are equal. If B and C are equal then (since we assume
1906 // that operands have already been simplified) "select(cond, B, C)" should
1907 // have been simplified to the common value of B and C already. Analysing
1908 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1909 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001910
Craig Topper9f008862014-04-15 04:59:12 +00001911 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001912}
1913
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001914Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001915 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001916 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001917 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001918 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001919 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001920}
1921
Chris Lattner229907c2011-07-18 04:54:35 +00001922static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001923 return CmpInst::makeCmpResultType(Op->getType());
1924}
1925
Sanjay Patel472cc782016-01-11 22:14:42 +00001926/// Rummage around inside V looking for something equivalent to the comparison
1927/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1928/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001929static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1930 Value *LHS, Value *RHS) {
1931 SelectInst *SI = dyn_cast<SelectInst>(V);
1932 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001933 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001934 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1935 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001936 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001937 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1938 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1939 return Cmp;
1940 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1941 LHS == CmpRHS && RHS == CmpLHS)
1942 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001943 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001944}
1945
Dan Gohman9631d902013-02-01 00:49:06 +00001946// A significant optimization not implemented here is assuming that alloca
1947// addresses are not equal to incoming argument values. They don't *alias*,
1948// as we say, but that doesn't mean they aren't equal, so we take a
1949// conservative approach.
1950//
1951// This is inspired in part by C++11 5.10p1:
1952// "Two pointers of the same type compare equal if and only if they are both
1953// null, both point to the same function, or both represent the same
1954// address."
1955//
1956// This is pretty permissive.
1957//
1958// It's also partly due to C11 6.5.9p6:
1959// "Two pointers compare equal if and only if both are null pointers, both are
1960// pointers to the same object (including a pointer to an object and a
1961// subobject at its beginning) or function, both are pointers to one past the
1962// last element of the same array object, or one is a pointer to one past the
1963// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001964// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001965// object in the address space.)
1966//
1967// C11's version is more restrictive, however there's no reason why an argument
1968// couldn't be a one-past-the-end value for a stack object in the caller and be
1969// equal to the beginning of a stack object in the callee.
1970//
1971// If the C and C++ standards are ever made sufficiently restrictive in this
1972// area, it may be possible to update LLVM's semantics accordingly and reinstate
1973// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00001974static Constant *
1975computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1976 const DominatorTree *DT, CmpInst::Predicate Pred,
1977 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001978 // First, skip past any trivial no-ops.
1979 LHS = LHS->stripPointerCasts();
1980 RHS = RHS->stripPointerCasts();
1981
1982 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00001983 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001984 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1985 return ConstantInt::get(GetCompareTy(LHS),
1986 !CmpInst::isTrueWhenEqual(Pred));
1987
Chandler Carruth8059c842012-03-25 21:28:14 +00001988 // We can only fold certain predicates on pointer comparisons.
1989 switch (Pred) {
1990 default:
Craig Topper9f008862014-04-15 04:59:12 +00001991 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001992
1993 // Equality comaprisons are easy to fold.
1994 case CmpInst::ICMP_EQ:
1995 case CmpInst::ICMP_NE:
1996 break;
1997
1998 // We can only handle unsigned relational comparisons because 'inbounds' on
1999 // a GEP only protects against unsigned wrapping.
2000 case CmpInst::ICMP_UGT:
2001 case CmpInst::ICMP_UGE:
2002 case CmpInst::ICMP_ULT:
2003 case CmpInst::ICMP_ULE:
2004 // However, we have to switch them to their signed variants to handle
2005 // negative indices from the base pointer.
2006 Pred = ICmpInst::getSignedPredicate(Pred);
2007 break;
2008 }
2009
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002010 // Strip off any constant offsets so that we can reason about them.
2011 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2012 // here and compare base addresses like AliasAnalysis does, however there are
2013 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2014 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2015 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002016 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2017 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002018
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002019 // If LHS and RHS are related via constant offsets to the same base
2020 // value, we can replace it with an icmp which just compares the offsets.
2021 if (LHS == RHS)
2022 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002023
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002024 // Various optimizations for (in)equality comparisons.
2025 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2026 // Different non-empty allocations that exist at the same time have
2027 // different addresses (if the program can tell). Global variables always
2028 // exist, so they always exist during the lifetime of each other and all
2029 // allocas. Two different allocas usually have different addresses...
2030 //
2031 // However, if there's an @llvm.stackrestore dynamically in between two
2032 // allocas, they may have the same address. It's tempting to reduce the
2033 // scope of the problem by only looking at *static* allocas here. That would
2034 // cover the majority of allocas while significantly reducing the likelihood
2035 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2036 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2037 // an entry block. Also, if we have a block that's not attached to a
2038 // function, we can't tell if it's "static" under the current definition.
2039 // Theoretically, this problem could be fixed by creating a new kind of
2040 // instruction kind specifically for static allocas. Such a new instruction
2041 // could be required to be at the top of the entry block, thus preventing it
2042 // from being subject to a @llvm.stackrestore. Instcombine could even
2043 // convert regular allocas into these special allocas. It'd be nifty.
2044 // However, until then, this problem remains open.
2045 //
2046 // So, we'll assume that two non-empty allocas have different addresses
2047 // for now.
2048 //
2049 // With all that, if the offsets are within the bounds of their allocations
2050 // (and not one-past-the-end! so we can't use inbounds!), and their
2051 // allocations aren't the same, the pointers are not equal.
2052 //
2053 // Note that it's not necessary to check for LHS being a global variable
2054 // address, due to canonicalization and constant folding.
2055 if (isa<AllocaInst>(LHS) &&
2056 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002057 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2058 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002059 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002060 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002061 getObjectSize(LHS, LHSSize, DL, TLI) &&
2062 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002063 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2064 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002065 if (!LHSOffsetValue.isNegative() &&
2066 !RHSOffsetValue.isNegative() &&
2067 LHSOffsetValue.ult(LHSSize) &&
2068 RHSOffsetValue.ult(RHSSize)) {
2069 return ConstantInt::get(GetCompareTy(LHS),
2070 !CmpInst::isTrueWhenEqual(Pred));
2071 }
2072 }
2073
2074 // Repeat the above check but this time without depending on DataLayout
2075 // or being able to compute a precise size.
2076 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2077 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2078 LHSOffset->isNullValue() &&
2079 RHSOffset->isNullValue())
2080 return ConstantInt::get(GetCompareTy(LHS),
2081 !CmpInst::isTrueWhenEqual(Pred));
2082 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002083
2084 // Even if an non-inbounds GEP occurs along the path we can still optimize
2085 // equality comparisons concerning the result. We avoid walking the whole
2086 // chain again by starting where the last calls to
2087 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002088 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2089 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002090 if (LHS == RHS)
2091 return ConstantExpr::getICmp(Pred,
2092 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2093 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002094
2095 // If one side of the equality comparison must come from a noalias call
2096 // (meaning a system memory allocation function), and the other side must
2097 // come from a pointer that cannot overlap with dynamically-allocated
2098 // memory within the lifetime of the current function (allocas, byval
2099 // arguments, globals), then determine the comparison result here.
2100 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2101 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2102 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2103
2104 // Is the set of underlying objects all noalias calls?
2105 auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
Craig Topperb4b66d02015-11-29 04:37:14 +00002106 return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002107 };
2108
2109 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002110 // noalias calls. For allocas, we consider only static ones (dynamic
2111 // allocas might be transformed into calls to malloc not simultaneously
2112 // live with the compared-to allocation). For globals, we exclude symbols
2113 // that might be resolve lazily to symbols in another dynamically-loaded
2114 // library (and, thus, could be malloc'ed by the implementation).
Hal Finkelafcd8db2014-12-01 23:38:06 +00002115 auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002116 return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2117 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2118 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2119 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2120 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002121 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002122 !GV->isThreadLocal();
2123 if (const Argument *A = dyn_cast<Argument>(V))
2124 return A->hasByValAttr();
2125 return false;
2126 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002127 };
2128
2129 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2130 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2131 return ConstantInt::get(GetCompareTy(LHS),
2132 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002133
2134 // Fold comparisons for non-escaping pointer even if the allocation call
2135 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2136 // dynamic allocation call could be either of the operands.
2137 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002138 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002139 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002140 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002141 MI = RHS;
2142 // FIXME: We should also fold the compare when the pointer escapes, but the
2143 // compare dominates the pointer escape
2144 if (MI && !PointerMayBeCaptured(MI, true, true))
2145 return ConstantInt::get(GetCompareTy(LHS),
2146 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002147 }
2148
2149 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002150 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002151}
Chris Lattner01990f02012-02-24 19:01:58 +00002152
Sanjay Patel472cc782016-01-11 22:14:42 +00002153/// Given operands for an ICmpInst, see if we can fold the result.
2154/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002155static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002156 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00002157 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002158 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002159
Chris Lattnera71e9d62009-11-10 00:55:12 +00002160 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002161 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002162 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002163
2164 // If we have a constant, make sure it is on the RHS.
2165 std::swap(LHS, RHS);
2166 Pred = CmpInst::getSwappedPredicate(Pred);
2167 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002168
Chris Lattner229907c2011-07-18 04:54:35 +00002169 Type *ITy = GetCompareTy(LHS); // The return type.
2170 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002171
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002172 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002173 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2174 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002175 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002176 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002177
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002178 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00002179 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002180 switch (Pred) {
2181 default: break;
2182 case ICmpInst::ICMP_EQ:
2183 // X == 1 -> X
2184 if (match(RHS, m_One()))
2185 return LHS;
2186 break;
2187 case ICmpInst::ICMP_NE:
2188 // X != 0 -> X
2189 if (match(RHS, m_Zero()))
2190 return LHS;
2191 break;
2192 case ICmpInst::ICMP_UGT:
2193 // X >u 0 -> X
2194 if (match(RHS, m_Zero()))
2195 return LHS;
2196 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002197 case ICmpInst::ICMP_UGE: {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002198 // X >=u 1 -> X
2199 if (match(RHS, m_One()))
2200 return LHS;
Chad Rosier41dd31f2016-04-20 19:15:26 +00002201 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002202 return getTrue(ITy);
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002203 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002204 }
2205 case ICmpInst::ICMP_SGE: {
Junmo Park53470fc2016-04-05 21:14:31 +00002206 /// For signed comparison, the values for an i1 are 0 and -1
Philip Reamesdbbd7792015-10-29 03:19:10 +00002207 /// respectively. This maps into a truth table of:
2208 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2209 /// 0 | 0 | 1 (0 >= 0) | 1
2210 /// 0 | 1 | 1 (0 >= -1) | 1
2211 /// 1 | 0 | 0 (-1 >= 0) | 0
2212 /// 1 | 1 | 1 (-1 >= -1) | 1
Chad Rosier41dd31f2016-04-20 19:15:26 +00002213 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reamesdbbd7792015-10-29 03:19:10 +00002214 return getTrue(ITy);
2215 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002216 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002217 case ICmpInst::ICMP_SLT:
2218 // X <s 0 -> X
2219 if (match(RHS, m_Zero()))
2220 return LHS;
2221 break;
2222 case ICmpInst::ICMP_SLE:
2223 // X <=s -1 -> X
2224 if (match(RHS, m_One()))
2225 return LHS;
2226 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002227 case ICmpInst::ICMP_ULE: {
Chad Rosier41dd31f2016-04-20 19:15:26 +00002228 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002229 return getTrue(ITy);
2230 break;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002231 }
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002232 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002233 }
2234
Duncan Sandsd3951082011-01-25 09:38:29 +00002235 // If we are comparing with zero then try hard since this is a common case.
2236 if (match(RHS, m_Zero())) {
2237 bool LHSKnownNonNegative, LHSKnownNegative;
2238 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002239 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00002240 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002241 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002242 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002243 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002244 case ICmpInst::ICMP_EQ:
2245 case ICmpInst::ICMP_ULE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002246 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002247 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002248 break;
2249 case ICmpInst::ICMP_NE:
2250 case ICmpInst::ICMP_UGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002251 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002252 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002253 break;
2254 case ICmpInst::ICMP_SLT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002255 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2256 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002257 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002258 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002259 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002260 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002261 break;
2262 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002263 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2264 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002265 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002266 return getTrue(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002267 if (LHSKnownNonNegative &&
2268 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002269 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002270 break;
2271 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002272 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2273 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002274 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002275 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002276 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002277 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002278 break;
2279 case ICmpInst::ICMP_SGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002280 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2281 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002282 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002283 return getFalse(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002284 if (LHSKnownNonNegative &&
2285 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002286 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002287 break;
2288 }
2289 }
2290
2291 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002292 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002293 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2294 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2295 if (RHS_CR.isEmptySet())
2296 return ConstantInt::getFalse(CI->getContext());
2297 if (RHS_CR.isFullSet())
2298 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002299
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002300 // Many binary operators with constant RHS have easy to compute constant
2301 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002302 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002303 APInt Lower = APInt(Width, 0);
2304 APInt Upper = APInt(Width, 0);
2305 ConstantInt *CI2;
2306 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2307 // 'urem x, CI2' produces [0, CI2).
2308 Upper = CI2->getValue();
2309 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2310 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2311 Upper = CI2->getValue().abs();
2312 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002313 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2314 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002315 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002316 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2317 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2318 APInt NegOne = APInt::getAllOnesValue(Width);
2319 if (!CI2->isZero())
2320 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002321 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00002322 if (CI2->isMinSignedValue()) {
2323 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2324 Lower = CI2->getValue();
2325 Upper = Lower.lshr(1) + 1;
2326 } else {
2327 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2328 Upper = CI2->getValue().abs() + 1;
2329 Lower = (-Upper) + 1;
2330 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002331 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002332 APInt IntMin = APInt::getSignedMinValue(Width);
2333 APInt IntMax = APInt::getSignedMaxValue(Width);
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002334 const APInt &Val = CI2->getValue();
David Majnemeraf9180f2014-07-14 20:38:45 +00002335 if (Val.isAllOnesValue()) {
2336 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2337 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2338 Lower = IntMin + 1;
2339 Upper = IntMax + 1;
2340 } else if (Val.countLeadingZeros() < Width - 1) {
2341 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2342 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002343 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00002344 Upper = IntMax.sdiv(Val);
2345 if (Lower.sgt(Upper))
2346 std::swap(Lower, Upper);
2347 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00002348 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002349 }
David Majnemerd6d16712014-08-27 18:03:46 +00002350 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2351 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2352 Lower = CI2->getValue();
2353 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2354 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2355 if (CI2->isNegative()) {
2356 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2357 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2358 Lower = CI2->getValue().shl(ShiftAmount);
2359 Upper = CI2->getValue() + 1;
2360 } else {
2361 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2362 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2363 Lower = CI2->getValue();
2364 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2365 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002366 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2367 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2368 APInt NegOne = APInt::getAllOnesValue(Width);
2369 if (CI2->getValue().ult(Width))
2370 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002371 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2372 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2373 unsigned ShiftAmount = Width - 1;
2374 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2375 ShiftAmount = CI2->getValue().countTrailingZeros();
2376 Lower = CI2->getValue().lshr(ShiftAmount);
2377 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002378 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2379 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2380 APInt IntMin = APInt::getSignedMinValue(Width);
2381 APInt IntMax = APInt::getSignedMaxValue(Width);
2382 if (CI2->getValue().ult(Width)) {
2383 Lower = IntMin.ashr(CI2->getValue());
2384 Upper = IntMax.ashr(CI2->getValue()) + 1;
2385 }
David Majnemer78910fc2014-05-16 17:14:03 +00002386 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2387 unsigned ShiftAmount = Width - 1;
2388 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2389 ShiftAmount = CI2->getValue().countTrailingZeros();
2390 if (CI2->isNegative()) {
2391 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2392 Lower = CI2->getValue();
2393 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2394 } else {
2395 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2396 Lower = CI2->getValue().ashr(ShiftAmount);
2397 Upper = CI2->getValue() + 1;
2398 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002399 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2400 // 'or x, CI2' produces [CI2, UINT_MAX].
2401 Lower = CI2->getValue();
2402 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2403 // 'and x, CI2' produces [0, CI2].
2404 Upper = CI2->getValue() + 1;
David Majnemer2df38cd2015-08-20 23:01:41 +00002405 } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2406 // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2407 Lower = CI2->getValue();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002408 }
Chen Li5cd6dee2015-09-23 17:58:44 +00002409
2410 ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2411 : ConstantRange(Width, true);
2412
2413 if (auto *I = dyn_cast<Instruction>(LHS))
2414 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002415 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
Chen Li5cd6dee2015-09-23 17:58:44 +00002416
2417 if (!LHS_CR.isFullSet()) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002418 if (RHS_CR.contains(LHS_CR))
2419 return ConstantInt::getTrue(RHS->getContext());
2420 if (RHS_CR.inverse().contains(LHS_CR))
2421 return ConstantInt::getFalse(RHS->getContext());
2422 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002423 }
2424
Chen Li7452d952015-09-26 03:26:47 +00002425 // If both operands have range metadata, use the metadata
2426 // to simplify the comparison.
2427 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2428 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2429 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2430
2431 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2432 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002433 auto RHS_CR = getConstantRangeFromMetadata(
2434 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2435 auto LHS_CR = getConstantRangeFromMetadata(
2436 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00002437
2438 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2439 if (Satisfied_CR.contains(LHS_CR))
2440 return ConstantInt::getTrue(RHS->getContext());
2441
2442 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2443 CmpInst::getInversePredicate(Pred), RHS_CR);
2444 if (InversedSatisfied_CR.contains(LHS_CR))
2445 return ConstantInt::getFalse(RHS->getContext());
2446 }
2447 }
2448
Duncan Sands8fb2c382011-01-20 13:21:55 +00002449 // Compare of cast, for example (zext X) != 0 -> X != 0
2450 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2451 Instruction *LI = cast<CastInst>(LHS);
2452 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002453 Type *SrcTy = SrcOp->getType();
2454 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002455
2456 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2457 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002458 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2459 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002460 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2461 // Transfer the cast to the constant.
2462 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2463 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002464 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002465 return V;
2466 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2467 if (RI->getOperand(0)->getType() == SrcTy)
2468 // Compare without the cast.
2469 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002470 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002471 return V;
2472 }
2473 }
2474
2475 if (isa<ZExtInst>(LHS)) {
2476 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2477 // same type.
2478 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2479 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2480 // Compare X and Y. Note that signed predicates become unsigned.
2481 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002482 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002483 MaxRecurse-1))
2484 return V;
2485 }
2486 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2487 // too. If not, then try to deduce the result of the comparison.
2488 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2489 // Compute the constant that would happen if we truncated to SrcTy then
2490 // reextended to DstTy.
2491 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2492 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2493
2494 // If the re-extended constant didn't change then this is effectively
2495 // also a case of comparing two zero-extended values.
2496 if (RExt == CI && MaxRecurse)
2497 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002498 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002499 return V;
2500
2501 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2502 // there. Use this to work out the result of the comparison.
2503 if (RExt != CI) {
2504 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002505 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002506 // LHS <u RHS.
2507 case ICmpInst::ICMP_EQ:
2508 case ICmpInst::ICMP_UGT:
2509 case ICmpInst::ICMP_UGE:
2510 return ConstantInt::getFalse(CI->getContext());
2511
2512 case ICmpInst::ICMP_NE:
2513 case ICmpInst::ICMP_ULT:
2514 case ICmpInst::ICMP_ULE:
2515 return ConstantInt::getTrue(CI->getContext());
2516
2517 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2518 // is non-negative then LHS <s RHS.
2519 case ICmpInst::ICMP_SGT:
2520 case ICmpInst::ICMP_SGE:
2521 return CI->getValue().isNegative() ?
2522 ConstantInt::getTrue(CI->getContext()) :
2523 ConstantInt::getFalse(CI->getContext());
2524
2525 case ICmpInst::ICMP_SLT:
2526 case ICmpInst::ICMP_SLE:
2527 return CI->getValue().isNegative() ?
2528 ConstantInt::getFalse(CI->getContext()) :
2529 ConstantInt::getTrue(CI->getContext());
2530 }
2531 }
2532 }
2533 }
2534
2535 if (isa<SExtInst>(LHS)) {
2536 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2537 // same type.
2538 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2539 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2540 // Compare X and Y. Note that the predicate does not change.
2541 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002542 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002543 return V;
2544 }
2545 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2546 // too. If not, then try to deduce the result of the comparison.
2547 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2548 // Compute the constant that would happen if we truncated to SrcTy then
2549 // reextended to DstTy.
2550 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2551 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2552
2553 // If the re-extended constant didn't change then this is effectively
2554 // also a case of comparing two sign-extended values.
2555 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002556 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002557 return V;
2558
2559 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2560 // bits there. Use this to work out the result of the comparison.
2561 if (RExt != CI) {
2562 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002563 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002564 case ICmpInst::ICMP_EQ:
2565 return ConstantInt::getFalse(CI->getContext());
2566 case ICmpInst::ICMP_NE:
2567 return ConstantInt::getTrue(CI->getContext());
2568
2569 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2570 // LHS >s RHS.
2571 case ICmpInst::ICMP_SGT:
2572 case ICmpInst::ICMP_SGE:
2573 return CI->getValue().isNegative() ?
2574 ConstantInt::getTrue(CI->getContext()) :
2575 ConstantInt::getFalse(CI->getContext());
2576 case ICmpInst::ICMP_SLT:
2577 case ICmpInst::ICMP_SLE:
2578 return CI->getValue().isNegative() ?
2579 ConstantInt::getFalse(CI->getContext()) :
2580 ConstantInt::getTrue(CI->getContext());
2581
2582 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2583 // LHS >u RHS.
2584 case ICmpInst::ICMP_UGT:
2585 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002586 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002587 if (MaxRecurse)
2588 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2589 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002590 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002591 return V;
2592 break;
2593 case ICmpInst::ICMP_ULT:
2594 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002595 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002596 if (MaxRecurse)
2597 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2598 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002599 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002600 return V;
2601 break;
2602 }
2603 }
2604 }
2605 }
2606 }
2607
James Molloy1d88d6f2015-10-22 13:18:42 +00002608 // icmp eq|ne X, Y -> false|true if X != Y
2609 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2610 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2611 LLVMContext &Ctx = LHS->getType()->getContext();
2612 return Pred == ICmpInst::ICMP_NE ?
2613 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2614 }
Junmo Park53470fc2016-04-05 21:14:31 +00002615
Duncan Sandsd114ab32011-02-13 17:15:40 +00002616 // Special logic for binary operators.
2617 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2618 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2619 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002620 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002621 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002622 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2623 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2624 if (LBO && LBO->getOpcode() == Instruction::Add) {
2625 A = LBO->getOperand(0); B = LBO->getOperand(1);
2626 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2627 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2628 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2629 }
2630 if (RBO && RBO->getOpcode() == Instruction::Add) {
2631 C = RBO->getOperand(0); D = RBO->getOperand(1);
2632 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2633 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2634 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2635 }
2636
2637 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2638 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2639 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2640 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002641 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002642 return V;
2643
2644 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2645 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2646 if (Value *V = SimplifyICmpInst(Pred,
2647 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002648 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002649 return V;
2650
2651 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2652 if (A && C && (A == C || A == D || B == C || B == D) &&
2653 NoLHSWrapProblem && NoRHSWrapProblem) {
2654 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002655 Value *Y, *Z;
2656 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002657 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002658 Y = B;
2659 Z = D;
2660 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002661 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002662 Y = B;
2663 Z = C;
2664 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002665 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002666 Y = A;
2667 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002668 } else {
2669 assert(B == D);
2670 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002671 Y = A;
2672 Z = C;
2673 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002674 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002675 return V;
2676 }
2677 }
2678
Nick Lewycky762f8a82016-04-21 00:53:14 +00002679 {
2680 Value *Y = nullptr;
2681 // icmp pred (or X, Y), X
2682 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2683 if (Pred == ICmpInst::ICMP_ULT)
2684 return getFalse(ITy);
2685 if (Pred == ICmpInst::ICMP_UGE)
2686 return getTrue(ITy);
2687
2688 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2689 bool RHSKnownNonNegative, RHSKnownNegative;
2690 bool YKnownNonNegative, YKnownNegative;
2691 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2692 Q.AC, Q.CxtI, Q.DT);
2693 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2694 Q.CxtI, Q.DT);
2695 if (RHSKnownNonNegative && YKnownNegative)
2696 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2697 if (RHSKnownNegative || YKnownNonNegative)
2698 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2699 }
2700 }
2701 // icmp pred X, (or X, Y)
2702 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2703 if (Pred == ICmpInst::ICMP_ULE)
2704 return getTrue(ITy);
2705 if (Pred == ICmpInst::ICMP_UGT)
2706 return getFalse(ITy);
2707
2708 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2709 bool LHSKnownNonNegative, LHSKnownNegative;
2710 bool YKnownNonNegative, YKnownNegative;
2711 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2712 Q.AC, Q.CxtI, Q.DT);
2713 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2714 Q.CxtI, Q.DT);
2715 if (LHSKnownNonNegative && YKnownNegative)
2716 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2717 if (LHSKnownNegative || YKnownNonNegative)
2718 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2719 }
2720 }
David Majnemerbd9ce4e2014-11-25 02:55:48 +00002721 }
2722
2723 // icmp pred (and X, Y), X
2724 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2725 m_And(m_Specific(RHS), m_Value())))) {
2726 if (Pred == ICmpInst::ICMP_UGT)
2727 return getFalse(ITy);
2728 if (Pred == ICmpInst::ICMP_ULE)
2729 return getTrue(ITy);
2730 }
2731 // icmp pred X, (and X, Y)
2732 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2733 m_And(m_Specific(LHS), m_Value())))) {
2734 if (Pred == ICmpInst::ICMP_UGE)
2735 return getTrue(ITy);
2736 if (Pred == ICmpInst::ICMP_ULT)
2737 return getFalse(ITy);
2738 }
2739
David Majnemer2d6c0232014-05-14 20:16:28 +00002740 // 0 - (zext X) pred C
2741 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2742 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2743 if (RHSC->getValue().isStrictlyPositive()) {
2744 if (Pred == ICmpInst::ICMP_SLT)
2745 return ConstantInt::getTrue(RHSC->getContext());
2746 if (Pred == ICmpInst::ICMP_SGE)
2747 return ConstantInt::getFalse(RHSC->getContext());
2748 if (Pred == ICmpInst::ICMP_EQ)
2749 return ConstantInt::getFalse(RHSC->getContext());
2750 if (Pred == ICmpInst::ICMP_NE)
2751 return ConstantInt::getTrue(RHSC->getContext());
2752 }
2753 if (RHSC->getValue().isNonNegative()) {
2754 if (Pred == ICmpInst::ICMP_SLE)
2755 return ConstantInt::getTrue(RHSC->getContext());
2756 if (Pred == ICmpInst::ICMP_SGT)
2757 return ConstantInt::getFalse(RHSC->getContext());
2758 }
2759 }
2760 }
2761
Nick Lewycky35aeea92013-07-12 23:42:57 +00002762 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002763 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002764 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002765 switch (Pred) {
2766 default:
2767 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002768 case ICmpInst::ICMP_SGT:
2769 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002770 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2771 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002772 if (!KnownNonNegative)
2773 break;
2774 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002775 case ICmpInst::ICMP_EQ:
2776 case ICmpInst::ICMP_UGT:
2777 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002778 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002779 case ICmpInst::ICMP_SLT:
2780 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002781 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2782 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002783 if (!KnownNonNegative)
2784 break;
2785 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002786 case ICmpInst::ICMP_NE:
2787 case ICmpInst::ICMP_ULT:
2788 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002789 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002790 }
2791 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002792
2793 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002794 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2795 bool KnownNonNegative, KnownNegative;
2796 switch (Pred) {
2797 default:
2798 break;
2799 case ICmpInst::ICMP_SGT:
2800 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002801 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2802 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002803 if (!KnownNonNegative)
2804 break;
2805 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002806 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002807 case ICmpInst::ICMP_UGT:
2808 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002809 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002810 case ICmpInst::ICMP_SLT:
2811 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002812 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2813 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002814 if (!KnownNonNegative)
2815 break;
2816 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002817 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002818 case ICmpInst::ICMP_ULT:
2819 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002820 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002821 }
2822 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002823
David Majnemer3af5bf32016-01-21 18:55:54 +00002824 // x >> y <=u x
Duncan Sands92af0a82011-10-28 18:17:44 +00002825 // x udiv y <=u x.
David Majnemer3af5bf32016-01-21 18:55:54 +00002826 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2827 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2828 // icmp pred (X op Y), X
Duncan Sands92af0a82011-10-28 18:17:44 +00002829 if (Pred == ICmpInst::ICMP_UGT)
2830 return getFalse(ITy);
2831 if (Pred == ICmpInst::ICMP_ULE)
2832 return getTrue(ITy);
2833 }
2834
David Majnemer76d06bc2014-08-28 03:34:28 +00002835 // handle:
2836 // CI2 << X == CI
2837 // CI2 << X != CI
2838 //
2839 // where CI2 is a power of 2 and CI isn't
2840 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2841 const APInt *CI2Val, *CIVal = &CI->getValue();
2842 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2843 CI2Val->isPowerOf2()) {
2844 if (!CIVal->isPowerOf2()) {
2845 // CI2 << X can equal zero in some circumstances,
2846 // this simplification is unsafe if CI is zero.
2847 //
2848 // We know it is safe if:
2849 // - The shift is nsw, we can't shift out the one bit.
2850 // - The shift is nuw, we can't shift out the one bit.
2851 // - CI2 is one
2852 // - CI isn't zero
2853 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2854 *CI2Val == 1 || !CI->isZero()) {
2855 if (Pred == ICmpInst::ICMP_EQ)
2856 return ConstantInt::getFalse(RHS->getContext());
2857 if (Pred == ICmpInst::ICMP_NE)
2858 return ConstantInt::getTrue(RHS->getContext());
2859 }
2860 }
2861 if (CIVal->isSignBit() && *CI2Val == 1) {
2862 if (Pred == ICmpInst::ICMP_UGT)
2863 return ConstantInt::getFalse(RHS->getContext());
2864 if (Pred == ICmpInst::ICMP_ULE)
2865 return ConstantInt::getTrue(RHS->getContext());
2866 }
2867 }
2868 }
2869
Nick Lewycky9719a712011-03-05 05:19:11 +00002870 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2871 LBO->getOperand(1) == RBO->getOperand(1)) {
2872 switch (LBO->getOpcode()) {
2873 default: break;
2874 case Instruction::UDiv:
2875 case Instruction::LShr:
2876 if (ICmpInst::isSigned(Pred))
2877 break;
2878 // fall-through
2879 case Instruction::SDiv:
2880 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002881 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002882 break;
2883 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002884 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002885 return V;
2886 break;
2887 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002888 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002889 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2890 if (!NUW && !NSW)
2891 break;
2892 if (!NSW && ICmpInst::isSigned(Pred))
2893 break;
2894 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002895 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002896 return V;
2897 break;
2898 }
2899 }
2900 }
2901
Duncan Sands0a9c1242011-05-03 19:53:10 +00002902 // Simplify comparisons involving max/min.
2903 Value *A, *B;
2904 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002905 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002906
Duncan Sandsa2287852011-05-04 16:05:05 +00002907 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002908 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2909 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002910 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002911 // We analyze this as smax(A, B) pred A.
2912 P = Pred;
2913 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2914 (A == LHS || B == LHS)) {
2915 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002916 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002917 // We analyze this as smax(A, B) swapped-pred A.
2918 P = CmpInst::getSwappedPredicate(Pred);
2919 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2920 (A == RHS || B == RHS)) {
2921 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002922 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002923 // We analyze this as smax(-A, -B) swapped-pred -A.
2924 // Note that we do not need to actually form -A or -B thanks to EqP.
2925 P = CmpInst::getSwappedPredicate(Pred);
2926 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2927 (A == LHS || B == LHS)) {
2928 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002929 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002930 // We analyze this as smax(-A, -B) pred -A.
2931 // Note that we do not need to actually form -A or -B thanks to EqP.
2932 P = Pred;
2933 }
2934 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2935 // Cases correspond to "max(A, B) p A".
2936 switch (P) {
2937 default:
2938 break;
2939 case CmpInst::ICMP_EQ:
2940 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002941 // Equivalent to "A EqP B". This may be the same as the condition tested
2942 // in the max/min; if so, we can just return that.
2943 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2944 return V;
2945 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2946 return V;
2947 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002948 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002949 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002950 return V;
2951 break;
2952 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002953 case CmpInst::ICMP_SGT: {
2954 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2955 // Equivalent to "A InvEqP B". This may be the same as the condition
2956 // tested in the max/min; if so, we can just return that.
2957 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2958 return V;
2959 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2960 return V;
2961 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002962 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002963 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002964 return V;
2965 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002966 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002967 case CmpInst::ICMP_SGE:
2968 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002969 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002970 case CmpInst::ICMP_SLT:
2971 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002972 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002973 }
2974 }
2975
Duncan Sandsa2287852011-05-04 16:05:05 +00002976 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002977 P = CmpInst::BAD_ICMP_PREDICATE;
2978 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2979 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002980 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002981 // We analyze this as umax(A, B) pred A.
2982 P = Pred;
2983 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2984 (A == LHS || B == LHS)) {
2985 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002986 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002987 // We analyze this as umax(A, B) swapped-pred A.
2988 P = CmpInst::getSwappedPredicate(Pred);
2989 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2990 (A == RHS || B == RHS)) {
2991 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002992 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002993 // We analyze this as umax(-A, -B) swapped-pred -A.
2994 // Note that we do not need to actually form -A or -B thanks to EqP.
2995 P = CmpInst::getSwappedPredicate(Pred);
2996 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2997 (A == LHS || B == LHS)) {
2998 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002999 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003000 // We analyze this as umax(-A, -B) pred -A.
3001 // Note that we do not need to actually form -A or -B thanks to EqP.
3002 P = Pred;
3003 }
3004 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3005 // Cases correspond to "max(A, B) p A".
3006 switch (P) {
3007 default:
3008 break;
3009 case CmpInst::ICMP_EQ:
3010 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003011 // Equivalent to "A EqP B". This may be the same as the condition tested
3012 // in the max/min; if so, we can just return that.
3013 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3014 return V;
3015 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3016 return V;
3017 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003018 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003019 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003020 return V;
3021 break;
3022 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003023 case CmpInst::ICMP_UGT: {
3024 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3025 // Equivalent to "A InvEqP B". This may be the same as the condition
3026 // tested in the max/min; if so, we can just return that.
3027 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3028 return V;
3029 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3030 return V;
3031 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003032 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003033 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003034 return V;
3035 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003036 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003037 case CmpInst::ICMP_UGE:
3038 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003039 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003040 case CmpInst::ICMP_ULT:
3041 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003042 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003043 }
3044 }
3045
Duncan Sandsa2287852011-05-04 16:05:05 +00003046 // Variants on "max(x,y) >= min(x,z)".
3047 Value *C, *D;
3048 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3049 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3050 (A == C || A == D || B == C || B == D)) {
3051 // max(x, ?) pred min(x, ?).
3052 if (Pred == CmpInst::ICMP_SGE)
3053 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003054 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003055 if (Pred == CmpInst::ICMP_SLT)
3056 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003057 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003058 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3059 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3060 (A == C || A == D || B == C || B == D)) {
3061 // min(x, ?) pred max(x, ?).
3062 if (Pred == CmpInst::ICMP_SLE)
3063 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003064 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003065 if (Pred == CmpInst::ICMP_SGT)
3066 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003067 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003068 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3069 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3070 (A == C || A == D || B == C || B == D)) {
3071 // max(x, ?) pred min(x, ?).
3072 if (Pred == CmpInst::ICMP_UGE)
3073 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003074 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003075 if (Pred == CmpInst::ICMP_ULT)
3076 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003077 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003078 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3079 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3080 (A == C || A == D || B == C || B == D)) {
3081 // min(x, ?) pred max(x, ?).
3082 if (Pred == CmpInst::ICMP_ULE)
3083 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003084 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003085 if (Pred == CmpInst::ICMP_UGT)
3086 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003087 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003088 }
3089
Chandler Carruth8059c842012-03-25 21:28:14 +00003090 // Simplify comparisons of related pointers using a powerful, recursive
3091 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003092 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003093 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003094 return C;
3095
Nick Lewycky3db143e2012-02-26 02:09:49 +00003096 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3097 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3098 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3099 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3100 (ICmpInst::isEquality(Pred) ||
3101 (GLHS->isInBounds() && GRHS->isInBounds() &&
3102 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3103 // The bases are equal and the indices are constant. Build a constant
3104 // expression GEP with the same indices and a null base pointer to see
3105 // what constant folding can make out of it.
3106 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3107 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003108 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3109 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003110
3111 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003112 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3113 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003114 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3115 }
3116 }
3117 }
3118
David Majnemer5854e9f2014-11-16 02:20:08 +00003119 // If a bit is known to be zero for A and known to be one for B,
3120 // then A and B cannot be equal.
3121 if (ICmpInst::isEquality(Pred)) {
3122 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3123 uint32_t BitWidth = CI->getBitWidth();
3124 APInt LHSKnownZero(BitWidth, 0);
3125 APInt LHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003126 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003127 Q.CxtI, Q.DT);
3128 const APInt &RHSVal = CI->getValue();
3129 if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3130 return Pred == ICmpInst::ICMP_EQ
3131 ? ConstantInt::getFalse(CI->getContext())
3132 : ConstantInt::getTrue(CI->getContext());
3133 }
3134 }
3135
Duncan Sandsf532d312010-11-07 16:12:23 +00003136 // If the comparison is with the result of a select instruction, check whether
3137 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003138 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003139 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003140 return V;
3141
3142 // If the comparison is with the result of a phi instruction, check whether
3143 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003144 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003145 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003146 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003147
Craig Topper9f008862014-04-15 04:59:12 +00003148 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003149}
3150
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003151Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003152 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003153 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003154 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003155 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003156 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003157 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003158}
3159
Sanjay Patel472cc782016-01-11 22:14:42 +00003160/// Given operands for an FCmpInst, see if we can fold the result.
3161/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003162static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003163 FastMathFlags FMF, const Query &Q,
3164 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003165 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3166 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3167
Chris Lattnera71e9d62009-11-10 00:55:12 +00003168 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003169 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003170 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003171
Chris Lattnera71e9d62009-11-10 00:55:12 +00003172 // If we have a constant, make sure it is on the RHS.
3173 std::swap(LHS, RHS);
3174 Pred = CmpInst::getSwappedPredicate(Pred);
3175 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003176
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003177 // Fold trivial predicates.
3178 if (Pred == FCmpInst::FCMP_FALSE)
3179 return ConstantInt::get(GetCompareTy(LHS), 0);
3180 if (Pred == FCmpInst::FCMP_TRUE)
3181 return ConstantInt::get(GetCompareTy(LHS), 1);
3182
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003183 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3184 if (FMF.noNaNs()) {
3185 if (Pred == FCmpInst::FCMP_UNO)
3186 return ConstantInt::get(GetCompareTy(LHS), 0);
3187 if (Pred == FCmpInst::FCMP_ORD)
3188 return ConstantInt::get(GetCompareTy(LHS), 1);
3189 }
3190
Mehdi Aminieb242a52015-03-09 03:20:25 +00003191 // fcmp pred x, undef and fcmp pred undef, x
3192 // fold to true if unordered, false if ordered
3193 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3194 // Choosing NaN for the undef will always make unordered comparison succeed
3195 // and ordered comparison fail.
3196 return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3197 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003198
3199 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003200 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003201 if (CmpInst::isTrueWhenEqual(Pred))
3202 return ConstantInt::get(GetCompareTy(LHS), 1);
3203 if (CmpInst::isFalseWhenEqual(Pred))
3204 return ConstantInt::get(GetCompareTy(LHS), 0);
3205 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003206
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003207 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003208 const ConstantFP *CFP = nullptr;
3209 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3210 if (RHS->getType()->isVectorTy())
3211 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3212 else
3213 CFP = dyn_cast<ConstantFP>(RHSC);
3214 }
3215 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003216 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003217 if (CFP->getValueAPF().isNaN()) {
3218 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3219 return ConstantInt::getFalse(CFP->getContext());
3220 assert(FCmpInst::isUnordered(Pred) &&
3221 "Comparison must be either ordered or unordered!");
3222 // True if unordered.
David Majnemer3ee5f342016-04-13 06:55:52 +00003223 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003224 }
3225 // Check whether the constant is an infinity.
3226 if (CFP->getValueAPF().isInfinity()) {
3227 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003228 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003229 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003230 // No value is ordered and less than negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003231 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003232 case FCmpInst::FCMP_UGE:
3233 // All values are unordered with or at least negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003234 return ConstantInt::get(GetCompareTy(LHS), 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003235 default:
3236 break;
3237 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003238 } else {
3239 switch (Pred) {
3240 case FCmpInst::FCMP_OGT:
3241 // No value is ordered and greater than infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003242 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003243 case FCmpInst::FCMP_ULE:
3244 // All values are unordered with and at most infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003245 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003246 default:
3247 break;
3248 }
3249 }
3250 }
3251 if (CFP->getValueAPF().isZero()) {
3252 switch (Pred) {
3253 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003254 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3255 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003256 break;
3257 case FCmpInst::FCMP_OLT:
3258 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003259 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3260 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003261 break;
3262 default:
3263 break;
3264 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003265 }
3266 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003267
Duncan Sandsa620bd12010-11-07 16:46:25 +00003268 // If the comparison is with the result of a select instruction, check whether
3269 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003270 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003271 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003272 return V;
3273
3274 // If the comparison is with the result of a phi instruction, check whether
3275 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003276 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003277 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003278 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003279
Craig Topper9f008862014-04-15 04:59:12 +00003280 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003281}
3282
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003283Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003284 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003285 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003286 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003287 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003288 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3289 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003290}
3291
Sanjay Patel472cc782016-01-11 22:14:42 +00003292/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003293static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3294 const Query &Q,
3295 unsigned MaxRecurse) {
3296 // Trivial replacement.
3297 if (V == Op)
3298 return RepOp;
3299
3300 auto *I = dyn_cast<Instruction>(V);
3301 if (!I)
3302 return nullptr;
3303
3304 // If this is a binary operator, try to simplify it with the replaced op.
3305 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3306 // Consider:
3307 // %cmp = icmp eq i32 %x, 2147483647
3308 // %add = add nsw i32 %x, 1
3309 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3310 //
3311 // We can't replace %sel with %add unless we strip away the flags.
3312 if (isa<OverflowingBinaryOperator>(B))
3313 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3314 return nullptr;
3315 if (isa<PossiblyExactOperator>(B))
3316 if (B->isExact())
3317 return nullptr;
3318
3319 if (MaxRecurse) {
3320 if (B->getOperand(0) == Op)
3321 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3322 MaxRecurse - 1);
3323 if (B->getOperand(1) == Op)
3324 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3325 MaxRecurse - 1);
3326 }
3327 }
3328
3329 // Same for CmpInsts.
3330 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3331 if (MaxRecurse) {
3332 if (C->getOperand(0) == Op)
3333 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3334 MaxRecurse - 1);
3335 if (C->getOperand(1) == Op)
3336 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3337 MaxRecurse - 1);
3338 }
3339 }
3340
3341 // TODO: We could hand off more cases to instsimplify here.
3342
3343 // If all operands are constant after substituting Op for RepOp then we can
3344 // constant fold the instruction.
3345 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3346 // Build a list of all constant operands.
3347 SmallVector<Constant *, 8> ConstOps;
3348 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3349 if (I->getOperand(i) == Op)
3350 ConstOps.push_back(CRepOp);
3351 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3352 ConstOps.push_back(COp);
3353 else
3354 break;
3355 }
3356
3357 // All operands were constants, fold it.
3358 if (ConstOps.size() == I->getNumOperands()) {
3359 if (CmpInst *C = dyn_cast<CmpInst>(I))
3360 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3361 ConstOps[1], Q.DL, Q.TLI);
3362
3363 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3364 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003365 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003366
Manuel Jacobe9024592016-01-21 06:33:22 +00003367 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003368 }
3369 }
3370
3371 return nullptr;
3372}
3373
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003374/// Try to simplify a select instruction when its condition operand is an
3375/// integer comparison where one operand of the compare is a constant.
3376static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3377 const APInt *Y, bool TrueWhenUnset) {
3378 const APInt *C;
3379
3380 // (X & Y) == 0 ? X & ~Y : X --> X
3381 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3382 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3383 *Y == ~*C)
3384 return TrueWhenUnset ? FalseVal : TrueVal;
3385
3386 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3387 // (X & Y) != 0 ? X : X & ~Y --> X
3388 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3389 *Y == ~*C)
3390 return TrueWhenUnset ? FalseVal : TrueVal;
3391
3392 if (Y->isPowerOf2()) {
3393 // (X & Y) == 0 ? X | Y : X --> X | Y
3394 // (X & Y) != 0 ? X | Y : X --> X
3395 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3396 *Y == *C)
3397 return TrueWhenUnset ? TrueVal : FalseVal;
3398
3399 // (X & Y) == 0 ? X : X | Y --> X
3400 // (X & Y) != 0 ? X : X | Y --> X | Y
3401 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3402 *Y == *C)
3403 return TrueWhenUnset ? TrueVal : FalseVal;
3404 }
3405
3406 return nullptr;
3407}
3408
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003409/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3410/// eq/ne.
3411static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3412 Value *FalseVal,
3413 bool TrueWhenUnset) {
3414 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003415 if (!BitWidth)
3416 return nullptr;
3417
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003418 APInt MinSignedValue;
3419 Value *X;
3420 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3421 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3422 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3423 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3424 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3425 } else {
3426 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3427 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3428 X = CmpLHS;
3429 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3430 }
3431
3432 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3433 TrueWhenUnset))
3434 return V;
3435
3436 return nullptr;
3437}
3438
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003439/// Try to simplify a select instruction when its condition operand is an
3440/// integer comparison.
3441static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3442 Value *FalseVal, const Query &Q,
3443 unsigned MaxRecurse) {
3444 ICmpInst::Predicate Pred;
3445 Value *CmpLHS, *CmpRHS;
3446 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3447 return nullptr;
3448
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003449 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3450 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003451 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3452 Value *X;
3453 const APInt *Y;
3454 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3455 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3456 Pred == ICmpInst::ICMP_EQ))
3457 return V;
3458 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003459 // Comparing signed-less-than 0 checks if the sign bit is set.
3460 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3461 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003462 return V;
3463 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003464 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3465 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3466 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003467 return V;
3468 }
3469
3470 if (CondVal->hasOneUse()) {
3471 const APInt *C;
3472 if (match(CmpRHS, m_APInt(C))) {
3473 // X < MIN ? T : F --> F
3474 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3475 return FalseVal;
3476 // X < MIN ? T : F --> F
3477 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3478 return FalseVal;
3479 // X > MAX ? T : F --> F
3480 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3481 return FalseVal;
3482 // X > MAX ? T : F --> F
3483 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3484 return FalseVal;
3485 }
3486 }
3487
3488 // If we have an equality comparison, then we know the value in one of the
3489 // arms of the select. See if substituting this value into the arm and
3490 // simplifying the result yields the same value as the other arm.
3491 if (Pred == ICmpInst::ICMP_EQ) {
3492 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3493 TrueVal ||
3494 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3495 TrueVal)
3496 return FalseVal;
3497 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3498 FalseVal ||
3499 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3500 FalseVal)
3501 return FalseVal;
3502 } else if (Pred == ICmpInst::ICMP_NE) {
3503 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3504 FalseVal ||
3505 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3506 FalseVal)
3507 return TrueVal;
3508 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3509 TrueVal ||
3510 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3511 TrueVal)
3512 return TrueVal;
3513 }
3514
3515 return nullptr;
3516}
3517
Sanjay Patel472cc782016-01-11 22:14:42 +00003518/// Given operands for a SelectInst, see if we can fold the result.
3519/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003520static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3521 Value *FalseVal, const Query &Q,
3522 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003523 // select true, X, Y -> X
3524 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003525 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3526 if (CB->isAllOnesValue())
3527 return TrueVal;
3528 if (CB->isNullValue())
3529 return FalseVal;
3530 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003531
Chris Lattnerc707fa92010-04-20 05:32:14 +00003532 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003533 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003534 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003535
Chris Lattnerc707fa92010-04-20 05:32:14 +00003536 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3537 if (isa<Constant>(TrueVal))
3538 return TrueVal;
3539 return FalseVal;
3540 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003541 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3542 return FalseVal;
3543 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3544 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003545
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003546 if (Value *V =
3547 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3548 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003549
Craig Topper9f008862014-04-15 04:59:12 +00003550 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003551}
3552
Duncan Sandsb8cee002012-03-13 11:42:19 +00003553Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003554 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003555 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003556 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003557 const Instruction *CxtI) {
3558 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Chandler Carruth66b31302015-01-04 12:03:27 +00003559 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003560}
3561
Sanjay Patel472cc782016-01-11 22:14:42 +00003562/// Given operands for an GetElementPtrInst, see if we can fold the result.
3563/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003564static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3565 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003566 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003567 unsigned AS =
3568 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003569
Chris Lattner8574aba2009-11-27 00:29:05 +00003570 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003571 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003572 return Ops[0];
3573
Nico Weber48c82402014-08-27 20:06:19 +00003574 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003575 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003576 Type *GEPTy = PointerType::get(LastType, AS);
3577 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3578 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3579
3580 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003581 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003582
Jay Foadb992a632011-07-19 15:07:52 +00003583 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003584 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003585 if (match(Ops[1], m_Zero()))
3586 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003587
David Blaikie4a2e73b2015-04-02 18:55:32 +00003588 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003589 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003590 Value *P;
3591 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003592 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003593 // getelementptr P, N -> P if P points to a type of zero size.
3594 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003595 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003596
3597 // The following transforms are only safe if the ptrtoint cast
3598 // doesn't truncate the pointers.
3599 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003600 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003601 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3602 if (match(P, m_Zero()))
3603 return Constant::getNullValue(GEPTy);
3604 Value *Temp;
3605 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003606 if (Temp->getType() == GEPTy)
3607 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003608 return nullptr;
3609 };
3610
3611 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3612 if (TyAllocSize == 1 &&
3613 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3614 if (Value *R = PtrToIntOrZero(P))
3615 return R;
3616
3617 // getelementptr V, (ashr (sub P, V), C) -> Q
3618 // if P points to a type of size 1 << C.
3619 if (match(Ops[1],
3620 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3621 m_ConstantInt(C))) &&
3622 TyAllocSize == 1ULL << C)
3623 if (Value *R = PtrToIntOrZero(P))
3624 return R;
3625
3626 // getelementptr V, (sdiv (sub P, V), C) -> Q
3627 // if P points to a type of size C.
3628 if (match(Ops[1],
3629 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3630 m_SpecificInt(TyAllocSize))))
3631 if (Value *R = PtrToIntOrZero(P))
3632 return R;
3633 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003634 }
3635 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003636
Chris Lattner8574aba2009-11-27 00:29:05 +00003637 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003638 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003639 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003640 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003641
David Blaikie4a2e73b2015-04-02 18:55:32 +00003642 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3643 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003644}
3645
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003646Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3647 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003648 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003649 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003650 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003651 return ::SimplifyGEPInst(SrcTy, Ops,
3652 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003653}
3654
Sanjay Patel472cc782016-01-11 22:14:42 +00003655/// Given operands for an InsertValueInst, see if we can fold the result.
3656/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003657static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3658 ArrayRef<unsigned> Idxs, const Query &Q,
3659 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003660 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3661 if (Constant *CVal = dyn_cast<Constant>(Val))
3662 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3663
3664 // insertvalue x, undef, n -> x
3665 if (match(Val, m_Undef()))
3666 return Agg;
3667
3668 // insertvalue x, (extractvalue y, n), n
3669 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003670 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3671 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003672 // insertvalue undef, (extractvalue y, n), n -> y
3673 if (match(Agg, m_Undef()))
3674 return EV->getAggregateOperand();
3675
3676 // insertvalue y, (extractvalue y, n), n -> y
3677 if (Agg == EV->getAggregateOperand())
3678 return Agg;
3679 }
3680
Craig Topper9f008862014-04-15 04:59:12 +00003681 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003682}
3683
Chandler Carruth66b31302015-01-04 12:03:27 +00003684Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003685 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003686 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3687 const Instruction *CxtI) {
3688 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003689 RecursionLimit);
3690}
3691
Sanjay Patel472cc782016-01-11 22:14:42 +00003692/// Given operands for an ExtractValueInst, see if we can fold the result.
3693/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003694static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3695 const Query &, unsigned) {
3696 if (auto *CAgg = dyn_cast<Constant>(Agg))
3697 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3698
3699 // extractvalue x, (insertvalue y, elt, n), n -> elt
3700 unsigned NumIdxs = Idxs.size();
3701 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3702 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3703 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3704 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3705 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3706 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3707 Idxs.slice(0, NumCommonIdxs)) {
3708 if (NumIdxs == NumInsertValueIdxs)
3709 return IVI->getInsertedValueOperand();
3710 break;
3711 }
3712 }
3713
3714 return nullptr;
3715}
3716
3717Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3718 const DataLayout &DL,
3719 const TargetLibraryInfo *TLI,
3720 const DominatorTree *DT,
3721 AssumptionCache *AC,
3722 const Instruction *CxtI) {
3723 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3724 RecursionLimit);
3725}
3726
Sanjay Patel472cc782016-01-11 22:14:42 +00003727/// Given operands for an ExtractElementInst, see if we can fold the result.
3728/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003729static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3730 unsigned) {
3731 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3732 if (auto *CIdx = dyn_cast<Constant>(Idx))
3733 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3734
3735 // The index is not relevant if our vector is a splat.
3736 if (auto *Splat = CVec->getSplatValue())
3737 return Splat;
3738
3739 if (isa<UndefValue>(Vec))
3740 return UndefValue::get(Vec->getType()->getVectorElementType());
3741 }
3742
3743 // If extracting a specified index from the vector, see if we can recursively
3744 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003745 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3746 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003747 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003748
3749 return nullptr;
3750}
3751
3752Value *llvm::SimplifyExtractElementInst(
3753 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3754 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3755 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3756 RecursionLimit);
3757}
3758
Sanjay Patel472cc782016-01-11 22:14:42 +00003759/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003760static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003761 // If all of the PHI's incoming values are the same then replace the PHI node
3762 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003763 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003764 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003765 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003766 // If the incoming value is the phi node itself, it can safely be skipped.
3767 if (Incoming == PN) continue;
3768 if (isa<UndefValue>(Incoming)) {
3769 // Remember that we saw an undef value, but otherwise ignore them.
3770 HasUndefInput = true;
3771 continue;
3772 }
3773 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003774 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003775 CommonValue = Incoming;
3776 }
3777
3778 // If CommonValue is null then all of the incoming values were either undef or
3779 // equal to the phi node itself.
3780 if (!CommonValue)
3781 return UndefValue::get(PN->getType());
3782
3783 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3784 // instruction, we cannot return X as the result of the PHI node unless it
3785 // dominates the PHI block.
3786 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003787 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003788
3789 return CommonValue;
3790}
3791
Duncan Sands395ac42d2012-03-13 14:07:05 +00003792static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3793 if (Constant *C = dyn_cast<Constant>(Op))
Manuel Jacob925d0292016-01-21 06:31:08 +00003794 return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003795
Craig Topper9f008862014-04-15 04:59:12 +00003796 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00003797}
3798
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003799Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00003800 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003801 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003802 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003803 return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003804 RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003805}
3806
Chris Lattnera71e9d62009-11-10 00:55:12 +00003807//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003808
Sanjay Patel472cc782016-01-11 22:14:42 +00003809/// Given operands for a BinaryOperator, see if we can fold the result.
3810/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003811static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003812 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003813 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003814 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003815 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003816 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003817 case Instruction::FAdd:
3818 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3819
Chris Lattner9e4aa022011-02-09 17:15:04 +00003820 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003821 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003822 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003823 case Instruction::FSub:
3824 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3825
Duncan Sandsb8cee002012-03-13 11:42:19 +00003826 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003827 case Instruction::FMul:
3828 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003829 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3830 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003831 case Instruction::FDiv:
3832 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003833 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3834 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003835 case Instruction::FRem:
3836 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003837 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003838 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003839 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003840 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003841 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003842 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003843 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3844 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3845 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3846 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003847 default:
3848 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00003849 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3850 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00003851
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003852 // If the operation is associative, try some generic simplifications.
3853 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003854 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003855 return V;
3856
Duncan Sandsb8cee002012-03-13 11:42:19 +00003857 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003858 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003859 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003860 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003861 return V;
3862
3863 // If the operation is with the result of a phi instruction, check whether
3864 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003865 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003866 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003867 return V;
3868
Craig Topper9f008862014-04-15 04:59:12 +00003869 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003870 }
3871}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003872
Sanjay Patel472cc782016-01-11 22:14:42 +00003873/// Given operands for a BinaryOperator, see if we can fold the result.
3874/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003875/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3876/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3877static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3878 const FastMathFlags &FMF, const Query &Q,
3879 unsigned MaxRecurse) {
3880 switch (Opcode) {
3881 case Instruction::FAdd:
3882 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3883 case Instruction::FSub:
3884 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3885 case Instruction::FMul:
3886 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3887 default:
3888 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3889 }
3890}
3891
Duncan Sands7e800d62010-11-14 11:23:23 +00003892Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003893 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003894 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003895 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003896 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003897 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003898}
3899
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003900Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003901 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003902 const TargetLibraryInfo *TLI,
3903 const DominatorTree *DT, AssumptionCache *AC,
3904 const Instruction *CxtI) {
3905 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3906 RecursionLimit);
3907}
3908
Sanjay Patel472cc782016-01-11 22:14:42 +00003909/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003910static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003911 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003912 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003913 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003914 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003915}
3916
3917Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003918 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003919 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003920 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003921 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003922 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003923}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003924
Michael Ilseman54857292013-02-07 19:26:05 +00003925static bool IsIdempotent(Intrinsic::ID ID) {
3926 switch (ID) {
3927 default: return false;
3928
3929 // Unary idempotent: f(f(x)) = f(x)
3930 case Intrinsic::fabs:
3931 case Intrinsic::floor:
3932 case Intrinsic::ceil:
3933 case Intrinsic::trunc:
3934 case Intrinsic::rint:
3935 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003936 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003937 return true;
3938 }
3939}
3940
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00003941static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3942 const DataLayout &DL) {
3943 GlobalValue *PtrSym;
3944 APInt PtrOffset;
3945 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3946 return nullptr;
3947
3948 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3949 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3950 Type *Int32PtrTy = Int32Ty->getPointerTo();
3951 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3952
3953 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3954 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3955 return nullptr;
3956
3957 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3958 if (OffsetInt % 4 != 0)
3959 return nullptr;
3960
3961 Constant *C = ConstantExpr::getGetElementPtr(
3962 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3963 ConstantInt::get(Int64Ty, OffsetInt / 4));
3964 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3965 if (!Loaded)
3966 return nullptr;
3967
3968 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3969 if (!LoadedCE)
3970 return nullptr;
3971
3972 if (LoadedCE->getOpcode() == Instruction::Trunc) {
3973 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3974 if (!LoadedCE)
3975 return nullptr;
3976 }
3977
3978 if (LoadedCE->getOpcode() != Instruction::Sub)
3979 return nullptr;
3980
3981 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3982 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3983 return nullptr;
3984 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3985
3986 Constant *LoadedRHS = LoadedCE->getOperand(1);
3987 GlobalValue *LoadedRHSSym;
3988 APInt LoadedRHSOffset;
3989 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3990 DL) ||
3991 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3992 return nullptr;
3993
3994 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3995}
3996
David Majnemer17a95aa2016-07-14 06:58:37 +00003997static bool maskIsAllZeroOrUndef(Value *Mask) {
3998 auto *ConstMask = dyn_cast<Constant>(Mask);
3999 if (!ConstMask)
4000 return false;
4001 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4002 return true;
4003 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4004 ++I) {
4005 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4006 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4007 continue;
4008 return false;
4009 }
4010 return true;
4011}
4012
Michael Ilseman54857292013-02-07 19:26:05 +00004013template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004014static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004015 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004016 Intrinsic::ID IID = F->getIntrinsicID();
4017 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4018 Type *ReturnType = F->getReturnType();
4019
4020 // Binary Ops
4021 if (NumOperands == 2) {
4022 Value *LHS = *ArgBegin;
4023 Value *RHS = *(ArgBegin + 1);
4024 if (IID == Intrinsic::usub_with_overflow ||
4025 IID == Intrinsic::ssub_with_overflow) {
4026 // X - X -> { 0, false }
4027 if (LHS == RHS)
4028 return Constant::getNullValue(ReturnType);
4029
4030 // X - undef -> undef
4031 // undef - X -> undef
4032 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4033 return UndefValue::get(ReturnType);
4034 }
4035
4036 if (IID == Intrinsic::uadd_with_overflow ||
4037 IID == Intrinsic::sadd_with_overflow) {
4038 // X + undef -> undef
4039 if (isa<UndefValue>(RHS))
4040 return UndefValue::get(ReturnType);
4041 }
4042
4043 if (IID == Intrinsic::umul_with_overflow ||
4044 IID == Intrinsic::smul_with_overflow) {
4045 // X * 0 -> { 0, false }
4046 if (match(RHS, m_Zero()))
4047 return Constant::getNullValue(ReturnType);
4048
4049 // X * undef -> { 0, false }
4050 if (match(RHS, m_Undef()))
4051 return Constant::getNullValue(ReturnType);
4052 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004053
4054 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4055 isa<Constant>(RHS))
4056 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4057 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00004058 }
4059
David Majnemerd77a3b62016-07-13 23:32:53 +00004060 // Simplify calls to llvm.masked.load.*
4061 if (IID == Intrinsic::masked_load) {
David Majnemer17a95aa2016-07-14 06:58:37 +00004062 Value *MaskArg = ArgBegin[2];
4063 Value *PassthruArg = ArgBegin[3];
4064 // If the mask is all zeros or undef, the "passthru" argument is the result.
4065 if (maskIsAllZeroOrUndef(MaskArg))
4066 return PassthruArg;
David Majnemerd77a3b62016-07-13 23:32:53 +00004067 }
4068
Michael Ilseman54857292013-02-07 19:26:05 +00004069 // Perform idempotent optimizations
4070 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00004071 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004072
4073 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00004074 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00004075 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4076 if (II->getIntrinsicID() == IID)
4077 return II;
4078
Craig Topper9f008862014-04-15 04:59:12 +00004079 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004080}
4081
Chandler Carruth9dc35582012-12-28 11:30:55 +00004082template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004083static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004084 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004085 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004086 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4087 Ty = PTy->getElementType();
4088 FunctionType *FTy = cast<FunctionType>(Ty);
4089
Dan Gohman85977e62011-11-04 18:32:42 +00004090 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004091 // call null -> undef
4092 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004093 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004094
Chandler Carruthf6182152012-12-28 14:23:29 +00004095 Function *F = dyn_cast<Function>(V);
4096 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004097 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004098
David Majnemer15032582015-05-22 03:56:46 +00004099 if (F->isIntrinsic())
4100 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004101 return Ret;
4102
Chandler Carruthf6182152012-12-28 14:23:29 +00004103 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004104 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004105
4106 SmallVector<Constant *, 4> ConstantArgs;
4107 ConstantArgs.reserve(ArgEnd - ArgBegin);
4108 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4109 Constant *C = dyn_cast<Constant>(*I);
4110 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004111 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004112 ConstantArgs.push_back(C);
4113 }
4114
4115 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004116}
4117
Chandler Carruthf6182152012-12-28 14:23:29 +00004118Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004119 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004120 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4121 AssumptionCache *AC, const Instruction *CxtI) {
4122 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004123 RecursionLimit);
4124}
4125
Chandler Carruthf6182152012-12-28 14:23:29 +00004126Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004127 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004128 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004129 const Instruction *CxtI) {
4130 return ::SimplifyCall(V, Args.begin(), Args.end(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004131 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004132}
4133
Sanjay Patel472cc782016-01-11 22:14:42 +00004134/// See if we can compute a simplified version of this instruction.
4135/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004136Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004137 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004138 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004139 Value *Result;
4140
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004141 switch (I->getOpcode()) {
4142 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004143 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004144 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004145 case Instruction::FAdd:
4146 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004147 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004148 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004149 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004150 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4151 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004152 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4153 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004154 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004155 case Instruction::FSub:
4156 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004157 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004158 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004159 case Instruction::Sub:
4160 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4161 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004162 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4163 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004164 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004165 case Instruction::FMul:
4166 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004167 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004168 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004169 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004170 Result =
4171 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004172 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004173 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004174 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4175 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004176 break;
4177 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004178 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4179 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004180 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004181 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004182 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4183 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004184 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004185 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004186 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4187 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004188 break;
4189 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004190 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4191 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004192 break;
4193 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004194 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4195 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004196 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004197 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004198 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4199 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004200 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4201 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004202 break;
4203 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004204 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004205 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4206 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004207 break;
4208 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004209 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004210 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4211 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004212 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004213 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004214 Result =
4215 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004216 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004217 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004218 Result =
4219 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004220 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004221 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004222 Result =
4223 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004224 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004225 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004226 Result =
4227 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4228 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004229 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004230 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004231 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4232 I->getOperand(0), I->getOperand(1),
4233 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004234 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004235 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004236 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004237 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004238 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004239 case Instruction::GetElementPtr: {
4240 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004241 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4242 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004243 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004244 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004245 case Instruction::InsertValue: {
4246 InsertValueInst *IV = cast<InsertValueInst>(I);
4247 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4248 IV->getInsertedValueOperand(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004249 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004250 break;
4251 }
David Majnemer25a796e2015-07-13 01:15:46 +00004252 case Instruction::ExtractValue: {
4253 auto *EVI = cast<ExtractValueInst>(I);
4254 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4255 EVI->getIndices(), DL, TLI, DT, AC, I);
4256 break;
4257 }
David Majnemer599ca442015-07-13 01:15:53 +00004258 case Instruction::ExtractElement: {
4259 auto *EEI = cast<ExtractElementInst>(I);
4260 Result = SimplifyExtractElementInst(
4261 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4262 break;
4263 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004264 case Instruction::PHI:
Chandler Carruth66b31302015-01-04 12:03:27 +00004265 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004266 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004267 case Instruction::Call: {
4268 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004269 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4270 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004271 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004272 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00004273 case Instruction::Trunc:
Chandler Carruth66b31302015-01-04 12:03:27 +00004274 Result =
4275 SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004276 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004277 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004278
Hal Finkelf2199b22015-10-23 20:37:08 +00004279 // In general, it is possible for computeKnownBits to determine all bits in a
4280 // value even when the operands are not all constants.
4281 if (!Result && I->getType()->isIntegerTy()) {
4282 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4283 APInt KnownZero(BitWidth, 0);
4284 APInt KnownOne(BitWidth, 0);
4285 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4286 if ((KnownZero | KnownOne).isAllOnesValue())
4287 Result = ConstantInt::get(I->getContext(), KnownOne);
4288 }
4289
Duncan Sands64e41cf2010-11-17 08:35:29 +00004290 /// If called on unreachable code, the above logic may report that the
4291 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004292 /// detecting that case here, returning a safe value instead.
4293 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004294}
4295
Sanjay Patelf44bd382016-01-20 18:59:48 +00004296/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004297/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004298///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004299/// This is the common implementation of the recursive simplification routines.
4300/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4301/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4302/// instructions to process and attempt to simplify it using
4303/// InstructionSimplify.
4304///
4305/// This routine returns 'true' only when *it* simplifies something. The passed
4306/// in simplified value does not count toward this.
4307static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004308 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004309 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004310 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004311 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004312 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004313 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004314
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004315 // If we have an explicit value to collapse to, do that round of the
4316 // simplification loop by hand initially.
4317 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004318 for (User *U : I->users())
4319 if (U != I)
4320 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004321
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004322 // Replace the instruction with its simplified value.
4323 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004324
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004325 // Gracefully handle edge cases where the instruction is not wired into any
4326 // parent block.
4327 if (I->getParent())
4328 I->eraseFromParent();
4329 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004330 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004331 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004332
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004333 // Note that we must test the size on each iteration, the worklist can grow.
4334 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4335 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004336
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004337 // See if this instruction simplifies.
Chandler Carruth66b31302015-01-04 12:03:27 +00004338 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004339 if (!SimpleV)
4340 continue;
4341
4342 Simplified = true;
4343
4344 // Stash away all the uses of the old instruction so we can check them for
4345 // recursive simplifications after a RAUW. This is cheaper than checking all
4346 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004347 for (User *U : I->users())
4348 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004349
4350 // Replace the instruction with its simplified value.
4351 I->replaceAllUsesWith(SimpleV);
4352
4353 // Gracefully handle edge cases where the instruction is not wired into any
4354 // parent block.
4355 if (I->getParent())
4356 I->eraseFromParent();
4357 }
4358 return Simplified;
4359}
4360
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004361bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004362 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004363 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004364 AssumptionCache *AC) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004365 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004366}
4367
4368bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004369 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004370 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004371 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004372 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4373 assert(SimpleV && "Must provide a simplified value.");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004374 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004375}