blob: 746b7409dfea0956f4054e31b856f5489bff7196 [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 {
624 break;
625 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000626 assert(V->getType()->getScalarType()->isPointerTy() &&
627 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000628 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000629
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000630 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
631 if (V->getType()->isVectorTy())
632 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
633 OffsetIntPtr);
634 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000635}
636
637/// \brief Compute the constant difference between two pointer values.
638/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000639static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
640 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000641 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
642 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000643
644 // If LHS and RHS are not related via constant offsets to the same base
645 // value, there is nothing we can do here.
646 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000647 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000648
649 // Otherwise, the difference of LHS - RHS can be computed as:
650 // LHS - RHS
651 // = (LHSOffset + Base) - (RHSOffset + Base)
652 // = LHSOffset - RHSOffset
653 return ConstantExpr::getSub(LHSOffset, RHSOffset);
654}
655
Sanjay Patel472cc782016-01-11 22:14:42 +0000656/// Given operands for a Sub, see if we can fold the result.
657/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000658static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000659 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000660 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000661 if (Constant *CRHS = dyn_cast<Constant>(Op1))
662 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000663
664 // X - undef -> undef
665 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000666 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000667 return UndefValue::get(Op0->getType());
668
669 // X - 0 -> X
670 if (match(Op1, m_Zero()))
671 return Op0;
672
673 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000674 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000675 return Constant::getNullValue(Op0->getType());
676
David Majnemer4efa9ff2014-11-22 07:15:16 +0000677 // 0 - X -> 0 if the sub is NUW.
678 if (isNUW && match(Op0, m_Zero()))
679 return Op0;
David Majnemercd4fbcd2014-07-31 04:49:18 +0000680
Duncan Sands99589d02011-01-18 11:50:19 +0000681 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
682 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000683 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000684 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
685 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000686 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000687 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000688 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000689 // It does, we successfully reassociated!
690 ++NumReassoc;
691 return W;
692 }
693 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000694 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000695 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000696 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000697 // It does, we successfully reassociated!
698 ++NumReassoc;
699 return W;
700 }
701 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000702
Duncan Sands99589d02011-01-18 11:50:19 +0000703 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
704 // For example, X - (X + 1) -> -1
705 X = Op0;
706 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
707 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000708 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000709 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000710 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000711 // It does, we successfully reassociated!
712 ++NumReassoc;
713 return W;
714 }
715 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000716 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000718 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000719 // It does, we successfully reassociated!
720 ++NumReassoc;
721 return W;
722 }
723 }
724
725 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
726 // For example, X - (X - Y) -> Y.
727 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000728 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
729 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000732 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000733 // It does, we successfully reassociated!
734 ++NumReassoc;
735 return W;
736 }
737
Duncan Sands395ac42d2012-03-13 14:07:05 +0000738 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
739 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
740 match(Op1, m_Trunc(m_Value(Y))))
741 if (X->getType() == Y->getType())
742 // See if "V === X - Y" simplifies.
743 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
744 // It does! Now see if "trunc V" simplifies.
745 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
746 // It does, return the simplified "trunc V".
747 return W;
748
749 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000750 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000751 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000752 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000753 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
754
Duncan Sands99589d02011-01-18 11:50:19 +0000755 // i1 sub -> xor.
756 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000757 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000758 return V;
759
Duncan Sands0a2c41682010-12-15 14:07:39 +0000760 // Threading Sub over selects and phi nodes is pointless, so don't bother.
761 // Threading over the select in "A - select(cond, B, C)" means evaluating
762 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
763 // only if B and C are equal. If B and C are equal then (since we assume
764 // that operands have already been simplified) "select(cond, B, C)" should
765 // have been simplified to the common value of B and C already. Analysing
766 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
767 // for threading over phi nodes.
768
Craig Topper9f008862014-04-15 04:59:12 +0000769 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000770}
771
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000772Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000773 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000774 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000775 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000776 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
777 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000778}
779
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000780/// Given operands for an FAdd, see if we can fold the result. If not, this
781/// returns null.
782static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
783 const Query &Q, unsigned MaxRecurse) {
784 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000785 if (Constant *CRHS = dyn_cast<Constant>(Op1))
786 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000787
788 // Canonicalize the constant to the RHS.
789 std::swap(Op0, Op1);
790 }
791
792 // fadd X, -0 ==> X
793 if (match(Op1, m_NegZero()))
794 return Op0;
795
796 // fadd X, 0 ==> X, when we know X is not -0
797 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000798 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000799 return Op0;
800
801 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
802 // where nnan and ninf have to occur at least once somewhere in this
803 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000804 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000805 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
806 SubOp = Op1;
807 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
808 SubOp = Op0;
809 if (SubOp) {
810 Instruction *FSub = cast<Instruction>(SubOp);
811 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
812 (FMF.noInfs() || FSub->hasNoInfs()))
813 return Constant::getNullValue(Op0->getType());
814 }
815
Craig Topper9f008862014-04-15 04:59:12 +0000816 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000817}
818
819/// Given operands for an FSub, see if we can fold the result. If not, this
820/// returns null.
821static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
822 const Query &Q, unsigned MaxRecurse) {
823 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000824 if (Constant *CRHS = dyn_cast<Constant>(Op1))
825 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000826 }
827
828 // fsub X, 0 ==> X
829 if (match(Op1, m_Zero()))
830 return Op0;
831
832 // fsub X, -0 ==> X, when we know X is not -0
833 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000834 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000835 return Op0;
836
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000837 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000838 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000839 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
840 return X;
841
842 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000843 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000844 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
845 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000846
Benjamin Kramer228680d2015-06-14 21:01:20 +0000847 // fsub nnan x, x ==> 0.0
848 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000849 return Constant::getNullValue(Op0->getType());
850
Craig Topper9f008862014-04-15 04:59:12 +0000851 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852}
853
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000854/// Given the operands for an FMul, see if we can fold the result
855static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
856 FastMathFlags FMF,
857 const Query &Q,
858 unsigned MaxRecurse) {
859 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000860 if (Constant *CRHS = dyn_cast<Constant>(Op1))
861 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000862
863 // Canonicalize the constant to the RHS.
864 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000865 }
866
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000867 // fmul X, 1.0 ==> X
868 if (match(Op1, m_FPOne()))
869 return Op0;
870
871 // fmul nnan nsz X, 0 ==> 0
872 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
873 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000874
Craig Topper9f008862014-04-15 04:59:12 +0000875 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000876}
877
Sanjay Patel472cc782016-01-11 22:14:42 +0000878/// Given operands for a Mul, see if we can fold the result.
879/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000880static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
881 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000882 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000883 if (Constant *CRHS = dyn_cast<Constant>(Op1))
884 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000885
886 // Canonicalize the constant to the RHS.
887 std::swap(Op0, Op1);
888 }
889
890 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000891 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000892 return Constant::getNullValue(Op0->getType());
893
894 // X * 0 -> 0
895 if (match(Op1, m_Zero()))
896 return Op1;
897
898 // X * 1 -> X
899 if (match(Op1, m_One()))
900 return Op0;
901
Duncan Sandsb67edc62011-01-30 18:03:50 +0000902 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000903 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000904 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
905 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
906 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000907
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000908 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000909 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000910 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000911 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000912
913 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000914 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000915 MaxRecurse))
916 return V;
917
918 // Mul distributes over Add. Try some generic simplifications based on this.
919 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000920 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000921 return V;
922
923 // If the operation is with the result of a select instruction, check whether
924 // operating on either branch of the select always yields the same value.
925 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000926 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000927 MaxRecurse))
928 return V;
929
930 // If the operation is with the result of a phi instruction, check whether
931 // operating on all incoming values of the phi always yields the same value.
932 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000933 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000934 MaxRecurse))
935 return V;
936
Craig Topper9f008862014-04-15 04:59:12 +0000937 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938}
939
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000940Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000941 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000942 const TargetLibraryInfo *TLI,
943 const DominatorTree *DT, AssumptionCache *AC,
944 const Instruction *CxtI) {
945 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000946 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000947}
948
949Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000950 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000951 const TargetLibraryInfo *TLI,
952 const DominatorTree *DT, AssumptionCache *AC,
953 const Instruction *CxtI) {
954 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000955 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000956}
957
Chandler Carruth66b31302015-01-04 12:03:27 +0000958Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000960 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000961 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000962 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000963 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000964 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000965}
966
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000968 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000969 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000970 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000971 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000972 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000973}
974
Sanjay Patel472cc782016-01-11 22:14:42 +0000975/// Given operands for an SDiv or UDiv, see if we can fold the result.
976/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000977static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000978 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000979 if (Constant *C0 = dyn_cast<Constant>(Op0))
980 if (Constant *C1 = dyn_cast<Constant>(Op1))
981 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +0000982
Duncan Sands65995fa2011-01-28 18:50:50 +0000983 bool isSigned = Opcode == Instruction::SDiv;
984
Duncan Sands771e82a2011-01-28 16:51:11 +0000985 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000986 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000987 return Op1;
988
David Majnemer71dc8fb2014-12-10 07:52:18 +0000989 // X / 0 -> undef, we don't need to preserve faults!
990 if (match(Op1, m_Zero()))
991 return UndefValue::get(Op1->getType());
992
Duncan Sands771e82a2011-01-28 16:51:11 +0000993 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000994 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000995 return Constant::getNullValue(Op0->getType());
996
997 // 0 / X -> 0, we don't need to preserve faults!
998 if (match(Op0, m_Zero()))
999 return Op0;
1000
1001 // X / 1 -> X
1002 if (match(Op1, m_One()))
1003 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001004
1005 if (Op0->getType()->isIntegerTy(1))
1006 // It can't be division by zero, hence it must be division by one.
1007 return Op0;
1008
1009 // X / X -> 1
1010 if (Op0 == Op1)
1011 return ConstantInt::get(Op0->getType(), 1);
1012
1013 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001014 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001015 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1016 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001017 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001018 // If the Mul knows it does not overflow, then we are good to go.
1019 if ((isSigned && Mul->hasNoSignedWrap()) ||
1020 (!isSigned && Mul->hasNoUnsignedWrap()))
1021 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 // If X has the form X = A / Y then X * Y cannot overflow.
1023 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1024 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1025 return X;
1026 }
1027
Duncan Sands65995fa2011-01-28 18:50:50 +00001028 // (X rem Y) / Y -> 0
1029 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1030 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1031 return Constant::getNullValue(Op0->getType());
1032
David Majnemercb9d5962014-10-11 10:20:01 +00001033 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1034 ConstantInt *C1, *C2;
1035 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1036 match(Op1, m_ConstantInt(C2))) {
1037 bool Overflow;
1038 C1->getValue().umul_ov(C2->getValue(), Overflow);
1039 if (Overflow)
1040 return Constant::getNullValue(Op0->getType());
1041 }
1042
Duncan Sands65995fa2011-01-28 18:50:50 +00001043 // If the operation is with the result of a select instruction, check whether
1044 // operating on either branch of the select always yields the same value.
1045 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001046 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001047 return V;
1048
1049 // If the operation is with the result of a phi instruction, check whether
1050 // operating on all incoming values of the phi always yields the same value.
1051 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001052 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 return V;
1054
Craig Topper9f008862014-04-15 04:59:12 +00001055 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001056}
1057
Sanjay Patel472cc782016-01-11 22:14:42 +00001058/// Given operands for an SDiv, see if we can fold the result.
1059/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001060static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1061 unsigned MaxRecurse) {
1062 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001063 return V;
1064
Craig Topper9f008862014-04-15 04:59:12 +00001065 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001066}
1067
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001068Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001069 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001070 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001071 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001072 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001073 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001074}
1075
Sanjay Patel472cc782016-01-11 22:14:42 +00001076/// Given operands for a UDiv, see if we can fold the result.
1077/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001078static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1079 unsigned MaxRecurse) {
1080 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001081 return V;
1082
Craig Topper9f008862014-04-15 04:59:12 +00001083 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001084}
1085
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001086Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001087 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001088 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001089 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001090 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001091 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001092}
1093
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001094static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1095 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001096 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001097 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001098 return Op0;
1099
1100 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001101 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001102 return Op1;
1103
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001104 // 0 / X -> 0
1105 // Requires that NaNs are off (X could be zero) and signed zeroes are
1106 // ignored (X could be positive or negative, so the output sign is unknown).
1107 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1108 return Op0;
1109
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001110 if (FMF.noNaNs()) {
1111 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001112 if (Op0 == Op1)
1113 return ConstantFP::get(Op0->getType(), 1.0);
1114
1115 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001116 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001117 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1118 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1119 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1120 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1121 BinaryOperator::getFNegArgument(Op1) == Op0))
1122 return ConstantFP::get(Op0->getType(), -1.0);
1123 }
1124
Craig Topper9f008862014-04-15 04:59:12 +00001125 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001126}
1127
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001128Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001129 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001130 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001131 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001132 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001133 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001134 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001135}
1136
Sanjay Patel472cc782016-01-11 22:14:42 +00001137/// Given operands for an SRem or URem, see if we can fold the result.
1138/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001139static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001140 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001141 if (Constant *C0 = dyn_cast<Constant>(Op0))
1142 if (Constant *C1 = dyn_cast<Constant>(Op1))
1143 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001144
Duncan Sandsa3e36992011-05-02 16:27:02 +00001145 // X % undef -> undef
1146 if (match(Op1, m_Undef()))
1147 return Op1;
1148
1149 // undef % X -> 0
1150 if (match(Op0, m_Undef()))
1151 return Constant::getNullValue(Op0->getType());
1152
1153 // 0 % X -> 0, we don't need to preserve faults!
1154 if (match(Op0, m_Zero()))
1155 return Op0;
1156
1157 // X % 0 -> undef, we don't need to preserve faults!
1158 if (match(Op1, m_Zero()))
1159 return UndefValue::get(Op0->getType());
1160
1161 // X % 1 -> 0
1162 if (match(Op1, m_One()))
1163 return Constant::getNullValue(Op0->getType());
1164
1165 if (Op0->getType()->isIntegerTy(1))
1166 // It can't be remainder by zero, hence it must be remainder by one.
1167 return Constant::getNullValue(Op0->getType());
1168
1169 // X % X -> 0
1170 if (Op0 == Op1)
1171 return Constant::getNullValue(Op0->getType());
1172
David Majnemerb435a422014-09-17 04:16:35 +00001173 // (X % Y) % Y -> X % Y
1174 if ((Opcode == Instruction::SRem &&
1175 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1176 (Opcode == Instruction::URem &&
1177 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001178 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001179
Duncan Sandsa3e36992011-05-02 16:27:02 +00001180 // If the operation is with the result of a select instruction, check whether
1181 // operating on either branch of the select always yields the same value.
1182 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001183 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001184 return V;
1185
1186 // If the operation is with the result of a phi instruction, check whether
1187 // operating on all incoming values of the phi always yields the same value.
1188 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001189 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001190 return V;
1191
Craig Topper9f008862014-04-15 04:59:12 +00001192 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001193}
1194
Sanjay Patel472cc782016-01-11 22:14:42 +00001195/// Given operands for an SRem, see if we can fold the result.
1196/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001197static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1198 unsigned MaxRecurse) {
1199 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001200 return V;
1201
Craig Topper9f008862014-04-15 04:59:12 +00001202 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001203}
1204
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001206 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001207 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001208 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001209 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001210 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001211}
1212
Sanjay Patel472cc782016-01-11 22:14:42 +00001213/// Given operands for a URem, see if we can fold the result.
1214/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001215static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001216 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001217 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001218 return V;
1219
Craig Topper9f008862014-04-15 04:59:12 +00001220 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001221}
1222
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001223Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001224 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001225 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001226 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001227 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001228 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001229}
1230
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001231static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1232 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233 // undef % X -> undef (the undef could be a snan).
1234 if (match(Op0, m_Undef()))
1235 return Op0;
1236
1237 // X % undef -> undef
1238 if (match(Op1, m_Undef()))
1239 return Op1;
1240
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001241 // 0 % X -> 0
1242 // Requires that NaNs are off (X could be zero) and signed zeroes are
1243 // ignored (X could be positive or negative, so the output sign is unknown).
1244 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1245 return Op0;
1246
Craig Topper9f008862014-04-15 04:59:12 +00001247 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248}
1249
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001250Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001251 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001252 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001253 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001254 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001255 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001256 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001257}
1258
Sanjay Patel472cc782016-01-11 22:14:42 +00001259/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001260static bool isUndefShift(Value *Amount) {
1261 Constant *C = dyn_cast<Constant>(Amount);
1262 if (!C)
1263 return false;
1264
1265 // X shift by undef -> undef because it may shift by the bitwidth.
1266 if (isa<UndefValue>(C))
1267 return true;
1268
1269 // Shifting by the bitwidth or more is undefined.
1270 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1271 if (CI->getValue().getLimitedValue() >=
1272 CI->getType()->getScalarSizeInBits())
1273 return true;
1274
1275 // If all lanes of a vector shift are undefined the whole shift is.
1276 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1277 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1278 if (!isUndefShift(C->getAggregateElement(I)))
1279 return false;
1280 return true;
1281 }
1282
1283 return false;
1284}
1285
Sanjay Patel472cc782016-01-11 22:14:42 +00001286/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1287/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001288static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001289 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001290 if (Constant *C0 = dyn_cast<Constant>(Op0))
1291 if (Constant *C1 = dyn_cast<Constant>(Op1))
1292 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001293
Duncan Sands571fd9a2011-01-14 14:44:12 +00001294 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001295 if (match(Op0, m_Zero()))
1296 return Op0;
1297
Duncan Sands571fd9a2011-01-14 14:44:12 +00001298 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001299 if (match(Op1, m_Zero()))
1300 return Op0;
1301
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001302 // Fold undefined shifts.
1303 if (isUndefShift(Op1))
1304 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001305
Duncan Sands571fd9a2011-01-14 14:44:12 +00001306 // If the operation is with the result of a select instruction, check whether
1307 // operating on either branch of the select always yields the same value.
1308 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001309 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001310 return V;
1311
1312 // If the operation is with the result of a phi instruction, check whether
1313 // operating on all incoming values of the phi always yields the same value.
1314 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001315 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001316 return V;
1317
Sanjay Patel6786bc52016-05-10 20:46:54 +00001318 // If any bits in the shift amount make that value greater than or equal to
1319 // the number of bits in the type, the shift is undefined.
1320 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1321 APInt KnownZero(BitWidth, 0);
1322 APInt KnownOne(BitWidth, 0);
1323 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1324 if (KnownOne.getLimitedValue() >= BitWidth)
1325 return UndefValue::get(Op0->getType());
1326
1327 // If all valid bits in the shift amount are known zero, the first operand is
1328 // unchanged.
1329 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1330 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1331 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1332 return Op0;
1333
Craig Topper9f008862014-04-15 04:59:12 +00001334 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001335}
1336
David Majnemerbf7550e2014-11-05 00:59:59 +00001337/// \brief Given operands for an Shl, LShr or AShr, see if we can
1338/// fold the result. If not, this returns null.
1339static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1340 bool isExact, const Query &Q,
1341 unsigned MaxRecurse) {
1342 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1343 return V;
1344
1345 // X >> X -> 0
1346 if (Op0 == Op1)
1347 return Constant::getNullValue(Op0->getType());
1348
David Majnemer65c52ae2014-12-17 01:54:33 +00001349 // undef >> X -> 0
1350 // undef >> X -> undef (if it's exact)
1351 if (match(Op0, m_Undef()))
1352 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1353
David Majnemerbf7550e2014-11-05 00:59:59 +00001354 // The low bit cannot be shifted out of an exact shift if it is set.
1355 if (isExact) {
1356 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1357 APInt Op0KnownZero(BitWidth, 0);
1358 APInt Op0KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00001359 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1360 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001361 if (Op0KnownOne[0])
1362 return Op0;
1363 }
1364
1365 return nullptr;
1366}
1367
Sanjay Patel472cc782016-01-11 22:14:42 +00001368/// Given operands for an Shl, see if we can fold the result.
1369/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001370static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001371 const Query &Q, unsigned MaxRecurse) {
1372 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001373 return V;
1374
1375 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001376 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001377 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001378 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001379
Chris Lattner9e4aa022011-02-09 17:15:04 +00001380 // (X >> A) << A -> X
1381 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001382 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001383 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001384 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001385}
1386
Chris Lattner9e4aa022011-02-09 17:15:04 +00001387Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001388 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001389 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001390 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001391 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001392 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001393}
1394
Sanjay Patel472cc782016-01-11 22:14:42 +00001395/// Given operands for an LShr, see if we can fold the result.
1396/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001397static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001398 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001399 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1400 MaxRecurse))
1401 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001402
Chris Lattner9e4aa022011-02-09 17:15:04 +00001403 // (X << A) >> A -> X
1404 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001405 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001406 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001407
Craig Topper9f008862014-04-15 04:59:12 +00001408 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001409}
1410
Chris Lattner9e4aa022011-02-09 17:15:04 +00001411Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001412 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001413 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001414 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001415 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001416 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001417 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001418}
1419
Sanjay Patel472cc782016-01-11 22:14:42 +00001420/// Given operands for an AShr, see if we can fold the result.
1421/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001422static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001423 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001424 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1425 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001426 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001427
1428 // all ones >>a X -> all ones
1429 if (match(Op0, m_AllOnes()))
1430 return Op0;
1431
Chris Lattner9e4aa022011-02-09 17:15:04 +00001432 // (X << A) >> A -> X
1433 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001434 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001435 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001436
Suyog Sarda68862412014-07-17 06:28:15 +00001437 // Arithmetic shifting an all-sign-bit value is a no-op.
Chandler Carruth66b31302015-01-04 12:03:27 +00001438 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001439 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1440 return Op0;
1441
Craig Topper9f008862014-04-15 04:59:12 +00001442 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001443}
1444
Chris Lattner9e4aa022011-02-09 17:15:04 +00001445Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001446 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001447 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001448 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001449 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001450 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001451 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001452}
1453
David Majnemer1af36e52014-12-06 10:51:40 +00001454static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1455 ICmpInst *UnsignedICmp, bool IsAnd) {
1456 Value *X, *Y;
1457
1458 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001459 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1460 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001461 return nullptr;
1462
1463 ICmpInst::Predicate UnsignedPred;
1464 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1465 ICmpInst::isUnsigned(UnsignedPred))
1466 ;
1467 else if (match(UnsignedICmp,
1468 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1469 ICmpInst::isUnsigned(UnsignedPred))
1470 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1471 else
1472 return nullptr;
1473
1474 // X < Y && Y != 0 --> X < Y
1475 // X < Y || Y != 0 --> Y != 0
1476 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1477 return IsAnd ? UnsignedICmp : ZeroICmp;
1478
1479 // X >= Y || Y != 0 --> true
1480 // X >= Y || Y == 0 --> X >= Y
1481 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1482 if (EqPred == ICmpInst::ICMP_NE)
1483 return getTrue(UnsignedICmp->getType());
1484 return UnsignedICmp;
1485 }
1486
David Majnemerd5b3aa42014-12-08 18:30:43 +00001487 // X < Y && Y == 0 --> false
1488 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1489 IsAnd)
1490 return getFalse(UnsignedICmp->getType());
1491
David Majnemer1af36e52014-12-06 10:51:40 +00001492 return nullptr;
1493}
1494
David Majnemera315bd82014-09-15 08:15:28 +00001495static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001496 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001497 ICmpInst::Predicate Pred0, Pred1;
1498 ConstantInt *CI1, *CI2;
1499 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001500
1501 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1502 return X;
1503
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001504 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1505 const APInt *C0, *C1;
1506 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1507 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1508 // Make a constant range that's the intersection of the two icmp ranges.
1509 // If the intersection is empty, we know that the result is false.
1510 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1511 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1512 if (Range0.intersectWith(Range1).isEmptySet())
1513 return getFalse(ITy);
1514 }
1515
David Majnemera315bd82014-09-15 08:15:28 +00001516 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1517 m_ConstantInt(CI2))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001518 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001519
1520 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1521 return nullptr;
1522
David Majnemera315bd82014-09-15 08:15:28 +00001523 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1524 bool isNSW = AddInst->hasNoSignedWrap();
1525 bool isNUW = AddInst->hasNoUnsignedWrap();
1526
1527 const APInt &CI1V = CI1->getValue();
1528 const APInt &CI2V = CI2->getValue();
1529 const APInt Delta = CI2V - CI1V;
1530 if (CI1V.isStrictlyPositive()) {
1531 if (Delta == 2) {
1532 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1533 return getFalse(ITy);
1534 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1535 return getFalse(ITy);
1536 }
1537 if (Delta == 1) {
1538 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1539 return getFalse(ITy);
1540 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1541 return getFalse(ITy);
1542 }
1543 }
1544 if (CI1V.getBoolValue() && isNUW) {
1545 if (Delta == 2)
1546 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1547 return getFalse(ITy);
1548 if (Delta == 1)
1549 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1550 return getFalse(ITy);
1551 }
1552
1553 return nullptr;
1554}
1555
Sanjay Patel472cc782016-01-11 22:14:42 +00001556/// Given operands for an And, see if we can fold the result.
1557/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001558static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001559 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001560 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001561 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1562 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001563
Chris Lattnera71e9d62009-11-10 00:55:12 +00001564 // Canonicalize the constant to the RHS.
1565 std::swap(Op0, Op1);
1566 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001567
Chris Lattnera71e9d62009-11-10 00:55:12 +00001568 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001569 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001570 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001571
Chris Lattnera71e9d62009-11-10 00:55:12 +00001572 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001573 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001574 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001575
Duncan Sandsc89ac072010-11-17 18:52:15 +00001576 // X & 0 = 0
1577 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001578 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001579
Duncan Sandsc89ac072010-11-17 18:52:15 +00001580 // X & -1 = X
1581 if (match(Op1, m_AllOnes()))
1582 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001583
Chris Lattnera71e9d62009-11-10 00:55:12 +00001584 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001585 if (match(Op0, m_Not(m_Specific(Op1))) ||
1586 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001587 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001588
Chris Lattnera71e9d62009-11-10 00:55:12 +00001589 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001590 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001591 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001592 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001593 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001594
Chris Lattnera71e9d62009-11-10 00:55:12 +00001595 // A & (A | ?) = A
1596 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001597 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001598 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001599
Duncan Sandsba286d72011-10-26 20:55:21 +00001600 // A & (-A) = A if A is a power of two or zero.
1601 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1602 match(Op1, m_Neg(m_Specific(Op0)))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001603 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1604 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001605 return Op0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001606 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1607 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001608 return Op1;
1609 }
1610
David Majnemera315bd82014-09-15 08:15:28 +00001611 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1612 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1613 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1614 return V;
1615 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1616 return V;
1617 }
1618 }
1619
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001620 // The compares may be hidden behind casts. Look through those and try the
1621 // same folds as above.
1622 auto *Cast0 = dyn_cast<CastInst>(Op0);
1623 auto *Cast1 = dyn_cast<CastInst>(Op1);
1624 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1625 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1626 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1627 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1628 if (Cmp0 && Cmp1) {
1629 Instruction::CastOps CastOpc = Cast0->getOpcode();
1630 Type *ResultType = Cast0->getType();
1631 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1632 return ConstantExpr::getCast(CastOpc, V, ResultType);
1633 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1634 return ConstantExpr::getCast(CastOpc, V, ResultType);
1635 }
1636 }
1637
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001638 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001639 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1640 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001641 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001642
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001643 // And distributes over Or. Try some generic simplifications based on this.
1644 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001645 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001646 return V;
1647
1648 // And distributes over Xor. Try some generic simplifications based on this.
1649 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001650 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001651 return V;
1652
Duncan Sandsb0579e92010-11-10 13:00:08 +00001653 // If the operation is with the result of a select instruction, check whether
1654 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001655 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001656 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1657 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001658 return V;
1659
1660 // If the operation is with the result of a phi instruction, check whether
1661 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001662 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001663 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001664 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001665 return V;
1666
Craig Topper9f008862014-04-15 04:59:12 +00001667 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001668}
1669
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001670Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001671 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001672 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001673 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001674 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001675 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001676}
1677
Sanjay Patel472cc782016-01-11 22:14:42 +00001678/// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1679/// contains all possible values.
David Majnemera315bd82014-09-15 08:15:28 +00001680static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1681 ICmpInst::Predicate Pred0, Pred1;
1682 ConstantInt *CI1, *CI2;
1683 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001684
1685 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1686 return X;
1687
David Majnemera315bd82014-09-15 08:15:28 +00001688 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1689 m_ConstantInt(CI2))))
1690 return nullptr;
1691
1692 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1693 return nullptr;
1694
1695 Type *ITy = Op0->getType();
1696
1697 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1698 bool isNSW = AddInst->hasNoSignedWrap();
1699 bool isNUW = AddInst->hasNoUnsignedWrap();
1700
1701 const APInt &CI1V = CI1->getValue();
1702 const APInt &CI2V = CI2->getValue();
1703 const APInt Delta = CI2V - CI1V;
1704 if (CI1V.isStrictlyPositive()) {
1705 if (Delta == 2) {
1706 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1707 return getTrue(ITy);
1708 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1709 return getTrue(ITy);
1710 }
1711 if (Delta == 1) {
1712 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1713 return getTrue(ITy);
1714 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1715 return getTrue(ITy);
1716 }
1717 }
1718 if (CI1V.getBoolValue() && isNUW) {
1719 if (Delta == 2)
1720 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1721 return getTrue(ITy);
1722 if (Delta == 1)
1723 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1724 return getTrue(ITy);
1725 }
1726
1727 return nullptr;
1728}
1729
Sanjay Patel472cc782016-01-11 22:14:42 +00001730/// Given operands for an Or, see if we can fold the result.
1731/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001732static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1733 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001734 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001735 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1736 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001737
Chris Lattnera71e9d62009-11-10 00:55:12 +00001738 // Canonicalize the constant to the RHS.
1739 std::swap(Op0, Op1);
1740 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001741
Chris Lattnera71e9d62009-11-10 00:55:12 +00001742 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001743 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001744 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001745
Chris Lattnera71e9d62009-11-10 00:55:12 +00001746 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001747 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001748 return Op0;
1749
Duncan Sandsc89ac072010-11-17 18:52:15 +00001750 // X | 0 = X
1751 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001752 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001753
Duncan Sandsc89ac072010-11-17 18:52:15 +00001754 // X | -1 = -1
1755 if (match(Op1, m_AllOnes()))
1756 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001757
Chris Lattnera71e9d62009-11-10 00:55:12 +00001758 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001759 if (match(Op0, m_Not(m_Specific(Op1))) ||
1760 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001761 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001762
Chris Lattnera71e9d62009-11-10 00:55:12 +00001763 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001764 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001765 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001766 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001767 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001768
Chris Lattnera71e9d62009-11-10 00:55:12 +00001769 // A | (A & ?) = A
1770 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001771 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001772 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001773
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001774 // ~(A & ?) | A = -1
1775 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1776 (A == Op1 || B == Op1))
1777 return Constant::getAllOnesValue(Op1->getType());
1778
1779 // A | ~(A & ?) = -1
1780 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781 (A == Op0 || B == Op0))
1782 return Constant::getAllOnesValue(Op0->getType());
1783
David Majnemera315bd82014-09-15 08:15:28 +00001784 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1785 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1786 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1787 return V;
1788 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1789 return V;
1790 }
1791 }
1792
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001793 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001794 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1795 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001796 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001797
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001798 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001799 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1800 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001801 return V;
1802
Duncan Sandsb0579e92010-11-10 13:00:08 +00001803 // If the operation is with the result of a select instruction, check whether
1804 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001805 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001806 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001807 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001808 return V;
1809
Nick Lewycky8561a492014-06-19 03:51:46 +00001810 // (A & C)|(B & D)
1811 Value *C = nullptr, *D = nullptr;
1812 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1813 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1814 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1815 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1816 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1817 // (A & C1)|(B & C2)
1818 // If we have: ((V + N) & C1) | (V & C2)
1819 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1820 // replace with V+N.
1821 Value *V1, *V2;
1822 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1823 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1824 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001825 if (V1 == B &&
1826 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001827 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001828 if (V2 == B &&
1829 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001830 return A;
1831 }
1832 // Or commutes, try both ways.
1833 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1834 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1835 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001836 if (V1 == A &&
1837 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001838 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001839 if (V2 == A &&
1840 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001841 return B;
1842 }
1843 }
1844 }
1845
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001846 // If the operation is with the result of a phi instruction, check whether
1847 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001848 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001849 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001850 return V;
1851
Craig Topper9f008862014-04-15 04:59:12 +00001852 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001853}
1854
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001855Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001856 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001857 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001858 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001859 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001860 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001861}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001862
Sanjay Patel472cc782016-01-11 22:14:42 +00001863/// Given operands for a Xor, see if we can fold the result.
1864/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001865static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1866 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001867 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001868 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1869 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001870
1871 // Canonicalize the constant to the RHS.
1872 std::swap(Op0, Op1);
1873 }
1874
1875 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001876 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001877 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001878
1879 // A ^ 0 = A
1880 if (match(Op1, m_Zero()))
1881 return Op0;
1882
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001883 // A ^ A = 0
1884 if (Op0 == Op1)
1885 return Constant::getNullValue(Op0->getType());
1886
Duncan Sandsc89ac072010-11-17 18:52:15 +00001887 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001888 if (match(Op0, m_Not(m_Specific(Op1))) ||
1889 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001890 return Constant::getAllOnesValue(Op0->getType());
1891
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001892 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001893 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1894 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001895 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001896
Duncan Sandsb238de02010-11-19 09:20:39 +00001897 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1898 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1899 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1900 // only if B and C are equal. If B and C are equal then (since we assume
1901 // that operands have already been simplified) "select(cond, B, C)" should
1902 // have been simplified to the common value of B and C already. Analysing
1903 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1904 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001905
Craig Topper9f008862014-04-15 04:59:12 +00001906 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001907}
1908
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001909Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001910 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001911 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001912 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001913 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001914 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001915}
1916
Chris Lattner229907c2011-07-18 04:54:35 +00001917static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001918 return CmpInst::makeCmpResultType(Op->getType());
1919}
1920
Sanjay Patel472cc782016-01-11 22:14:42 +00001921/// Rummage around inside V looking for something equivalent to the comparison
1922/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1923/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001924static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1925 Value *LHS, Value *RHS) {
1926 SelectInst *SI = dyn_cast<SelectInst>(V);
1927 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001928 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001929 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1930 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001931 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001932 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1933 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1934 return Cmp;
1935 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1936 LHS == CmpRHS && RHS == CmpLHS)
1937 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001938 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001939}
1940
Dan Gohman9631d902013-02-01 00:49:06 +00001941// A significant optimization not implemented here is assuming that alloca
1942// addresses are not equal to incoming argument values. They don't *alias*,
1943// as we say, but that doesn't mean they aren't equal, so we take a
1944// conservative approach.
1945//
1946// This is inspired in part by C++11 5.10p1:
1947// "Two pointers of the same type compare equal if and only if they are both
1948// null, both point to the same function, or both represent the same
1949// address."
1950//
1951// This is pretty permissive.
1952//
1953// It's also partly due to C11 6.5.9p6:
1954// "Two pointers compare equal if and only if both are null pointers, both are
1955// pointers to the same object (including a pointer to an object and a
1956// subobject at its beginning) or function, both are pointers to one past the
1957// last element of the same array object, or one is a pointer to one past the
1958// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001959// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001960// object in the address space.)
1961//
1962// C11's version is more restrictive, however there's no reason why an argument
1963// couldn't be a one-past-the-end value for a stack object in the caller and be
1964// equal to the beginning of a stack object in the callee.
1965//
1966// If the C and C++ standards are ever made sufficiently restrictive in this
1967// area, it may be possible to update LLVM's semantics accordingly and reinstate
1968// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00001969static Constant *
1970computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1971 const DominatorTree *DT, CmpInst::Predicate Pred,
1972 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001973 // First, skip past any trivial no-ops.
1974 LHS = LHS->stripPointerCasts();
1975 RHS = RHS->stripPointerCasts();
1976
1977 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001978 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001979 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1980 return ConstantInt::get(GetCompareTy(LHS),
1981 !CmpInst::isTrueWhenEqual(Pred));
1982
Chandler Carruth8059c842012-03-25 21:28:14 +00001983 // We can only fold certain predicates on pointer comparisons.
1984 switch (Pred) {
1985 default:
Craig Topper9f008862014-04-15 04:59:12 +00001986 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001987
1988 // Equality comaprisons are easy to fold.
1989 case CmpInst::ICMP_EQ:
1990 case CmpInst::ICMP_NE:
1991 break;
1992
1993 // We can only handle unsigned relational comparisons because 'inbounds' on
1994 // a GEP only protects against unsigned wrapping.
1995 case CmpInst::ICMP_UGT:
1996 case CmpInst::ICMP_UGE:
1997 case CmpInst::ICMP_ULT:
1998 case CmpInst::ICMP_ULE:
1999 // However, we have to switch them to their signed variants to handle
2000 // negative indices from the base pointer.
2001 Pred = ICmpInst::getSignedPredicate(Pred);
2002 break;
2003 }
2004
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002005 // Strip off any constant offsets so that we can reason about them.
2006 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2007 // here and compare base addresses like AliasAnalysis does, however there are
2008 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2009 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2010 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002011 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2012 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002013
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002014 // If LHS and RHS are related via constant offsets to the same base
2015 // value, we can replace it with an icmp which just compares the offsets.
2016 if (LHS == RHS)
2017 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002018
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002019 // Various optimizations for (in)equality comparisons.
2020 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2021 // Different non-empty allocations that exist at the same time have
2022 // different addresses (if the program can tell). Global variables always
2023 // exist, so they always exist during the lifetime of each other and all
2024 // allocas. Two different allocas usually have different addresses...
2025 //
2026 // However, if there's an @llvm.stackrestore dynamically in between two
2027 // allocas, they may have the same address. It's tempting to reduce the
2028 // scope of the problem by only looking at *static* allocas here. That would
2029 // cover the majority of allocas while significantly reducing the likelihood
2030 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2031 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2032 // an entry block. Also, if we have a block that's not attached to a
2033 // function, we can't tell if it's "static" under the current definition.
2034 // Theoretically, this problem could be fixed by creating a new kind of
2035 // instruction kind specifically for static allocas. Such a new instruction
2036 // could be required to be at the top of the entry block, thus preventing it
2037 // from being subject to a @llvm.stackrestore. Instcombine could even
2038 // convert regular allocas into these special allocas. It'd be nifty.
2039 // However, until then, this problem remains open.
2040 //
2041 // So, we'll assume that two non-empty allocas have different addresses
2042 // for now.
2043 //
2044 // With all that, if the offsets are within the bounds of their allocations
2045 // (and not one-past-the-end! so we can't use inbounds!), and their
2046 // allocations aren't the same, the pointers are not equal.
2047 //
2048 // Note that it's not necessary to check for LHS being a global variable
2049 // address, due to canonicalization and constant folding.
2050 if (isa<AllocaInst>(LHS) &&
2051 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002052 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2053 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002054 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002055 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002056 getObjectSize(LHS, LHSSize, DL, TLI) &&
2057 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002058 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2059 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002060 if (!LHSOffsetValue.isNegative() &&
2061 !RHSOffsetValue.isNegative() &&
2062 LHSOffsetValue.ult(LHSSize) &&
2063 RHSOffsetValue.ult(RHSSize)) {
2064 return ConstantInt::get(GetCompareTy(LHS),
2065 !CmpInst::isTrueWhenEqual(Pred));
2066 }
2067 }
2068
2069 // Repeat the above check but this time without depending on DataLayout
2070 // or being able to compute a precise size.
2071 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2072 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2073 LHSOffset->isNullValue() &&
2074 RHSOffset->isNullValue())
2075 return ConstantInt::get(GetCompareTy(LHS),
2076 !CmpInst::isTrueWhenEqual(Pred));
2077 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002078
2079 // Even if an non-inbounds GEP occurs along the path we can still optimize
2080 // equality comparisons concerning the result. We avoid walking the whole
2081 // chain again by starting where the last calls to
2082 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002083 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2084 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002085 if (LHS == RHS)
2086 return ConstantExpr::getICmp(Pred,
2087 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2088 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002089
2090 // If one side of the equality comparison must come from a noalias call
2091 // (meaning a system memory allocation function), and the other side must
2092 // come from a pointer that cannot overlap with dynamically-allocated
2093 // memory within the lifetime of the current function (allocas, byval
2094 // arguments, globals), then determine the comparison result here.
2095 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2096 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2097 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2098
2099 // Is the set of underlying objects all noalias calls?
2100 auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
Craig Topperb4b66d02015-11-29 04:37:14 +00002101 return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002102 };
2103
2104 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002105 // noalias calls. For allocas, we consider only static ones (dynamic
2106 // allocas might be transformed into calls to malloc not simultaneously
2107 // live with the compared-to allocation). For globals, we exclude symbols
2108 // that might be resolve lazily to symbols in another dynamically-loaded
2109 // library (and, thus, could be malloc'ed by the implementation).
Hal Finkelafcd8db2014-12-01 23:38:06 +00002110 auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002111 return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2112 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2113 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2114 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2115 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002116 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002117 !GV->isThreadLocal();
2118 if (const Argument *A = dyn_cast<Argument>(V))
2119 return A->hasByValAttr();
2120 return false;
2121 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002122 };
2123
2124 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2125 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2126 return ConstantInt::get(GetCompareTy(LHS),
2127 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002128
2129 // Fold comparisons for non-escaping pointer even if the allocation call
2130 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2131 // dynamic allocation call could be either of the operands.
2132 Value *MI = nullptr;
2133 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT, TLI))
2134 MI = LHS;
2135 else if (isAllocLikeFn(RHS, TLI) &&
2136 llvm::isKnownNonNullAt(LHS, CxtI, DT, TLI))
2137 MI = RHS;
2138 // FIXME: We should also fold the compare when the pointer escapes, but the
2139 // compare dominates the pointer escape
2140 if (MI && !PointerMayBeCaptured(MI, true, true))
2141 return ConstantInt::get(GetCompareTy(LHS),
2142 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002143 }
2144
2145 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002146 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002147}
Chris Lattner01990f02012-02-24 19:01:58 +00002148
Sanjay Patel472cc782016-01-11 22:14:42 +00002149/// Given operands for an ICmpInst, see if we can fold the result.
2150/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002151static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002152 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00002153 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002154 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002155
Chris Lattnera71e9d62009-11-10 00:55:12 +00002156 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002157 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002158 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002159
2160 // If we have a constant, make sure it is on the RHS.
2161 std::swap(LHS, RHS);
2162 Pred = CmpInst::getSwappedPredicate(Pred);
2163 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002164
Chris Lattner229907c2011-07-18 04:54:35 +00002165 Type *ITy = GetCompareTy(LHS); // The return type.
2166 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002167
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002168 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002169 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2170 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002171 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002172 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002173
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002174 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00002175 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002176 switch (Pred) {
2177 default: break;
2178 case ICmpInst::ICMP_EQ:
2179 // X == 1 -> X
2180 if (match(RHS, m_One()))
2181 return LHS;
2182 break;
2183 case ICmpInst::ICMP_NE:
2184 // X != 0 -> X
2185 if (match(RHS, m_Zero()))
2186 return LHS;
2187 break;
2188 case ICmpInst::ICMP_UGT:
2189 // X >u 0 -> X
2190 if (match(RHS, m_Zero()))
2191 return LHS;
2192 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002193 case ICmpInst::ICMP_UGE: {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002194 // X >=u 1 -> X
2195 if (match(RHS, m_One()))
2196 return LHS;
Chad Rosier41dd31f2016-04-20 19:15:26 +00002197 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002198 return getTrue(ITy);
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002199 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002200 }
2201 case ICmpInst::ICMP_SGE: {
Junmo Park53470fc2016-04-05 21:14:31 +00002202 /// For signed comparison, the values for an i1 are 0 and -1
Philip Reamesdbbd7792015-10-29 03:19:10 +00002203 /// respectively. This maps into a truth table of:
2204 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2205 /// 0 | 0 | 1 (0 >= 0) | 1
2206 /// 0 | 1 | 1 (0 >= -1) | 1
2207 /// 1 | 0 | 0 (-1 >= 0) | 0
2208 /// 1 | 1 | 1 (-1 >= -1) | 1
Chad Rosier41dd31f2016-04-20 19:15:26 +00002209 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reamesdbbd7792015-10-29 03:19:10 +00002210 return getTrue(ITy);
2211 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002212 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002213 case ICmpInst::ICMP_SLT:
2214 // X <s 0 -> X
2215 if (match(RHS, m_Zero()))
2216 return LHS;
2217 break;
2218 case ICmpInst::ICMP_SLE:
2219 // X <=s -1 -> X
2220 if (match(RHS, m_One()))
2221 return LHS;
2222 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002223 case ICmpInst::ICMP_ULE: {
Chad Rosier41dd31f2016-04-20 19:15:26 +00002224 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002225 return getTrue(ITy);
2226 break;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002227 }
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002228 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002229 }
2230
Duncan Sandsd3951082011-01-25 09:38:29 +00002231 // If we are comparing with zero then try hard since this is a common case.
2232 if (match(RHS, m_Zero())) {
2233 bool LHSKnownNonNegative, LHSKnownNegative;
2234 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002235 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00002236 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002237 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002238 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002239 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002240 case ICmpInst::ICMP_EQ:
2241 case ICmpInst::ICMP_ULE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002242 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002243 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002244 break;
2245 case ICmpInst::ICMP_NE:
2246 case ICmpInst::ICMP_UGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002247 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002248 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002249 break;
2250 case ICmpInst::ICMP_SLT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002251 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2252 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002253 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002254 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002255 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002256 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002257 break;
2258 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002259 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2260 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002261 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002262 return getTrue(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002263 if (LHSKnownNonNegative &&
2264 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002265 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002266 break;
2267 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002268 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2269 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002270 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002271 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002272 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002273 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002274 break;
2275 case ICmpInst::ICMP_SGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002276 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2277 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002278 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002279 return getFalse(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002280 if (LHSKnownNonNegative &&
2281 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002282 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002283 break;
2284 }
2285 }
2286
2287 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002288 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002289 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2290 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2291 if (RHS_CR.isEmptySet())
2292 return ConstantInt::getFalse(CI->getContext());
2293 if (RHS_CR.isFullSet())
2294 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002295
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002296 // Many binary operators with constant RHS have easy to compute constant
2297 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002298 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002299 APInt Lower = APInt(Width, 0);
2300 APInt Upper = APInt(Width, 0);
2301 ConstantInt *CI2;
2302 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2303 // 'urem x, CI2' produces [0, CI2).
2304 Upper = CI2->getValue();
2305 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2306 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2307 Upper = CI2->getValue().abs();
2308 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002309 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2310 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002311 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002312 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2313 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2314 APInt NegOne = APInt::getAllOnesValue(Width);
2315 if (!CI2->isZero())
2316 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002317 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00002318 if (CI2->isMinSignedValue()) {
2319 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2320 Lower = CI2->getValue();
2321 Upper = Lower.lshr(1) + 1;
2322 } else {
2323 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2324 Upper = CI2->getValue().abs() + 1;
2325 Lower = (-Upper) + 1;
2326 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002327 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002328 APInt IntMin = APInt::getSignedMinValue(Width);
2329 APInt IntMax = APInt::getSignedMaxValue(Width);
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002330 const APInt &Val = CI2->getValue();
David Majnemeraf9180f2014-07-14 20:38:45 +00002331 if (Val.isAllOnesValue()) {
2332 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2333 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2334 Lower = IntMin + 1;
2335 Upper = IntMax + 1;
2336 } else if (Val.countLeadingZeros() < Width - 1) {
2337 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2338 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002339 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00002340 Upper = IntMax.sdiv(Val);
2341 if (Lower.sgt(Upper))
2342 std::swap(Lower, Upper);
2343 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00002344 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002345 }
David Majnemerd6d16712014-08-27 18:03:46 +00002346 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2347 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2348 Lower = CI2->getValue();
2349 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2350 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2351 if (CI2->isNegative()) {
2352 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2353 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2354 Lower = CI2->getValue().shl(ShiftAmount);
2355 Upper = CI2->getValue() + 1;
2356 } else {
2357 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2358 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2359 Lower = CI2->getValue();
2360 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2361 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002362 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2363 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2364 APInt NegOne = APInt::getAllOnesValue(Width);
2365 if (CI2->getValue().ult(Width))
2366 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002367 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2368 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2369 unsigned ShiftAmount = Width - 1;
2370 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2371 ShiftAmount = CI2->getValue().countTrailingZeros();
2372 Lower = CI2->getValue().lshr(ShiftAmount);
2373 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002374 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2375 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2376 APInt IntMin = APInt::getSignedMinValue(Width);
2377 APInt IntMax = APInt::getSignedMaxValue(Width);
2378 if (CI2->getValue().ult(Width)) {
2379 Lower = IntMin.ashr(CI2->getValue());
2380 Upper = IntMax.ashr(CI2->getValue()) + 1;
2381 }
David Majnemer78910fc2014-05-16 17:14:03 +00002382 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2383 unsigned ShiftAmount = Width - 1;
2384 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2385 ShiftAmount = CI2->getValue().countTrailingZeros();
2386 if (CI2->isNegative()) {
2387 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2388 Lower = CI2->getValue();
2389 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2390 } else {
2391 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2392 Lower = CI2->getValue().ashr(ShiftAmount);
2393 Upper = CI2->getValue() + 1;
2394 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002395 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2396 // 'or x, CI2' produces [CI2, UINT_MAX].
2397 Lower = CI2->getValue();
2398 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2399 // 'and x, CI2' produces [0, CI2].
2400 Upper = CI2->getValue() + 1;
David Majnemer2df38cd2015-08-20 23:01:41 +00002401 } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2402 // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2403 Lower = CI2->getValue();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002404 }
Chen Li5cd6dee2015-09-23 17:58:44 +00002405
2406 ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2407 : ConstantRange(Width, true);
2408
2409 if (auto *I = dyn_cast<Instruction>(LHS))
2410 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002411 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
Chen Li5cd6dee2015-09-23 17:58:44 +00002412
2413 if (!LHS_CR.isFullSet()) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002414 if (RHS_CR.contains(LHS_CR))
2415 return ConstantInt::getTrue(RHS->getContext());
2416 if (RHS_CR.inverse().contains(LHS_CR))
2417 return ConstantInt::getFalse(RHS->getContext());
2418 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002419 }
2420
Chen Li7452d952015-09-26 03:26:47 +00002421 // If both operands have range metadata, use the metadata
2422 // to simplify the comparison.
2423 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2424 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2425 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2426
2427 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2428 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002429 auto RHS_CR = getConstantRangeFromMetadata(
2430 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2431 auto LHS_CR = getConstantRangeFromMetadata(
2432 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00002433
2434 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2435 if (Satisfied_CR.contains(LHS_CR))
2436 return ConstantInt::getTrue(RHS->getContext());
2437
2438 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2439 CmpInst::getInversePredicate(Pred), RHS_CR);
2440 if (InversedSatisfied_CR.contains(LHS_CR))
2441 return ConstantInt::getFalse(RHS->getContext());
2442 }
2443 }
2444
Duncan Sands8fb2c382011-01-20 13:21:55 +00002445 // Compare of cast, for example (zext X) != 0 -> X != 0
2446 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2447 Instruction *LI = cast<CastInst>(LHS);
2448 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002449 Type *SrcTy = SrcOp->getType();
2450 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002451
2452 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2453 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002454 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2455 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002456 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2457 // Transfer the cast to the constant.
2458 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2459 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002460 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002461 return V;
2462 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2463 if (RI->getOperand(0)->getType() == SrcTy)
2464 // Compare without the cast.
2465 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002466 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002467 return V;
2468 }
2469 }
2470
2471 if (isa<ZExtInst>(LHS)) {
2472 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2473 // same type.
2474 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2475 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2476 // Compare X and Y. Note that signed predicates become unsigned.
2477 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002478 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002479 MaxRecurse-1))
2480 return V;
2481 }
2482 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2483 // too. If not, then try to deduce the result of the comparison.
2484 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2485 // Compute the constant that would happen if we truncated to SrcTy then
2486 // reextended to DstTy.
2487 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2488 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2489
2490 // If the re-extended constant didn't change then this is effectively
2491 // also a case of comparing two zero-extended values.
2492 if (RExt == CI && MaxRecurse)
2493 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002494 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002495 return V;
2496
2497 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2498 // there. Use this to work out the result of the comparison.
2499 if (RExt != CI) {
2500 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002501 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002502 // LHS <u RHS.
2503 case ICmpInst::ICMP_EQ:
2504 case ICmpInst::ICMP_UGT:
2505 case ICmpInst::ICMP_UGE:
2506 return ConstantInt::getFalse(CI->getContext());
2507
2508 case ICmpInst::ICMP_NE:
2509 case ICmpInst::ICMP_ULT:
2510 case ICmpInst::ICMP_ULE:
2511 return ConstantInt::getTrue(CI->getContext());
2512
2513 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2514 // is non-negative then LHS <s RHS.
2515 case ICmpInst::ICMP_SGT:
2516 case ICmpInst::ICMP_SGE:
2517 return CI->getValue().isNegative() ?
2518 ConstantInt::getTrue(CI->getContext()) :
2519 ConstantInt::getFalse(CI->getContext());
2520
2521 case ICmpInst::ICMP_SLT:
2522 case ICmpInst::ICMP_SLE:
2523 return CI->getValue().isNegative() ?
2524 ConstantInt::getFalse(CI->getContext()) :
2525 ConstantInt::getTrue(CI->getContext());
2526 }
2527 }
2528 }
2529 }
2530
2531 if (isa<SExtInst>(LHS)) {
2532 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2533 // same type.
2534 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2535 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2536 // Compare X and Y. Note that the predicate does not change.
2537 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002538 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002539 return V;
2540 }
2541 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2542 // too. If not, then try to deduce the result of the comparison.
2543 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2544 // Compute the constant that would happen if we truncated to SrcTy then
2545 // reextended to DstTy.
2546 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2547 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2548
2549 // If the re-extended constant didn't change then this is effectively
2550 // also a case of comparing two sign-extended values.
2551 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002552 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002553 return V;
2554
2555 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2556 // bits there. Use this to work out the result of the comparison.
2557 if (RExt != CI) {
2558 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002559 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002560 case ICmpInst::ICMP_EQ:
2561 return ConstantInt::getFalse(CI->getContext());
2562 case ICmpInst::ICMP_NE:
2563 return ConstantInt::getTrue(CI->getContext());
2564
2565 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2566 // LHS >s RHS.
2567 case ICmpInst::ICMP_SGT:
2568 case ICmpInst::ICMP_SGE:
2569 return CI->getValue().isNegative() ?
2570 ConstantInt::getTrue(CI->getContext()) :
2571 ConstantInt::getFalse(CI->getContext());
2572 case ICmpInst::ICMP_SLT:
2573 case ICmpInst::ICMP_SLE:
2574 return CI->getValue().isNegative() ?
2575 ConstantInt::getFalse(CI->getContext()) :
2576 ConstantInt::getTrue(CI->getContext());
2577
2578 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2579 // LHS >u RHS.
2580 case ICmpInst::ICMP_UGT:
2581 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002582 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002583 if (MaxRecurse)
2584 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2585 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002586 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002587 return V;
2588 break;
2589 case ICmpInst::ICMP_ULT:
2590 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002591 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002592 if (MaxRecurse)
2593 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2594 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002595 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002596 return V;
2597 break;
2598 }
2599 }
2600 }
2601 }
2602 }
2603
James Molloy1d88d6f2015-10-22 13:18:42 +00002604 // icmp eq|ne X, Y -> false|true if X != Y
2605 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2606 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2607 LLVMContext &Ctx = LHS->getType()->getContext();
2608 return Pred == ICmpInst::ICMP_NE ?
2609 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2610 }
Junmo Park53470fc2016-04-05 21:14:31 +00002611
Duncan Sandsd114ab32011-02-13 17:15:40 +00002612 // Special logic for binary operators.
2613 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2614 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2615 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002616 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002617 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002618 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2619 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2620 if (LBO && LBO->getOpcode() == Instruction::Add) {
2621 A = LBO->getOperand(0); B = LBO->getOperand(1);
2622 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2623 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2624 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2625 }
2626 if (RBO && RBO->getOpcode() == Instruction::Add) {
2627 C = RBO->getOperand(0); D = RBO->getOperand(1);
2628 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2629 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2630 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2631 }
2632
2633 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2634 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2635 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2636 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002637 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002638 return V;
2639
2640 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2641 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2642 if (Value *V = SimplifyICmpInst(Pred,
2643 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002644 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002645 return V;
2646
2647 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2648 if (A && C && (A == C || A == D || B == C || B == D) &&
2649 NoLHSWrapProblem && NoRHSWrapProblem) {
2650 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002651 Value *Y, *Z;
2652 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002653 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002654 Y = B;
2655 Z = D;
2656 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002657 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002658 Y = B;
2659 Z = C;
2660 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002661 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002662 Y = A;
2663 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002664 } else {
2665 assert(B == D);
2666 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002667 Y = A;
2668 Z = C;
2669 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002670 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002671 return V;
2672 }
2673 }
2674
Nick Lewycky762f8a82016-04-21 00:53:14 +00002675 {
2676 Value *Y = nullptr;
2677 // icmp pred (or X, Y), X
2678 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2679 if (Pred == ICmpInst::ICMP_ULT)
2680 return getFalse(ITy);
2681 if (Pred == ICmpInst::ICMP_UGE)
2682 return getTrue(ITy);
2683
2684 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2685 bool RHSKnownNonNegative, RHSKnownNegative;
2686 bool YKnownNonNegative, YKnownNegative;
2687 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2688 Q.AC, Q.CxtI, Q.DT);
2689 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2690 Q.CxtI, Q.DT);
2691 if (RHSKnownNonNegative && YKnownNegative)
2692 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2693 if (RHSKnownNegative || YKnownNonNegative)
2694 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2695 }
2696 }
2697 // icmp pred X, (or X, Y)
2698 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2699 if (Pred == ICmpInst::ICMP_ULE)
2700 return getTrue(ITy);
2701 if (Pred == ICmpInst::ICMP_UGT)
2702 return getFalse(ITy);
2703
2704 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2705 bool LHSKnownNonNegative, LHSKnownNegative;
2706 bool YKnownNonNegative, YKnownNegative;
2707 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2708 Q.AC, Q.CxtI, Q.DT);
2709 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2710 Q.CxtI, Q.DT);
2711 if (LHSKnownNonNegative && YKnownNegative)
2712 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2713 if (LHSKnownNegative || YKnownNonNegative)
2714 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2715 }
2716 }
David Majnemerbd9ce4e2014-11-25 02:55:48 +00002717 }
2718
2719 // icmp pred (and X, Y), X
2720 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2721 m_And(m_Specific(RHS), m_Value())))) {
2722 if (Pred == ICmpInst::ICMP_UGT)
2723 return getFalse(ITy);
2724 if (Pred == ICmpInst::ICMP_ULE)
2725 return getTrue(ITy);
2726 }
2727 // icmp pred X, (and X, Y)
2728 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2729 m_And(m_Specific(LHS), m_Value())))) {
2730 if (Pred == ICmpInst::ICMP_UGE)
2731 return getTrue(ITy);
2732 if (Pred == ICmpInst::ICMP_ULT)
2733 return getFalse(ITy);
2734 }
2735
David Majnemer2d6c0232014-05-14 20:16:28 +00002736 // 0 - (zext X) pred C
2737 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2738 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2739 if (RHSC->getValue().isStrictlyPositive()) {
2740 if (Pred == ICmpInst::ICMP_SLT)
2741 return ConstantInt::getTrue(RHSC->getContext());
2742 if (Pred == ICmpInst::ICMP_SGE)
2743 return ConstantInt::getFalse(RHSC->getContext());
2744 if (Pred == ICmpInst::ICMP_EQ)
2745 return ConstantInt::getFalse(RHSC->getContext());
2746 if (Pred == ICmpInst::ICMP_NE)
2747 return ConstantInt::getTrue(RHSC->getContext());
2748 }
2749 if (RHSC->getValue().isNonNegative()) {
2750 if (Pred == ICmpInst::ICMP_SLE)
2751 return ConstantInt::getTrue(RHSC->getContext());
2752 if (Pred == ICmpInst::ICMP_SGT)
2753 return ConstantInt::getFalse(RHSC->getContext());
2754 }
2755 }
2756 }
2757
Nick Lewycky35aeea92013-07-12 23:42:57 +00002758 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002759 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002760 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002761 switch (Pred) {
2762 default:
2763 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002764 case ICmpInst::ICMP_SGT:
2765 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002766 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2767 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002768 if (!KnownNonNegative)
2769 break;
2770 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002771 case ICmpInst::ICMP_EQ:
2772 case ICmpInst::ICMP_UGT:
2773 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002774 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002775 case ICmpInst::ICMP_SLT:
2776 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002777 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2778 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002779 if (!KnownNonNegative)
2780 break;
2781 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002782 case ICmpInst::ICMP_NE:
2783 case ICmpInst::ICMP_ULT:
2784 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002785 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002786 }
2787 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002788
2789 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002790 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2791 bool KnownNonNegative, KnownNegative;
2792 switch (Pred) {
2793 default:
2794 break;
2795 case ICmpInst::ICMP_SGT:
2796 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002797 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2798 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002799 if (!KnownNonNegative)
2800 break;
2801 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002802 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002803 case ICmpInst::ICMP_UGT:
2804 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002805 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002806 case ICmpInst::ICMP_SLT:
2807 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002808 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2809 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002810 if (!KnownNonNegative)
2811 break;
2812 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002813 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002814 case ICmpInst::ICMP_ULT:
2815 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002816 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002817 }
2818 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002819
David Majnemer3af5bf32016-01-21 18:55:54 +00002820 // x >> y <=u x
Duncan Sands92af0a82011-10-28 18:17:44 +00002821 // x udiv y <=u x.
David Majnemer3af5bf32016-01-21 18:55:54 +00002822 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2823 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2824 // icmp pred (X op Y), X
Duncan Sands92af0a82011-10-28 18:17:44 +00002825 if (Pred == ICmpInst::ICMP_UGT)
2826 return getFalse(ITy);
2827 if (Pred == ICmpInst::ICMP_ULE)
2828 return getTrue(ITy);
2829 }
2830
David Majnemer76d06bc2014-08-28 03:34:28 +00002831 // handle:
2832 // CI2 << X == CI
2833 // CI2 << X != CI
2834 //
2835 // where CI2 is a power of 2 and CI isn't
2836 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2837 const APInt *CI2Val, *CIVal = &CI->getValue();
2838 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2839 CI2Val->isPowerOf2()) {
2840 if (!CIVal->isPowerOf2()) {
2841 // CI2 << X can equal zero in some circumstances,
2842 // this simplification is unsafe if CI is zero.
2843 //
2844 // We know it is safe if:
2845 // - The shift is nsw, we can't shift out the one bit.
2846 // - The shift is nuw, we can't shift out the one bit.
2847 // - CI2 is one
2848 // - CI isn't zero
2849 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2850 *CI2Val == 1 || !CI->isZero()) {
2851 if (Pred == ICmpInst::ICMP_EQ)
2852 return ConstantInt::getFalse(RHS->getContext());
2853 if (Pred == ICmpInst::ICMP_NE)
2854 return ConstantInt::getTrue(RHS->getContext());
2855 }
2856 }
2857 if (CIVal->isSignBit() && *CI2Val == 1) {
2858 if (Pred == ICmpInst::ICMP_UGT)
2859 return ConstantInt::getFalse(RHS->getContext());
2860 if (Pred == ICmpInst::ICMP_ULE)
2861 return ConstantInt::getTrue(RHS->getContext());
2862 }
2863 }
2864 }
2865
Nick Lewycky9719a712011-03-05 05:19:11 +00002866 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2867 LBO->getOperand(1) == RBO->getOperand(1)) {
2868 switch (LBO->getOpcode()) {
2869 default: break;
2870 case Instruction::UDiv:
2871 case Instruction::LShr:
2872 if (ICmpInst::isSigned(Pred))
2873 break;
2874 // fall-through
2875 case Instruction::SDiv:
2876 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002877 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002878 break;
2879 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002880 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002881 return V;
2882 break;
2883 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002884 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002885 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2886 if (!NUW && !NSW)
2887 break;
2888 if (!NSW && ICmpInst::isSigned(Pred))
2889 break;
2890 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002891 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002892 return V;
2893 break;
2894 }
2895 }
2896 }
2897
Duncan Sands0a9c1242011-05-03 19:53:10 +00002898 // Simplify comparisons involving max/min.
2899 Value *A, *B;
2900 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002901 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002902
Duncan Sandsa2287852011-05-04 16:05:05 +00002903 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002904 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2905 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002906 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002907 // We analyze this as smax(A, B) pred A.
2908 P = Pred;
2909 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2910 (A == LHS || B == LHS)) {
2911 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002912 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002913 // We analyze this as smax(A, B) swapped-pred A.
2914 P = CmpInst::getSwappedPredicate(Pred);
2915 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2916 (A == RHS || B == RHS)) {
2917 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002918 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002919 // We analyze this as smax(-A, -B) swapped-pred -A.
2920 // Note that we do not need to actually form -A or -B thanks to EqP.
2921 P = CmpInst::getSwappedPredicate(Pred);
2922 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2923 (A == LHS || B == LHS)) {
2924 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002925 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002926 // We analyze this as smax(-A, -B) pred -A.
2927 // Note that we do not need to actually form -A or -B thanks to EqP.
2928 P = Pred;
2929 }
2930 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2931 // Cases correspond to "max(A, B) p A".
2932 switch (P) {
2933 default:
2934 break;
2935 case CmpInst::ICMP_EQ:
2936 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002937 // Equivalent to "A EqP B". This may be the same as the condition tested
2938 // in the max/min; if so, we can just return that.
2939 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2940 return V;
2941 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2942 return V;
2943 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002944 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002945 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002946 return V;
2947 break;
2948 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002949 case CmpInst::ICMP_SGT: {
2950 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2951 // Equivalent to "A InvEqP B". This may be the same as the condition
2952 // tested in the max/min; if so, we can just return that.
2953 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2954 return V;
2955 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2956 return V;
2957 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002958 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002959 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002960 return V;
2961 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002962 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002963 case CmpInst::ICMP_SGE:
2964 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002965 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002966 case CmpInst::ICMP_SLT:
2967 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002968 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002969 }
2970 }
2971
Duncan Sandsa2287852011-05-04 16:05:05 +00002972 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002973 P = CmpInst::BAD_ICMP_PREDICATE;
2974 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2975 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002976 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002977 // We analyze this as umax(A, B) pred A.
2978 P = Pred;
2979 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2980 (A == LHS || B == LHS)) {
2981 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002982 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002983 // We analyze this as umax(A, B) swapped-pred A.
2984 P = CmpInst::getSwappedPredicate(Pred);
2985 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2986 (A == RHS || B == RHS)) {
2987 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002988 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002989 // We analyze this as umax(-A, -B) swapped-pred -A.
2990 // Note that we do not need to actually form -A or -B thanks to EqP.
2991 P = CmpInst::getSwappedPredicate(Pred);
2992 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2993 (A == LHS || B == LHS)) {
2994 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002995 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002996 // We analyze this as umax(-A, -B) pred -A.
2997 // Note that we do not need to actually form -A or -B thanks to EqP.
2998 P = Pred;
2999 }
3000 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3001 // Cases correspond to "max(A, B) p A".
3002 switch (P) {
3003 default:
3004 break;
3005 case CmpInst::ICMP_EQ:
3006 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003007 // Equivalent to "A EqP B". This may be the same as the condition tested
3008 // in the max/min; if so, we can just return that.
3009 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3010 return V;
3011 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3012 return V;
3013 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003014 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003015 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003016 return V;
3017 break;
3018 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003019 case CmpInst::ICMP_UGT: {
3020 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3021 // Equivalent to "A InvEqP B". This may be the same as the condition
3022 // tested in the max/min; if so, we can just return that.
3023 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3024 return V;
3025 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3026 return V;
3027 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003028 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003029 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003030 return V;
3031 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003032 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003033 case CmpInst::ICMP_UGE:
3034 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003035 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003036 case CmpInst::ICMP_ULT:
3037 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003038 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003039 }
3040 }
3041
Duncan Sandsa2287852011-05-04 16:05:05 +00003042 // Variants on "max(x,y) >= min(x,z)".
3043 Value *C, *D;
3044 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3045 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3046 (A == C || A == D || B == C || B == D)) {
3047 // max(x, ?) pred min(x, ?).
3048 if (Pred == CmpInst::ICMP_SGE)
3049 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003050 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003051 if (Pred == CmpInst::ICMP_SLT)
3052 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003053 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003054 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3055 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3056 (A == C || A == D || B == C || B == D)) {
3057 // min(x, ?) pred max(x, ?).
3058 if (Pred == CmpInst::ICMP_SLE)
3059 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003060 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003061 if (Pred == CmpInst::ICMP_SGT)
3062 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003063 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003064 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3065 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3066 (A == C || A == D || B == C || B == D)) {
3067 // max(x, ?) pred min(x, ?).
3068 if (Pred == CmpInst::ICMP_UGE)
3069 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003070 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003071 if (Pred == CmpInst::ICMP_ULT)
3072 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003073 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003074 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3075 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3076 (A == C || A == D || B == C || B == D)) {
3077 // min(x, ?) pred max(x, ?).
3078 if (Pred == CmpInst::ICMP_ULE)
3079 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003080 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003081 if (Pred == CmpInst::ICMP_UGT)
3082 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003083 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003084 }
3085
Chandler Carruth8059c842012-03-25 21:28:14 +00003086 // Simplify comparisons of related pointers using a powerful, recursive
3087 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003088 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003089 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003090 return C;
3091
Nick Lewycky3db143e2012-02-26 02:09:49 +00003092 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3093 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3094 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3095 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3096 (ICmpInst::isEquality(Pred) ||
3097 (GLHS->isInBounds() && GRHS->isInBounds() &&
3098 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3099 // The bases are equal and the indices are constant. Build a constant
3100 // expression GEP with the same indices and a null base pointer to see
3101 // what constant folding can make out of it.
3102 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3103 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003104 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3105 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003106
3107 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003108 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3109 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003110 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3111 }
3112 }
3113 }
3114
David Majnemer5854e9f2014-11-16 02:20:08 +00003115 // If a bit is known to be zero for A and known to be one for B,
3116 // then A and B cannot be equal.
3117 if (ICmpInst::isEquality(Pred)) {
3118 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3119 uint32_t BitWidth = CI->getBitWidth();
3120 APInt LHSKnownZero(BitWidth, 0);
3121 APInt LHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003122 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003123 Q.CxtI, Q.DT);
3124 const APInt &RHSVal = CI->getValue();
3125 if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3126 return Pred == ICmpInst::ICMP_EQ
3127 ? ConstantInt::getFalse(CI->getContext())
3128 : ConstantInt::getTrue(CI->getContext());
3129 }
3130 }
3131
Duncan Sandsf532d312010-11-07 16:12:23 +00003132 // If the comparison is with the result of a select instruction, check whether
3133 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003134 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003135 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003136 return V;
3137
3138 // If the comparison is with the result of a phi instruction, check whether
3139 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003140 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003141 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003142 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003143
Craig Topper9f008862014-04-15 04:59:12 +00003144 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003145}
3146
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003147Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003148 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003149 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003150 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003151 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003152 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003153 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003154}
3155
Sanjay Patel472cc782016-01-11 22:14:42 +00003156/// Given operands for an FCmpInst, see if we can fold the result.
3157/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003158static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003159 FastMathFlags FMF, const Query &Q,
3160 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003161 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3162 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3163
Chris Lattnera71e9d62009-11-10 00:55:12 +00003164 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003165 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003166 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003167
Chris Lattnera71e9d62009-11-10 00:55:12 +00003168 // If we have a constant, make sure it is on the RHS.
3169 std::swap(LHS, RHS);
3170 Pred = CmpInst::getSwappedPredicate(Pred);
3171 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003172
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003173 // Fold trivial predicates.
3174 if (Pred == FCmpInst::FCMP_FALSE)
3175 return ConstantInt::get(GetCompareTy(LHS), 0);
3176 if (Pred == FCmpInst::FCMP_TRUE)
3177 return ConstantInt::get(GetCompareTy(LHS), 1);
3178
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003179 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3180 if (FMF.noNaNs()) {
3181 if (Pred == FCmpInst::FCMP_UNO)
3182 return ConstantInt::get(GetCompareTy(LHS), 0);
3183 if (Pred == FCmpInst::FCMP_ORD)
3184 return ConstantInt::get(GetCompareTy(LHS), 1);
3185 }
3186
Mehdi Aminieb242a52015-03-09 03:20:25 +00003187 // fcmp pred x, undef and fcmp pred undef, x
3188 // fold to true if unordered, false if ordered
3189 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3190 // Choosing NaN for the undef will always make unordered comparison succeed
3191 // and ordered comparison fail.
3192 return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3193 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003194
3195 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003196 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003197 if (CmpInst::isTrueWhenEqual(Pred))
3198 return ConstantInt::get(GetCompareTy(LHS), 1);
3199 if (CmpInst::isFalseWhenEqual(Pred))
3200 return ConstantInt::get(GetCompareTy(LHS), 0);
3201 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003202
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003203 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003204 const ConstantFP *CFP = nullptr;
3205 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3206 if (RHS->getType()->isVectorTy())
3207 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3208 else
3209 CFP = dyn_cast<ConstantFP>(RHSC);
3210 }
3211 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003212 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003213 if (CFP->getValueAPF().isNaN()) {
3214 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3215 return ConstantInt::getFalse(CFP->getContext());
3216 assert(FCmpInst::isUnordered(Pred) &&
3217 "Comparison must be either ordered or unordered!");
3218 // True if unordered.
David Majnemer3ee5f342016-04-13 06:55:52 +00003219 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003220 }
3221 // Check whether the constant is an infinity.
3222 if (CFP->getValueAPF().isInfinity()) {
3223 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003224 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003225 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003226 // No value is ordered and less than negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003227 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003228 case FCmpInst::FCMP_UGE:
3229 // All values are unordered with or at least negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003230 return ConstantInt::get(GetCompareTy(LHS), 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003231 default:
3232 break;
3233 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003234 } else {
3235 switch (Pred) {
3236 case FCmpInst::FCMP_OGT:
3237 // No value is ordered and greater than infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003238 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003239 case FCmpInst::FCMP_ULE:
3240 // All values are unordered with and at most infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003241 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003242 default:
3243 break;
3244 }
3245 }
3246 }
3247 if (CFP->getValueAPF().isZero()) {
3248 switch (Pred) {
3249 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003250 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3251 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003252 break;
3253 case FCmpInst::FCMP_OLT:
3254 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003255 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3256 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003257 break;
3258 default:
3259 break;
3260 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003261 }
3262 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003263
Duncan Sandsa620bd12010-11-07 16:46:25 +00003264 // If the comparison is with the result of a select instruction, check whether
3265 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003266 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003267 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003268 return V;
3269
3270 // If the comparison is with the result of a phi instruction, check whether
3271 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003272 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003273 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003274 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003275
Craig Topper9f008862014-04-15 04:59:12 +00003276 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003277}
3278
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003279Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003280 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003281 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003282 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003283 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003284 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3285 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003286}
3287
Sanjay Patel472cc782016-01-11 22:14:42 +00003288/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003289static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3290 const Query &Q,
3291 unsigned MaxRecurse) {
3292 // Trivial replacement.
3293 if (V == Op)
3294 return RepOp;
3295
3296 auto *I = dyn_cast<Instruction>(V);
3297 if (!I)
3298 return nullptr;
3299
3300 // If this is a binary operator, try to simplify it with the replaced op.
3301 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3302 // Consider:
3303 // %cmp = icmp eq i32 %x, 2147483647
3304 // %add = add nsw i32 %x, 1
3305 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3306 //
3307 // We can't replace %sel with %add unless we strip away the flags.
3308 if (isa<OverflowingBinaryOperator>(B))
3309 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3310 return nullptr;
3311 if (isa<PossiblyExactOperator>(B))
3312 if (B->isExact())
3313 return nullptr;
3314
3315 if (MaxRecurse) {
3316 if (B->getOperand(0) == Op)
3317 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3318 MaxRecurse - 1);
3319 if (B->getOperand(1) == Op)
3320 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3321 MaxRecurse - 1);
3322 }
3323 }
3324
3325 // Same for CmpInsts.
3326 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3327 if (MaxRecurse) {
3328 if (C->getOperand(0) == Op)
3329 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3330 MaxRecurse - 1);
3331 if (C->getOperand(1) == Op)
3332 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3333 MaxRecurse - 1);
3334 }
3335 }
3336
3337 // TODO: We could hand off more cases to instsimplify here.
3338
3339 // If all operands are constant after substituting Op for RepOp then we can
3340 // constant fold the instruction.
3341 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3342 // Build a list of all constant operands.
3343 SmallVector<Constant *, 8> ConstOps;
3344 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3345 if (I->getOperand(i) == Op)
3346 ConstOps.push_back(CRepOp);
3347 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3348 ConstOps.push_back(COp);
3349 else
3350 break;
3351 }
3352
3353 // All operands were constants, fold it.
3354 if (ConstOps.size() == I->getNumOperands()) {
3355 if (CmpInst *C = dyn_cast<CmpInst>(I))
3356 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3357 ConstOps[1], Q.DL, Q.TLI);
3358
3359 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3360 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003361 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003362
Manuel Jacobe9024592016-01-21 06:33:22 +00003363 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003364 }
3365 }
3366
3367 return nullptr;
3368}
3369
Sanjay Patel472cc782016-01-11 22:14:42 +00003370/// Given operands for a SelectInst, see if we can fold the result.
3371/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003372static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3373 Value *FalseVal, const Query &Q,
3374 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003375 // select true, X, Y -> X
3376 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003377 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3378 if (CB->isAllOnesValue())
3379 return TrueVal;
3380 if (CB->isNullValue())
3381 return FalseVal;
3382 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003383
Chris Lattnerc707fa92010-04-20 05:32:14 +00003384 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003385 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003386 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003387
Chris Lattnerc707fa92010-04-20 05:32:14 +00003388 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3389 if (isa<Constant>(TrueVal))
3390 return TrueVal;
3391 return FalseVal;
3392 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003393 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3394 return FalseVal;
3395 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3396 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003397
David Majnemer3f0fb982015-06-06 22:40:21 +00003398 if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3399 unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
David Majnemer7bd71442014-12-20 03:29:59 +00003400 ICmpInst::Predicate Pred = ICI->getPredicate();
David Majnemer3f0fb982015-06-06 22:40:21 +00003401 Value *CmpLHS = ICI->getOperand(0);
3402 Value *CmpRHS = ICI->getOperand(1);
David Majnemer147f8582014-12-20 04:45:33 +00003403 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003404 Value *X;
3405 const APInt *Y;
David Majnemer7bd71442014-12-20 03:29:59 +00003406 bool TrueWhenUnset;
David Majnemer147f8582014-12-20 04:45:33 +00003407 bool IsBitTest = false;
David Majnemer0b6a0b02014-12-20 03:04:38 +00003408 if (ICmpInst::isEquality(Pred) &&
David Majnemer3f0fb982015-06-06 22:40:21 +00003409 match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3410 match(CmpRHS, m_Zero())) {
David Majnemer7bd71442014-12-20 03:29:59 +00003411 IsBitTest = true;
3412 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
David Majnemer3f0fb982015-06-06 22:40:21 +00003413 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3414 X = CmpLHS;
David Majnemer7bd71442014-12-20 03:29:59 +00003415 Y = &MinSignedValue;
3416 IsBitTest = true;
3417 TrueWhenUnset = false;
David Majnemer3f0fb982015-06-06 22:40:21 +00003418 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3419 X = CmpLHS;
David Majnemer7bd71442014-12-20 03:29:59 +00003420 Y = &MinSignedValue;
3421 IsBitTest = true;
3422 TrueWhenUnset = true;
3423 }
3424 if (IsBitTest) {
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003425 const APInt *C;
3426 // (X & Y) == 0 ? X & ~Y : X --> X
3427 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3428 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3429 *Y == ~*C)
David Majnemer7bd71442014-12-20 03:29:59 +00003430 return TrueWhenUnset ? FalseVal : TrueVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003431 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3432 // (X & Y) != 0 ? X : X & ~Y --> X
3433 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3434 *Y == ~*C)
David Majnemer7bd71442014-12-20 03:29:59 +00003435 return TrueWhenUnset ? FalseVal : TrueVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003436
3437 if (Y->isPowerOf2()) {
3438 // (X & Y) == 0 ? X | Y : X --> X | Y
3439 // (X & Y) != 0 ? X | Y : X --> X
3440 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3441 *Y == *C)
David Majnemer7bd71442014-12-20 03:29:59 +00003442 return TrueWhenUnset ? TrueVal : FalseVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003443 // (X & Y) == 0 ? X : X | Y --> X
3444 // (X & Y) != 0 ? X : X | Y --> X | Y
3445 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3446 *Y == *C)
David Majnemer7bd71442014-12-20 03:29:59 +00003447 return TrueWhenUnset ? TrueVal : FalseVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003448 }
3449 }
David Majnemer3f0fb982015-06-06 22:40:21 +00003450 if (ICI->hasOneUse()) {
3451 const APInt *C;
3452 if (match(CmpRHS, m_APInt(C))) {
3453 // X < MIN ? T : F --> F
3454 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3455 return FalseVal;
3456 // X < MIN ? T : F --> F
3457 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3458 return FalseVal;
3459 // X > MAX ? T : F --> F
3460 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3461 return FalseVal;
3462 // X > MAX ? T : F --> F
3463 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3464 return FalseVal;
3465 }
3466 }
3467
3468 // If we have an equality comparison then we know the value in one of the
3469 // arms of the select. See if substituting this value into the arm and
3470 // simplifying the result yields the same value as the other arm.
3471 if (Pred == ICmpInst::ICMP_EQ) {
3472 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3473 TrueVal ||
3474 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3475 TrueVal)
3476 return FalseVal;
3477 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3478 FalseVal ||
3479 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3480 FalseVal)
3481 return FalseVal;
3482 } else if (Pred == ICmpInst::ICMP_NE) {
3483 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3484 FalseVal ||
3485 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3486 FalseVal)
3487 return TrueVal;
3488 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3489 TrueVal ||
3490 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3491 TrueVal)
3492 return TrueVal;
3493 }
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003494 }
3495
Craig Topper9f008862014-04-15 04:59:12 +00003496 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003497}
3498
Duncan Sandsb8cee002012-03-13 11:42:19 +00003499Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003500 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003501 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003502 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003503 const Instruction *CxtI) {
3504 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Chandler Carruth66b31302015-01-04 12:03:27 +00003505 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003506}
3507
Sanjay Patel472cc782016-01-11 22:14:42 +00003508/// Given operands for an GetElementPtrInst, see if we can fold the result.
3509/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003510static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3511 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003512 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003513 unsigned AS =
3514 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003515
Chris Lattner8574aba2009-11-27 00:29:05 +00003516 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003517 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003518 return Ops[0];
3519
Nico Weber48c82402014-08-27 20:06:19 +00003520 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003521 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003522 Type *GEPTy = PointerType::get(LastType, AS);
3523 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3524 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3525
3526 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003527 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003528
Jay Foadb992a632011-07-19 15:07:52 +00003529 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003530 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003531 if (match(Ops[1], m_Zero()))
3532 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003533
David Blaikie4a2e73b2015-04-02 18:55:32 +00003534 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003535 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003536 Value *P;
3537 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003538 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003539 // getelementptr P, N -> P if P points to a type of zero size.
3540 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003541 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003542
3543 // The following transforms are only safe if the ptrtoint cast
3544 // doesn't truncate the pointers.
3545 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003546 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003547 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3548 if (match(P, m_Zero()))
3549 return Constant::getNullValue(GEPTy);
3550 Value *Temp;
3551 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003552 if (Temp->getType() == GEPTy)
3553 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003554 return nullptr;
3555 };
3556
3557 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3558 if (TyAllocSize == 1 &&
3559 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3560 if (Value *R = PtrToIntOrZero(P))
3561 return R;
3562
3563 // getelementptr V, (ashr (sub P, V), C) -> Q
3564 // if P points to a type of size 1 << C.
3565 if (match(Ops[1],
3566 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3567 m_ConstantInt(C))) &&
3568 TyAllocSize == 1ULL << C)
3569 if (Value *R = PtrToIntOrZero(P))
3570 return R;
3571
3572 // getelementptr V, (sdiv (sub P, V), C) -> Q
3573 // if P points to a type of size C.
3574 if (match(Ops[1],
3575 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3576 m_SpecificInt(TyAllocSize))))
3577 if (Value *R = PtrToIntOrZero(P))
3578 return R;
3579 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003580 }
3581 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003582
Chris Lattner8574aba2009-11-27 00:29:05 +00003583 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003584 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003585 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003586 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003587
David Blaikie4a2e73b2015-04-02 18:55:32 +00003588 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3589 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003590}
3591
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003592Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3593 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003594 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003595 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003596 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003597 return ::SimplifyGEPInst(SrcTy, Ops,
3598 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003599}
3600
Sanjay Patel472cc782016-01-11 22:14:42 +00003601/// Given operands for an InsertValueInst, see if we can fold the result.
3602/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003603static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3604 ArrayRef<unsigned> Idxs, const Query &Q,
3605 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003606 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3607 if (Constant *CVal = dyn_cast<Constant>(Val))
3608 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3609
3610 // insertvalue x, undef, n -> x
3611 if (match(Val, m_Undef()))
3612 return Agg;
3613
3614 // insertvalue x, (extractvalue y, n), n
3615 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003616 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3617 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003618 // insertvalue undef, (extractvalue y, n), n -> y
3619 if (match(Agg, m_Undef()))
3620 return EV->getAggregateOperand();
3621
3622 // insertvalue y, (extractvalue y, n), n -> y
3623 if (Agg == EV->getAggregateOperand())
3624 return Agg;
3625 }
3626
Craig Topper9f008862014-04-15 04:59:12 +00003627 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003628}
3629
Chandler Carruth66b31302015-01-04 12:03:27 +00003630Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003631 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003632 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3633 const Instruction *CxtI) {
3634 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003635 RecursionLimit);
3636}
3637
Sanjay Patel472cc782016-01-11 22:14:42 +00003638/// Given operands for an ExtractValueInst, see if we can fold the result.
3639/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003640static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3641 const Query &, unsigned) {
3642 if (auto *CAgg = dyn_cast<Constant>(Agg))
3643 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3644
3645 // extractvalue x, (insertvalue y, elt, n), n -> elt
3646 unsigned NumIdxs = Idxs.size();
3647 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3648 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3649 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3650 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3651 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3652 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3653 Idxs.slice(0, NumCommonIdxs)) {
3654 if (NumIdxs == NumInsertValueIdxs)
3655 return IVI->getInsertedValueOperand();
3656 break;
3657 }
3658 }
3659
3660 return nullptr;
3661}
3662
3663Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3664 const DataLayout &DL,
3665 const TargetLibraryInfo *TLI,
3666 const DominatorTree *DT,
3667 AssumptionCache *AC,
3668 const Instruction *CxtI) {
3669 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3670 RecursionLimit);
3671}
3672
Sanjay Patel472cc782016-01-11 22:14:42 +00003673/// Given operands for an ExtractElementInst, see if we can fold the result.
3674/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003675static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3676 unsigned) {
3677 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3678 if (auto *CIdx = dyn_cast<Constant>(Idx))
3679 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3680
3681 // The index is not relevant if our vector is a splat.
3682 if (auto *Splat = CVec->getSplatValue())
3683 return Splat;
3684
3685 if (isa<UndefValue>(Vec))
3686 return UndefValue::get(Vec->getType()->getVectorElementType());
3687 }
3688
3689 // If extracting a specified index from the vector, see if we can recursively
3690 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003691 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3692 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003693 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003694
3695 return nullptr;
3696}
3697
3698Value *llvm::SimplifyExtractElementInst(
3699 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3700 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3701 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3702 RecursionLimit);
3703}
3704
Sanjay Patel472cc782016-01-11 22:14:42 +00003705/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003706static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003707 // If all of the PHI's incoming values are the same then replace the PHI node
3708 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003709 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003710 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003711 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003712 // If the incoming value is the phi node itself, it can safely be skipped.
3713 if (Incoming == PN) continue;
3714 if (isa<UndefValue>(Incoming)) {
3715 // Remember that we saw an undef value, but otherwise ignore them.
3716 HasUndefInput = true;
3717 continue;
3718 }
3719 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003720 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003721 CommonValue = Incoming;
3722 }
3723
3724 // If CommonValue is null then all of the incoming values were either undef or
3725 // equal to the phi node itself.
3726 if (!CommonValue)
3727 return UndefValue::get(PN->getType());
3728
3729 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3730 // instruction, we cannot return X as the result of the PHI node unless it
3731 // dominates the PHI block.
3732 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003733 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003734
3735 return CommonValue;
3736}
3737
Duncan Sands395ac42d2012-03-13 14:07:05 +00003738static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3739 if (Constant *C = dyn_cast<Constant>(Op))
Manuel Jacob925d0292016-01-21 06:31:08 +00003740 return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003741
Craig Topper9f008862014-04-15 04:59:12 +00003742 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00003743}
3744
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003745Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00003746 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003747 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003748 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003749 return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003750 RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003751}
3752
Chris Lattnera71e9d62009-11-10 00:55:12 +00003753//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003754
Sanjay Patel472cc782016-01-11 22:14:42 +00003755/// Given operands for a BinaryOperator, see if we can fold the result.
3756/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003757static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003758 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003759 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003760 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003761 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003762 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003763 case Instruction::FAdd:
3764 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3765
Chris Lattner9e4aa022011-02-09 17:15:04 +00003766 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003767 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003768 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003769 case Instruction::FSub:
3770 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3771
Duncan Sandsb8cee002012-03-13 11:42:19 +00003772 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003773 case Instruction::FMul:
3774 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003775 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3776 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003777 case Instruction::FDiv:
3778 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003779 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3780 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003781 case Instruction::FRem:
3782 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003783 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003784 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003785 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003786 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003787 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003788 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003789 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3790 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3791 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3792 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003793 default:
3794 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00003795 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3796 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00003797
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003798 // If the operation is associative, try some generic simplifications.
3799 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003800 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003801 return V;
3802
Duncan Sandsb8cee002012-03-13 11:42:19 +00003803 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003804 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003805 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003806 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003807 return V;
3808
3809 // If the operation is with the result of a phi instruction, check whether
3810 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003811 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003812 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003813 return V;
3814
Craig Topper9f008862014-04-15 04:59:12 +00003815 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003816 }
3817}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003818
Sanjay Patel472cc782016-01-11 22:14:42 +00003819/// Given operands for a BinaryOperator, see if we can fold the result.
3820/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003821/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3822/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3823static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3824 const FastMathFlags &FMF, const Query &Q,
3825 unsigned MaxRecurse) {
3826 switch (Opcode) {
3827 case Instruction::FAdd:
3828 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3829 case Instruction::FSub:
3830 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3831 case Instruction::FMul:
3832 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3833 default:
3834 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3835 }
3836}
3837
Duncan Sands7e800d62010-11-14 11:23:23 +00003838Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003839 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003840 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003841 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003842 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003843 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003844}
3845
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003846Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003847 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003848 const TargetLibraryInfo *TLI,
3849 const DominatorTree *DT, AssumptionCache *AC,
3850 const Instruction *CxtI) {
3851 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3852 RecursionLimit);
3853}
3854
Sanjay Patel472cc782016-01-11 22:14:42 +00003855/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003856static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003857 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003858 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003859 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003860 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003861}
3862
3863Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003864 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003865 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003866 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003867 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003868 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003869}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003870
Michael Ilseman54857292013-02-07 19:26:05 +00003871static bool IsIdempotent(Intrinsic::ID ID) {
3872 switch (ID) {
3873 default: return false;
3874
3875 // Unary idempotent: f(f(x)) = f(x)
3876 case Intrinsic::fabs:
3877 case Intrinsic::floor:
3878 case Intrinsic::ceil:
3879 case Intrinsic::trunc:
3880 case Intrinsic::rint:
3881 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003882 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003883 return true;
3884 }
3885}
3886
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00003887static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3888 const DataLayout &DL) {
3889 GlobalValue *PtrSym;
3890 APInt PtrOffset;
3891 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3892 return nullptr;
3893
3894 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3895 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3896 Type *Int32PtrTy = Int32Ty->getPointerTo();
3897 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3898
3899 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3900 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3901 return nullptr;
3902
3903 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3904 if (OffsetInt % 4 != 0)
3905 return nullptr;
3906
3907 Constant *C = ConstantExpr::getGetElementPtr(
3908 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3909 ConstantInt::get(Int64Ty, OffsetInt / 4));
3910 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3911 if (!Loaded)
3912 return nullptr;
3913
3914 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3915 if (!LoadedCE)
3916 return nullptr;
3917
3918 if (LoadedCE->getOpcode() == Instruction::Trunc) {
3919 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3920 if (!LoadedCE)
3921 return nullptr;
3922 }
3923
3924 if (LoadedCE->getOpcode() != Instruction::Sub)
3925 return nullptr;
3926
3927 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3928 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3929 return nullptr;
3930 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3931
3932 Constant *LoadedRHS = LoadedCE->getOperand(1);
3933 GlobalValue *LoadedRHSSym;
3934 APInt LoadedRHSOffset;
3935 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3936 DL) ||
3937 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3938 return nullptr;
3939
3940 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3941}
3942
Michael Ilseman54857292013-02-07 19:26:05 +00003943template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00003944static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00003945 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00003946 Intrinsic::ID IID = F->getIntrinsicID();
3947 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3948 Type *ReturnType = F->getReturnType();
3949
3950 // Binary Ops
3951 if (NumOperands == 2) {
3952 Value *LHS = *ArgBegin;
3953 Value *RHS = *(ArgBegin + 1);
3954 if (IID == Intrinsic::usub_with_overflow ||
3955 IID == Intrinsic::ssub_with_overflow) {
3956 // X - X -> { 0, false }
3957 if (LHS == RHS)
3958 return Constant::getNullValue(ReturnType);
3959
3960 // X - undef -> undef
3961 // undef - X -> undef
3962 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3963 return UndefValue::get(ReturnType);
3964 }
3965
3966 if (IID == Intrinsic::uadd_with_overflow ||
3967 IID == Intrinsic::sadd_with_overflow) {
3968 // X + undef -> undef
3969 if (isa<UndefValue>(RHS))
3970 return UndefValue::get(ReturnType);
3971 }
3972
3973 if (IID == Intrinsic::umul_with_overflow ||
3974 IID == Intrinsic::smul_with_overflow) {
3975 // X * 0 -> { 0, false }
3976 if (match(RHS, m_Zero()))
3977 return Constant::getNullValue(ReturnType);
3978
3979 // X * undef -> { 0, false }
3980 if (match(RHS, m_Undef()))
3981 return Constant::getNullValue(ReturnType);
3982 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00003983
3984 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
3985 isa<Constant>(RHS))
3986 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
3987 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00003988 }
3989
Michael Ilseman54857292013-02-07 19:26:05 +00003990 // Perform idempotent optimizations
3991 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003992 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003993
3994 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00003995 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00003996 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3997 if (II->getIntrinsicID() == IID)
3998 return II;
3999
Craig Topper9f008862014-04-15 04:59:12 +00004000 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004001}
4002
Chandler Carruth9dc35582012-12-28 11:30:55 +00004003template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004004static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004005 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004006 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004007 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4008 Ty = PTy->getElementType();
4009 FunctionType *FTy = cast<FunctionType>(Ty);
4010
Dan Gohman85977e62011-11-04 18:32:42 +00004011 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00004012 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004013 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004014
Chandler Carruthf6182152012-12-28 14:23:29 +00004015 Function *F = dyn_cast<Function>(V);
4016 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004017 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004018
David Majnemer15032582015-05-22 03:56:46 +00004019 if (F->isIntrinsic())
4020 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004021 return Ret;
4022
Chandler Carruthf6182152012-12-28 14:23:29 +00004023 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004024 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004025
4026 SmallVector<Constant *, 4> ConstantArgs;
4027 ConstantArgs.reserve(ArgEnd - ArgBegin);
4028 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4029 Constant *C = dyn_cast<Constant>(*I);
4030 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004031 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004032 ConstantArgs.push_back(C);
4033 }
4034
4035 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004036}
4037
Chandler Carruthf6182152012-12-28 14:23:29 +00004038Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004039 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004040 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4041 AssumptionCache *AC, const Instruction *CxtI) {
4042 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004043 RecursionLimit);
4044}
4045
Chandler Carruthf6182152012-12-28 14:23:29 +00004046Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004047 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004048 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004049 const Instruction *CxtI) {
4050 return ::SimplifyCall(V, Args.begin(), Args.end(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004051 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004052}
4053
Sanjay Patel472cc782016-01-11 22:14:42 +00004054/// See if we can compute a simplified version of this instruction.
4055/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004056Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004057 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004058 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004059 Value *Result;
4060
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004061 switch (I->getOpcode()) {
4062 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004063 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004064 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004065 case Instruction::FAdd:
4066 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004067 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004068 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004069 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004070 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4071 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004072 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4073 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004074 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004075 case Instruction::FSub:
4076 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004077 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004078 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004079 case Instruction::Sub:
4080 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4081 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004082 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4083 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004084 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004085 case Instruction::FMul:
4086 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004087 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004088 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004089 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004090 Result =
4091 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004092 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004093 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004094 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4095 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004096 break;
4097 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004098 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4099 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004100 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004101 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004102 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4103 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004104 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004105 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004106 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4107 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004108 break;
4109 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004110 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4111 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004112 break;
4113 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004114 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4115 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004116 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004117 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004118 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4119 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004120 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4121 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004122 break;
4123 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004124 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004125 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4126 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004127 break;
4128 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004129 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004130 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4131 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004132 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004133 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004134 Result =
4135 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004136 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004137 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004138 Result =
4139 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004140 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004141 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004142 Result =
4143 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004144 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004145 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004146 Result =
4147 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4148 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004149 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004150 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004151 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4152 I->getOperand(0), I->getOperand(1),
4153 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004154 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004155 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004156 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004157 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004158 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004159 case Instruction::GetElementPtr: {
4160 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004161 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4162 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004163 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004164 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004165 case Instruction::InsertValue: {
4166 InsertValueInst *IV = cast<InsertValueInst>(I);
4167 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4168 IV->getInsertedValueOperand(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004169 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004170 break;
4171 }
David Majnemer25a796e2015-07-13 01:15:46 +00004172 case Instruction::ExtractValue: {
4173 auto *EVI = cast<ExtractValueInst>(I);
4174 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4175 EVI->getIndices(), DL, TLI, DT, AC, I);
4176 break;
4177 }
David Majnemer599ca442015-07-13 01:15:53 +00004178 case Instruction::ExtractElement: {
4179 auto *EEI = cast<ExtractElementInst>(I);
4180 Result = SimplifyExtractElementInst(
4181 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4182 break;
4183 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004184 case Instruction::PHI:
Chandler Carruth66b31302015-01-04 12:03:27 +00004185 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004186 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004187 case Instruction::Call: {
4188 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004189 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4190 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004191 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004192 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00004193 case Instruction::Trunc:
Chandler Carruth66b31302015-01-04 12:03:27 +00004194 Result =
4195 SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004196 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004197 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004198
Hal Finkelf2199b22015-10-23 20:37:08 +00004199 // In general, it is possible for computeKnownBits to determine all bits in a
4200 // value even when the operands are not all constants.
4201 if (!Result && I->getType()->isIntegerTy()) {
4202 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4203 APInt KnownZero(BitWidth, 0);
4204 APInt KnownOne(BitWidth, 0);
4205 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4206 if ((KnownZero | KnownOne).isAllOnesValue())
4207 Result = ConstantInt::get(I->getContext(), KnownOne);
4208 }
4209
Duncan Sands64e41cf2010-11-17 08:35:29 +00004210 /// If called on unreachable code, the above logic may report that the
4211 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004212 /// detecting that case here, returning a safe value instead.
4213 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004214}
4215
Sanjay Patelf44bd382016-01-20 18:59:48 +00004216/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004217/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004218///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004219/// This is the common implementation of the recursive simplification routines.
4220/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4221/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4222/// instructions to process and attempt to simplify it using
4223/// InstructionSimplify.
4224///
4225/// This routine returns 'true' only when *it* simplifies something. The passed
4226/// in simplified value does not count toward this.
4227static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004228 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004229 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004230 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004231 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004232 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004233 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004234
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004235 // If we have an explicit value to collapse to, do that round of the
4236 // simplification loop by hand initially.
4237 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004238 for (User *U : I->users())
4239 if (U != I)
4240 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004241
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004242 // Replace the instruction with its simplified value.
4243 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004244
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004245 // Gracefully handle edge cases where the instruction is not wired into any
4246 // parent block.
4247 if (I->getParent())
4248 I->eraseFromParent();
4249 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004250 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004251 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004252
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004253 // Note that we must test the size on each iteration, the worklist can grow.
4254 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4255 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004256
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004257 // See if this instruction simplifies.
Chandler Carruth66b31302015-01-04 12:03:27 +00004258 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004259 if (!SimpleV)
4260 continue;
4261
4262 Simplified = true;
4263
4264 // Stash away all the uses of the old instruction so we can check them for
4265 // recursive simplifications after a RAUW. This is cheaper than checking all
4266 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004267 for (User *U : I->users())
4268 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004269
4270 // Replace the instruction with its simplified value.
4271 I->replaceAllUsesWith(SimpleV);
4272
4273 // Gracefully handle edge cases where the instruction is not wired into any
4274 // parent block.
4275 if (I->getParent())
4276 I->eraseFromParent();
4277 }
4278 return Simplified;
4279}
4280
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004281bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004282 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004283 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004284 AssumptionCache *AC) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004285 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004286}
4287
4288bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004289 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004290 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004291 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004292 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4293 assert(SimpleV && "Must provide a simplified value.");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004294 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004295}