blob: cd795fdb7812d0373afa2932c5c0d2a1360b0158 [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"
Chris Lattner084a1b52009-11-09 22:57:59 +000023#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000036
Chandler Carruthf1221bd2014-04-22 02:48:03 +000037#define DEBUG_TYPE "instsimplify"
38
Chris Lattner9e4aa022011-02-09 17:15:04 +000039enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000040
Duncan Sands3547d2e2010-12-22 09:40:51 +000041STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000042STATISTIC(NumReassoc, "Number of reassociations");
43
Duncan Sandsb8cee002012-03-13 11:42:19 +000044struct Query {
Rafael Espindola37dc9e12014-02-21 00:06:31 +000045 const DataLayout *DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000046 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +000048 AssumptionTracker *AT;
49 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000050
Rafael Espindola37dc9e12014-02-21 00:06:31 +000051 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
Hal Finkel60db0582014-09-07 18:57:58 +000052 const DominatorTree *dt, AssumptionTracker *at = nullptr,
53 const Instruction *cxti = nullptr)
54 : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000055};
56
57static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
58static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000059 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000060static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000061 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000062static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
63static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000064static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000065
Duncan Sandsc1c92712011-07-26 15:03:53 +000066/// getFalse - For a boolean type, or a vector of boolean type, return false, or
67/// a vector with every element false, as appropriate for the type.
68static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000069 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000070 "Expected i1 type or a vector of i1!");
71 return Constant::getNullValue(Ty);
72}
73
74/// getTrue - For a boolean type, or a vector of boolean type, return true, or
75/// a vector with every element true, as appropriate for the type.
76static Constant *getTrue(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::getAllOnesValue(Ty);
80}
81
Duncan Sands3d5692a2011-10-30 19:56:36 +000082/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
83static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
84 Value *RHS) {
85 CmpInst *Cmp = dyn_cast<CmpInst>(V);
86 if (!Cmp)
87 return false;
88 CmpInst::Predicate CPred = Cmp->getPredicate();
89 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
90 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
91 return true;
92 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
93 CRHS == LHS;
94}
95
Duncan Sands5ffc2982010-11-16 12:16:38 +000096/// ValueDominatesPHI - Does the given value dominate the specified phi node?
97static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
98 Instruction *I = dyn_cast<Instruction>(V);
99 if (!I)
100 // Arguments and constants dominate all instructions.
101 return true;
102
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000103 // If we are processing instructions (and/or basic blocks) that have not been
104 // fully added to a function, the parent nodes may still be null. Simply
105 // return the conservative answer in these cases.
106 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
107 return false;
108
Duncan Sands5ffc2982010-11-16 12:16:38 +0000109 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000110 if (DT) {
111 if (!DT->isReachableFromEntry(P->getParent()))
112 return true;
113 if (!DT->isReachableFromEntry(I->getParent()))
114 return false;
115 return DT->dominates(I, P);
116 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000117
118 // Otherwise, if the instruction is in the entry block, and is not an invoke,
119 // then it obviously dominates all phi nodes.
120 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
121 !isa<InvokeInst>(I))
122 return true;
123
124 return false;
125}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000126
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000127/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
128/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
129/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
130/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
131/// Returns the simplified value, or null if no simplification was performed.
132static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000133 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000134 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000135 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000136 // Recursion is always used, so bail out at once if we already hit the limit.
137 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000138 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000139
140 // Check whether the expression has the form "(A op' B) op C".
141 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
142 if (Op0->getOpcode() == OpcodeToExpand) {
143 // It does! Try turning it into "(A op C) op' (B op C)".
144 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
145 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000146 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
147 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148 // They do! Return "L op' R" if it simplifies or is already available.
149 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000150 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
151 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000152 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000153 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000154 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000155 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000156 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000157 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000158 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000159 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000160 }
161 }
162
163 // Check whether the expression has the form "A op (B op' C)".
164 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
165 if (Op1->getOpcode() == OpcodeToExpand) {
166 // It does! Try turning it into "(A op B) op' (A op C)".
167 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
168 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000169 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
170 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000171 // They do! Return "L op' R" if it simplifies or is already available.
172 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000173 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
174 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000175 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000176 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000177 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000178 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000179 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000180 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000181 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000182 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 }
184 }
185
Craig Topper9f008862014-04-15 04:59:12 +0000186 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000187}
188
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
190/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000191static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000192 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000193 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000194 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
195
196 // Recursion is always used, so bail out at once if we already hit the limit.
197 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000198 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000199
200 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
201 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
202
203 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
204 if (Op0 && Op0->getOpcode() == Opcode) {
205 Value *A = Op0->getOperand(0);
206 Value *B = Op0->getOperand(1);
207 Value *C = RHS;
208
209 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000210 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000211 // It does! Return "A op V" if it simplifies or is already available.
212 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000213 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000214 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000215 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000216 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000217 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000218 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000219 }
220 }
221
222 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
223 if (Op1 && Op1->getOpcode() == Opcode) {
224 Value *A = LHS;
225 Value *B = Op1->getOperand(0);
226 Value *C = Op1->getOperand(1);
227
228 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000229 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000230 // It does! Return "V op C" if it simplifies or is already available.
231 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000232 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000233 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000234 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000235 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000236 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000237 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000238 }
239 }
240
241 // The remaining transforms require commutativity as well as associativity.
242 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000243 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000244
245 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
246 if (Op0 && Op0->getOpcode() == Opcode) {
247 Value *A = Op0->getOperand(0);
248 Value *B = Op0->getOperand(1);
249 Value *C = RHS;
250
251 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000252 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000253 // It does! Return "V op B" if it simplifies or is already available.
254 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000255 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000256 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000257 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000258 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000259 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000260 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000261 }
262 }
263
264 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
265 if (Op1 && Op1->getOpcode() == Opcode) {
266 Value *A = LHS;
267 Value *B = Op1->getOperand(0);
268 Value *C = Op1->getOperand(1);
269
270 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000271 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000272 // It does! Return "B op V" if it simplifies or is already available.
273 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000274 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000275 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000276 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000277 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000278 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000279 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280 }
281 }
282
Craig Topper9f008862014-04-15 04:59:12 +0000283 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000284}
285
Duncan Sandsb0579e92010-11-10 13:00:08 +0000286/// ThreadBinOpOverSelect - In the case of a binary operation with a select
287/// instruction as an operand, try to simplify the binop by seeing whether
288/// evaluating it on both branches of the select results in the same value.
289/// Returns the common value if so, otherwise returns null.
290static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000291 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000292 // Recursion is always used, so bail out at once if we already hit the limit.
293 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000294 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000295
Duncan Sandsb0579e92010-11-10 13:00:08 +0000296 SelectInst *SI;
297 if (isa<SelectInst>(LHS)) {
298 SI = cast<SelectInst>(LHS);
299 } else {
300 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
301 SI = cast<SelectInst>(RHS);
302 }
303
304 // Evaluate the BinOp on the true and false branches of the select.
305 Value *TV;
306 Value *FV;
307 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000308 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
309 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000310 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000311 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
312 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000313 }
314
Duncan Sandse3c53952011-01-01 16:12:09 +0000315 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000316 // If they both failed to simplify then return null.
317 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000318 return TV;
319
320 // If one branch simplified to undef, return the other one.
321 if (TV && isa<UndefValue>(TV))
322 return FV;
323 if (FV && isa<UndefValue>(FV))
324 return TV;
325
326 // If applying the operation did not change the true and false select values,
327 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000328 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000329 return SI;
330
331 // If one branch simplified and the other did not, and the simplified
332 // value is equal to the unsimplified one, return the simplified value.
333 // For example, select (cond, X, X & Z) & Z -> X & Z.
334 if ((FV && !TV) || (TV && !FV)) {
335 // Check that the simplified value has the form "X op Y" where "op" is the
336 // same as the original operation.
337 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
338 if (Simplified && Simplified->getOpcode() == Opcode) {
339 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
340 // We already know that "op" is the same as for the simplified value. See
341 // if the operands match too. If so, return the simplified value.
342 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
343 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
344 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000345 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
346 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000347 return Simplified;
348 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000349 Simplified->getOperand(1) == UnsimplifiedLHS &&
350 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000351 return Simplified;
352 }
353 }
354
Craig Topper9f008862014-04-15 04:59:12 +0000355 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000356}
357
358/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
359/// try to simplify the comparison by seeing whether both branches of the select
360/// result in the same value. Returns the common value if so, otherwise returns
361/// null.
362static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000363 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000364 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000365 // Recursion is always used, so bail out at once if we already hit the limit.
366 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000367 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000368
Duncan Sandsb0579e92010-11-10 13:00:08 +0000369 // Make sure the select is on the LHS.
370 if (!isa<SelectInst>(LHS)) {
371 std::swap(LHS, RHS);
372 Pred = CmpInst::getSwappedPredicate(Pred);
373 }
374 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
375 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000376 Value *Cond = SI->getCondition();
377 Value *TV = SI->getTrueValue();
378 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000379
Duncan Sands06504022011-02-03 09:37:39 +0000380 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000381 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000382 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000383 if (TCmp == Cond) {
384 // It not only simplified, it simplified to the select condition. Replace
385 // it with 'true'.
386 TCmp = getTrue(Cond->getType());
387 } else if (!TCmp) {
388 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
389 // condition then we can replace it with 'true'. Otherwise give up.
390 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000391 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000392 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000393 }
394
Duncan Sands3d5692a2011-10-30 19:56:36 +0000395 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000396 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000397 if (FCmp == Cond) {
398 // It not only simplified, it simplified to the select condition. Replace
399 // it with 'false'.
400 FCmp = getFalse(Cond->getType());
401 } else if (!FCmp) {
402 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
403 // condition then we can replace it with 'false'. Otherwise give up.
404 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000405 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000406 FCmp = getFalse(Cond->getType());
407 }
408
409 // If both sides simplified to the same value, then use it as the result of
410 // the original comparison.
411 if (TCmp == FCmp)
412 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000413
414 // The remaining cases only make sense if the select condition has the same
415 // type as the result of the comparison, so bail out if this is not so.
416 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000417 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000418 // If the false value simplified to false, then the result of the compare
419 // is equal to "Cond && TCmp". This also catches the case when the false
420 // value simplified to false and the true value to true, returning "Cond".
421 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000422 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000423 return V;
424 // If the true value simplified to true, then the result of the compare
425 // is equal to "Cond || FCmp".
426 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000427 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 return V;
429 // Finally, if the false value simplified to true and the true value to
430 // false, then the result of the compare is equal to "!Cond".
431 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
432 if (Value *V =
433 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000434 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000435 return V;
436
Craig Topper9f008862014-04-15 04:59:12 +0000437 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000438}
439
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000440/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
441/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
442/// it on the incoming phi values yields the same result for every value. If so
443/// returns the common value, otherwise returns null.
444static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000445 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000446 // Recursion is always used, so bail out at once if we already hit the limit.
447 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000448 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000449
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000450 PHINode *PI;
451 if (isa<PHINode>(LHS)) {
452 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000453 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000454 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000456 } else {
457 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
458 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000459 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000460 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000461 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000462 }
463
464 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000465 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000467 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000468 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000469 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000471 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
472 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000473 // If the operation failed to simplify, or simplified to a different value
474 // to previously, then give up.
475 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000476 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000477 CommonValue = V;
478 }
479
480 return CommonValue;
481}
482
483/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
484/// try to simplify the comparison by seeing whether comparing with all of the
485/// incoming phi values yields the same result every time. If so returns the
486/// common result, otherwise returns null.
487static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000488 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000489 // Recursion is always used, so bail out at once if we already hit the limit.
490 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000491 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000492
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000493 // Make sure the phi is on the LHS.
494 if (!isa<PHINode>(LHS)) {
495 std::swap(LHS, RHS);
496 Pred = CmpInst::getSwappedPredicate(Pred);
497 }
498 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
499 PHINode *PI = cast<PHINode>(LHS);
500
Duncan Sands5ffc2982010-11-16 12:16:38 +0000501 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000502 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000503 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000504
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000505 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000506 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000507 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000508 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000509 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000510 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000511 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 // If the operation failed to simplify, or simplified to a different value
513 // to previously, then give up.
514 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000515 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000516 CommonValue = V;
517 }
518
519 return CommonValue;
520}
521
Chris Lattner3d9823b2009-11-27 17:42:22 +0000522/// SimplifyAddInst - Given operands for an Add, see if we can
523/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000524static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000525 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000526 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
527 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
528 Constant *Ops[] = { CLHS, CRHS };
Duncan Sandsb8cee002012-03-13 11:42:19 +0000529 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000530 Q.DL, Q.TLI);
Chris Lattner3d9823b2009-11-27 17:42:22 +0000531 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000532
Chris Lattner3d9823b2009-11-27 17:42:22 +0000533 // Canonicalize the constant to the RHS.
534 std::swap(Op0, Op1);
535 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000536
Duncan Sands0a2c41682010-12-15 14:07:39 +0000537 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000538 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000540
Duncan Sands0a2c41682010-12-15 14:07:39 +0000541 // X + 0 -> X
542 if (match(Op1, m_Zero()))
543 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000544
Duncan Sands0a2c41682010-12-15 14:07:39 +0000545 // X + (Y - X) -> Y
546 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000547 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000548 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000549 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
550 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000551 return Y;
552
553 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000554 if (match(Op0, m_Not(m_Specific(Op1))) ||
555 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000556 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000557
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000558 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000559 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000560 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000561 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000562
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000563 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000564 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000565 MaxRecurse))
566 return V;
567
Duncan Sandsb238de02010-11-19 09:20:39 +0000568 // Threading Add over selects and phi nodes is pointless, so don't bother.
569 // Threading over the select in "A + select(cond, B, C)" means evaluating
570 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
571 // only if B and C are equal. If B and C are equal then (since we assume
572 // that operands have already been simplified) "select(cond, B, C)" should
573 // have been simplified to the common value of B and C already. Analysing
574 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
575 // for threading over phi nodes.
576
Craig Topper9f008862014-04-15 04:59:12 +0000577 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000578}
579
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000580Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000581 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000582 const DominatorTree *DT, AssumptionTracker *AT,
583 const Instruction *CxtI) {
584 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
585 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000586}
587
Chandler Carrutha0796552012-03-12 11:19:31 +0000588/// \brief Compute the base pointer and cumulative constant offsets for V.
589///
590/// This strips all constant offsets off of V, leaving it the base pointer, and
591/// accumulates the total constant offset applied in the returned constant. It
592/// returns 0 if V is not a pointer, and returns the constant '0' if there are
593/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000594///
595/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
596/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
597/// folding.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000598static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000599 Value *&V,
600 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000601 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000602
Dan Gohman18c77a12013-01-31 02:50:36 +0000603 // Without DataLayout, just be conservative for now. Theoretically, more could
604 // be done in this case.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000605 if (!DL)
Dan Gohman18c77a12013-01-31 02:50:36 +0000606 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
607
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000608 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000609 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000610
611 // Even though we don't look through PHI nodes, we could be called on an
612 // instruction in an unreachable block, which may be on a cycle.
613 SmallPtrSet<Value *, 4> Visited;
614 Visited.insert(V);
615 do {
616 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000617 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000618 !GEP->accumulateConstantOffset(*DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000620 V = GEP->getPointerOperand();
621 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000622 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000623 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
624 if (GA->mayBeOverridden())
625 break;
626 V = GA->getAliasee();
627 } else {
628 break;
629 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000630 assert(V->getType()->getScalarType()->isPointerTy() &&
631 "Unexpected operand type!");
Chandler Carrutha0796552012-03-12 11:19:31 +0000632 } while (Visited.insert(V));
633
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000634 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
635 if (V->getType()->isVectorTy())
636 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
637 OffsetIntPtr);
638 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000639}
640
641/// \brief Compute the constant difference between two pointer values.
642/// If the difference is not a constant, returns zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000643static Constant *computePointerDifference(const DataLayout *DL,
Chandler Carrutha0796552012-03-12 11:19:31 +0000644 Value *LHS, Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000645 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
646 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000647
648 // If LHS and RHS are not related via constant offsets to the same base
649 // value, there is nothing we can do here.
650 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000651 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000652
653 // Otherwise, the difference of LHS - RHS can be computed as:
654 // LHS - RHS
655 // = (LHSOffset + Base) - (RHSOffset + Base)
656 // = LHSOffset - RHSOffset
657 return ConstantExpr::getSub(LHSOffset, RHSOffset);
658}
659
Duncan Sands0a2c41682010-12-15 14:07:39 +0000660/// SimplifySubInst - Given operands for a Sub, see if we can
661/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000662static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000663 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000664 if (Constant *CLHS = dyn_cast<Constant>(Op0))
665 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
666 Constant *Ops[] = { CLHS, CRHS };
667 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000668 Ops, Q.DL, Q.TLI);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000669 }
670
671 // X - undef -> undef
672 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000673 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000674 return UndefValue::get(Op0->getType());
675
676 // X - 0 -> X
677 if (match(Op1, m_Zero()))
678 return Op0;
679
680 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000681 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000682 return Constant::getNullValue(Op0->getType());
683
David Majnemercd4fbcd2014-07-31 04:49:18 +0000684 // X - (0 - Y) -> X if the second sub is NUW.
685 // If Y != 0, 0 - Y is a poison value.
686 // If Y == 0, 0 - Y simplifies to 0.
687 if (BinaryOperator::isNeg(Op1)) {
688 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
689 assert(BO->getOpcode() == Instruction::Sub &&
690 "Expected a subtraction operator!");
691 if (BO->hasNoUnsignedWrap())
692 return Op0;
693 }
694 }
695
Duncan Sands99589d02011-01-18 11:50:19 +0000696 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
697 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000698 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000699 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
700 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000701 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000702 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000703 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000704 // It does, we successfully reassociated!
705 ++NumReassoc;
706 return W;
707 }
708 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000709 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000710 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000711 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000712 // It does, we successfully reassociated!
713 ++NumReassoc;
714 return W;
715 }
716 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000717
Duncan Sands99589d02011-01-18 11:50:19 +0000718 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
719 // For example, X - (X + 1) -> -1
720 X = Op0;
721 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
722 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000723 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000724 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000725 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000726 // It does, we successfully reassociated!
727 ++NumReassoc;
728 return W;
729 }
730 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000731 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000732 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does, we successfully reassociated!
735 ++NumReassoc;
736 return W;
737 }
738 }
739
740 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
741 // For example, X - (X - Y) -> Y.
742 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000743 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
744 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000745 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000746 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000747 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000748 // It does, we successfully reassociated!
749 ++NumReassoc;
750 return W;
751 }
752
Duncan Sands395ac42d2012-03-13 14:07:05 +0000753 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
754 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
755 match(Op1, m_Trunc(m_Value(Y))))
756 if (X->getType() == Y->getType())
757 // See if "V === X - Y" simplifies.
758 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
759 // It does! Now see if "trunc V" simplifies.
760 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
761 // It does, return the simplified "trunc V".
762 return W;
763
764 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000765 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000766 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000767 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000768 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
769
Duncan Sands99589d02011-01-18 11:50:19 +0000770 // i1 sub -> xor.
771 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000772 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000773 return V;
774
Duncan Sands0a2c41682010-12-15 14:07:39 +0000775 // Threading Sub over selects and phi nodes is pointless, so don't bother.
776 // Threading over the select in "A - select(cond, B, C)" means evaluating
777 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
778 // only if B and C are equal. If B and C are equal then (since we assume
779 // that operands have already been simplified) "select(cond, B, C)" should
780 // have been simplified to the common value of B and C already. Analysing
781 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
782 // for threading over phi nodes.
783
Craig Topper9f008862014-04-15 04:59:12 +0000784 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000785}
786
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000787Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000788 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000789 const DominatorTree *DT, AssumptionTracker *AT,
790 const Instruction *CxtI) {
791 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
792 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000793}
794
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000795/// Given operands for an FAdd, see if we can fold the result. If not, this
796/// returns null.
797static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
798 const Query &Q, unsigned MaxRecurse) {
799 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
800 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
801 Constant *Ops[] = { CLHS, CRHS };
802 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000803 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000804 }
805
806 // Canonicalize the constant to the RHS.
807 std::swap(Op0, Op1);
808 }
809
810 // fadd X, -0 ==> X
811 if (match(Op1, m_NegZero()))
812 return Op0;
813
814 // fadd X, 0 ==> X, when we know X is not -0
815 if (match(Op1, m_Zero()) &&
816 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
817 return Op0;
818
819 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
820 // where nnan and ninf have to occur at least once somewhere in this
821 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000822 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000823 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
824 SubOp = Op1;
825 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
826 SubOp = Op0;
827 if (SubOp) {
828 Instruction *FSub = cast<Instruction>(SubOp);
829 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
830 (FMF.noInfs() || FSub->hasNoInfs()))
831 return Constant::getNullValue(Op0->getType());
832 }
833
Craig Topper9f008862014-04-15 04:59:12 +0000834 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000835}
836
837/// Given operands for an FSub, see if we can fold the result. If not, this
838/// returns null.
839static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
840 const Query &Q, unsigned MaxRecurse) {
841 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
842 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
843 Constant *Ops[] = { CLHS, CRHS };
844 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000845 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000846 }
847 }
848
849 // fsub X, 0 ==> X
850 if (match(Op1, m_Zero()))
851 return Op0;
852
853 // fsub X, -0 ==> X, when we know X is not -0
854 if (match(Op1, m_NegZero()) &&
855 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
856 return Op0;
857
858 // fsub 0, (fsub -0.0, X) ==> X
859 Value *X;
860 if (match(Op0, m_AnyZero())) {
861 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
862 return X;
863 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
864 return X;
865 }
866
867 // fsub nnan ninf x, x ==> 0.0
868 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
869 return Constant::getNullValue(Op0->getType());
870
Craig Topper9f008862014-04-15 04:59:12 +0000871 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872}
873
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000874/// Given the operands for an FMul, see if we can fold the result
875static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
876 FastMathFlags FMF,
877 const Query &Q,
878 unsigned MaxRecurse) {
879 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
880 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
881 Constant *Ops[] = { CLHS, CRHS };
882 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000883 Ops, Q.DL, Q.TLI);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000884 }
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000885
886 // Canonicalize the constant to the RHS.
887 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000888 }
889
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000890 // fmul X, 1.0 ==> X
891 if (match(Op1, m_FPOne()))
892 return Op0;
893
894 // fmul nnan nsz X, 0 ==> 0
895 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
896 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000897
Craig Topper9f008862014-04-15 04:59:12 +0000898 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000899}
900
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000901/// SimplifyMulInst - Given operands for a Mul, see if we can
902/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000903static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
904 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000905 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
906 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
907 Constant *Ops[] = { CLHS, CRHS };
908 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000909 Ops, Q.DL, Q.TLI);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000910 }
911
912 // Canonicalize the constant to the RHS.
913 std::swap(Op0, Op1);
914 }
915
916 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000917 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000918 return Constant::getNullValue(Op0->getType());
919
920 // X * 0 -> 0
921 if (match(Op1, m_Zero()))
922 return Op1;
923
924 // X * 1 -> X
925 if (match(Op1, m_One()))
926 return Op0;
927
Duncan Sandsb67edc62011-01-30 18:03:50 +0000928 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000929 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000930 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
931 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
932 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000933
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000934 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000935 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000936 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000937 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938
939 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000940 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
944 // Mul distributes over Add. Try some generic simplifications based on this.
945 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000946 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000947 return V;
948
949 // If the operation is with the result of a select instruction, check whether
950 // operating on either branch of the select always yields the same value.
951 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000952 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000953 MaxRecurse))
954 return V;
955
956 // If the operation is with the result of a phi instruction, check whether
957 // operating on all incoming values of the phi always yields the same value.
958 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000959 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000960 MaxRecurse))
961 return V;
962
Craig Topper9f008862014-04-15 04:59:12 +0000963 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000964}
965
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000966Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000967 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000968 const DominatorTree *DT, AssumptionTracker *AT,
969 const Instruction *CxtI) {
970 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
971 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000972}
973
974Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000975 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000976 const DominatorTree *DT, AssumptionTracker *AT,
977 const Instruction *CxtI) {
978 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
979 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000980}
981
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000982Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
983 FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000984 const DataLayout *DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000985 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000986 const DominatorTree *DT,
987 AssumptionTracker *AT,
988 const Instruction *CxtI) {
989 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
990 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000991}
992
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000993Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000994 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000995 const DominatorTree *DT, AssumptionTracker *AT,
996 const Instruction *CxtI) {
997 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
998 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000999}
1000
Duncan Sands771e82a2011-01-28 16:51:11 +00001001/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1002/// fold the result. If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001003static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001004 const Query &Q, unsigned MaxRecurse) {
Duncan Sands771e82a2011-01-28 16:51:11 +00001005 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1006 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1007 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001008 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands771e82a2011-01-28 16:51:11 +00001009 }
1010 }
1011
Duncan Sands65995fa2011-01-28 18:50:50 +00001012 bool isSigned = Opcode == Instruction::SDiv;
1013
Duncan Sands771e82a2011-01-28 16:51:11 +00001014 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001015 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001016 return Op1;
1017
1018 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001019 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001020 return Constant::getNullValue(Op0->getType());
1021
1022 // 0 / X -> 0, we don't need to preserve faults!
1023 if (match(Op0, m_Zero()))
1024 return Op0;
1025
1026 // X / 1 -> X
1027 if (match(Op1, m_One()))
1028 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001029
1030 if (Op0->getType()->isIntegerTy(1))
1031 // It can't be division by zero, hence it must be division by one.
1032 return Op0;
1033
1034 // X / X -> 1
1035 if (Op0 == Op1)
1036 return ConstantInt::get(Op0->getType(), 1);
1037
1038 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001039 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001040 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1041 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001042 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001043 // If the Mul knows it does not overflow, then we are good to go.
1044 if ((isSigned && Mul->hasNoSignedWrap()) ||
1045 (!isSigned && Mul->hasNoUnsignedWrap()))
1046 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001047 // If X has the form X = A / Y then X * Y cannot overflow.
1048 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1049 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1050 return X;
1051 }
1052
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 // (X rem Y) / Y -> 0
1054 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1055 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1056 return Constant::getNullValue(Op0->getType());
1057
1058 // If the operation is with the result of a select instruction, check whether
1059 // operating on either branch of the select always yields the same value.
1060 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001061 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001062 return V;
1063
1064 // If the operation is with the result of a phi instruction, check whether
1065 // operating on all incoming values of the phi always yields the same value.
1066 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001067 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001068 return V;
1069
Craig Topper9f008862014-04-15 04:59:12 +00001070 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001071}
1072
1073/// SimplifySDivInst - Given operands for an SDiv, see if we can
1074/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001075static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1076 unsigned MaxRecurse) {
1077 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001078 return V;
1079
Craig Topper9f008862014-04-15 04:59:12 +00001080 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001081}
1082
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001083Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001084 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001085 const DominatorTree *DT,
1086 AssumptionTracker *AT,
1087 const Instruction *CxtI) {
1088 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1089 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001090}
1091
1092/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1093/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001094static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1095 unsigned MaxRecurse) {
1096 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001097 return V;
1098
Craig Topper9f008862014-04-15 04:59:12 +00001099 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001100}
1101
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001102Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001103 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001104 const DominatorTree *DT,
1105 AssumptionTracker *AT,
1106 const Instruction *CxtI) {
1107 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1108 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001109}
1110
Duncan Sandsb8cee002012-03-13 11:42:19 +00001111static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1112 unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001113 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001114 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001115 return Op0;
1116
1117 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001118 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001119 return Op1;
1120
Craig Topper9f008862014-04-15 04:59:12 +00001121 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001122}
1123
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001124Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001125 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001126 const DominatorTree *DT,
1127 AssumptionTracker *AT,
1128 const Instruction *CxtI) {
1129 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1130 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001131}
1132
Duncan Sandsa3e36992011-05-02 16:27:02 +00001133/// SimplifyRem - Given operands for an SRem or URem, see if we can
1134/// fold the result. If not, this returns null.
1135static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001136 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001137 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1138 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1139 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001140 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001141 }
1142 }
1143
Duncan Sandsa3e36992011-05-02 16:27:02 +00001144 // X % undef -> undef
1145 if (match(Op1, m_Undef()))
1146 return Op1;
1147
1148 // undef % X -> 0
1149 if (match(Op0, m_Undef()))
1150 return Constant::getNullValue(Op0->getType());
1151
1152 // 0 % X -> 0, we don't need to preserve faults!
1153 if (match(Op0, m_Zero()))
1154 return Op0;
1155
1156 // X % 0 -> undef, we don't need to preserve faults!
1157 if (match(Op1, m_Zero()))
1158 return UndefValue::get(Op0->getType());
1159
1160 // X % 1 -> 0
1161 if (match(Op1, m_One()))
1162 return Constant::getNullValue(Op0->getType());
1163
1164 if (Op0->getType()->isIntegerTy(1))
1165 // It can't be remainder by zero, hence it must be remainder by one.
1166 return Constant::getNullValue(Op0->getType());
1167
1168 // X % X -> 0
1169 if (Op0 == Op1)
1170 return Constant::getNullValue(Op0->getType());
1171
1172 // If the operation is with the result of a select instruction, check whether
1173 // operating on either branch of the select always yields the same value.
1174 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001175 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001176 return V;
1177
1178 // If the operation is with the result of a phi instruction, check whether
1179 // operating on all incoming values of the phi always yields the same value.
1180 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001181 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001182 return V;
1183
Craig Topper9f008862014-04-15 04:59:12 +00001184 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001185}
1186
1187/// SimplifySRemInst - Given operands for an SRem, see if we can
1188/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001189static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1190 unsigned MaxRecurse) {
1191 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001192 return V;
1193
Craig Topper9f008862014-04-15 04:59:12 +00001194 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001195}
1196
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001197Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001198 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001199 const DominatorTree *DT,
1200 AssumptionTracker *AT,
1201 const Instruction *CxtI) {
1202 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1203 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001204}
1205
1206/// SimplifyURemInst - Given operands for a URem, see if we can
1207/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001208static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001209 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001210 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001211 return V;
1212
Craig Topper9f008862014-04-15 04:59:12 +00001213 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001214}
1215
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001216Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001217 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001218 const DominatorTree *DT,
1219 AssumptionTracker *AT,
1220 const Instruction *CxtI) {
1221 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1222 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001223}
1224
Duncan Sandsb8cee002012-03-13 11:42:19 +00001225static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001226 unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001227 // undef % X -> undef (the undef could be a snan).
1228 if (match(Op0, m_Undef()))
1229 return Op0;
1230
1231 // X % undef -> undef
1232 if (match(Op1, m_Undef()))
1233 return Op1;
1234
Craig Topper9f008862014-04-15 04:59:12 +00001235 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001236}
1237
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001238Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001239 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001240 const DominatorTree *DT,
1241 AssumptionTracker *AT,
1242 const Instruction *CxtI) {
1243 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1244 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001245}
1246
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001247/// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1248static bool isUndefShift(Value *Amount) {
1249 Constant *C = dyn_cast<Constant>(Amount);
1250 if (!C)
1251 return false;
1252
1253 // X shift by undef -> undef because it may shift by the bitwidth.
1254 if (isa<UndefValue>(C))
1255 return true;
1256
1257 // Shifting by the bitwidth or more is undefined.
1258 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1259 if (CI->getValue().getLimitedValue() >=
1260 CI->getType()->getScalarSizeInBits())
1261 return true;
1262
1263 // If all lanes of a vector shift are undefined the whole shift is.
1264 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1265 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1266 if (!isUndefShift(C->getAggregateElement(I)))
1267 return false;
1268 return true;
1269 }
1270
1271 return false;
1272}
1273
Duncan Sands571fd9a2011-01-14 14:44:12 +00001274/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sands7f60dc12011-01-14 00:37:45 +00001275/// fold the result. If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001276static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001277 const Query &Q, unsigned MaxRecurse) {
Duncan Sands7f60dc12011-01-14 00:37:45 +00001278 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1279 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1280 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001281 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001282 }
1283 }
1284
Duncan Sands571fd9a2011-01-14 14:44:12 +00001285 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001286 if (match(Op0, m_Zero()))
1287 return Op0;
1288
Duncan Sands571fd9a2011-01-14 14:44:12 +00001289 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001290 if (match(Op1, m_Zero()))
1291 return Op0;
1292
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001293 // Fold undefined shifts.
1294 if (isUndefShift(Op1))
1295 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001296
Duncan Sands571fd9a2011-01-14 14:44:12 +00001297 // If the operation is with the result of a select instruction, check whether
1298 // operating on either branch of the select always yields the same value.
1299 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001300 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001301 return V;
1302
1303 // If the operation is with the result of a phi instruction, check whether
1304 // operating on all incoming values of the phi always yields the same value.
1305 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001306 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001307 return V;
1308
Craig Topper9f008862014-04-15 04:59:12 +00001309 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001310}
1311
1312/// SimplifyShlInst - Given operands for an Shl, see if we can
1313/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001314static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001315 const Query &Q, unsigned MaxRecurse) {
1316 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001317 return V;
1318
1319 // undef << X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001320 if (match(Op0, m_Undef()))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001321 return Constant::getNullValue(Op0->getType());
1322
Chris Lattner9e4aa022011-02-09 17:15:04 +00001323 // (X >> A) << A -> X
1324 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001325 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001326 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001327 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001328}
1329
Chris Lattner9e4aa022011-02-09 17:15:04 +00001330Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001331 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001332 const DominatorTree *DT, AssumptionTracker *AT,
1333 const Instruction *CxtI) {
1334 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001335 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001336}
1337
1338/// SimplifyLShrInst - Given operands for an LShr, see if we can
1339/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001340static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001341 const Query &Q, unsigned MaxRecurse) {
1342 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001343 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001344
David Majnemera80fed72013-07-09 22:01:22 +00001345 // X >> X -> 0
1346 if (Op0 == Op1)
1347 return Constant::getNullValue(Op0->getType());
1348
Duncan Sands7f60dc12011-01-14 00:37:45 +00001349 // undef >>l X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001350 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001351 return Constant::getNullValue(Op0->getType());
1352
Chris Lattner9e4aa022011-02-09 17:15:04 +00001353 // (X << A) >> A -> X
1354 Value *X;
1355 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1356 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1357 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001358
Craig Topper9f008862014-04-15 04:59:12 +00001359 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001360}
1361
Chris Lattner9e4aa022011-02-09 17:15:04 +00001362Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001363 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001364 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001365 const DominatorTree *DT,
1366 AssumptionTracker *AT,
1367 const Instruction *CxtI) {
1368 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001369 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001370}
1371
1372/// SimplifyAShrInst - Given operands for an AShr, see if we can
1373/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001374static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001375 const Query &Q, unsigned MaxRecurse) {
1376 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001377 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001378
David Majnemera80fed72013-07-09 22:01:22 +00001379 // X >> X -> 0
1380 if (Op0 == Op1)
1381 return Constant::getNullValue(Op0->getType());
1382
Duncan Sands7f60dc12011-01-14 00:37:45 +00001383 // all ones >>a X -> all ones
1384 if (match(Op0, m_AllOnes()))
1385 return Op0;
1386
1387 // undef >>a X -> all ones
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001388 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001389 return Constant::getAllOnesValue(Op0->getType());
1390
Chris Lattner9e4aa022011-02-09 17:15:04 +00001391 // (X << A) >> A -> X
1392 Value *X;
1393 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1394 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1395 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001396
Suyog Sarda68862412014-07-17 06:28:15 +00001397 // Arithmetic shifting an all-sign-bit value is a no-op.
Hal Finkel60db0582014-09-07 18:57:58 +00001398 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001399 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1400 return Op0;
1401
Craig Topper9f008862014-04-15 04:59:12 +00001402 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001403}
1404
Chris Lattner9e4aa022011-02-09 17:15:04 +00001405Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001406 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001407 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001408 const DominatorTree *DT,
1409 AssumptionTracker *AT,
1410 const Instruction *CxtI) {
1411 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001412 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001413}
1414
Chris Lattnera71e9d62009-11-10 00:55:12 +00001415/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner084a1b52009-11-09 22:57:59 +00001416/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001417static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001418 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001419 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1420 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1421 Constant *Ops[] = { CLHS, CRHS };
1422 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001423 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001424 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001425
Chris Lattnera71e9d62009-11-10 00:55:12 +00001426 // Canonicalize the constant to the RHS.
1427 std::swap(Op0, Op1);
1428 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001429
Chris Lattnera71e9d62009-11-10 00:55:12 +00001430 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001431 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001432 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001433
Chris Lattnera71e9d62009-11-10 00:55:12 +00001434 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001435 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001436 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001437
Duncan Sandsc89ac072010-11-17 18:52:15 +00001438 // X & 0 = 0
1439 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001440 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001441
Duncan Sandsc89ac072010-11-17 18:52:15 +00001442 // X & -1 = X
1443 if (match(Op1, m_AllOnes()))
1444 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001445
Chris Lattnera71e9d62009-11-10 00:55:12 +00001446 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001447 if (match(Op0, m_Not(m_Specific(Op1))) ||
1448 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001449 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001450
Chris Lattnera71e9d62009-11-10 00:55:12 +00001451 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001452 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001453 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001454 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001455 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001456
Chris Lattnera71e9d62009-11-10 00:55:12 +00001457 // A & (A | ?) = A
1458 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001459 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001460 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001461
Duncan Sandsba286d72011-10-26 20:55:21 +00001462 // A & (-A) = A if A is a power of two or zero.
1463 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1464 match(Op1, m_Neg(m_Specific(Op0)))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001465 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001466 return Op0;
Hal Finkel60db0582014-09-07 18:57:58 +00001467 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001468 return Op1;
1469 }
1470
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001471 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001472 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1473 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001474 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001475
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001476 // And distributes over Or. Try some generic simplifications based on this.
1477 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001478 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001479 return V;
1480
1481 // And distributes over Xor. Try some generic simplifications based on this.
1482 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001483 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001484 return V;
1485
Duncan Sandsb0579e92010-11-10 13:00:08 +00001486 // If the operation is with the result of a select instruction, check whether
1487 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001488 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001489 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1490 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001491 return V;
1492
1493 // If the operation is with the result of a phi instruction, check whether
1494 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001495 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001496 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001497 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001498 return V;
1499
Craig Topper9f008862014-04-15 04:59:12 +00001500 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001501}
1502
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001503Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001504 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001505 const DominatorTree *DT, AssumptionTracker *AT,
1506 const Instruction *CxtI) {
1507 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1508 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001509}
1510
Chris Lattnera71e9d62009-11-10 00:55:12 +00001511/// SimplifyOrInst - Given operands for an Or, see if we can
1512/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001513static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1514 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001515 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1516 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1517 Constant *Ops[] = { CLHS, CRHS };
1518 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001519 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001520 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001521
Chris Lattnera71e9d62009-11-10 00:55:12 +00001522 // Canonicalize the constant to the RHS.
1523 std::swap(Op0, Op1);
1524 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001525
Chris Lattnera71e9d62009-11-10 00:55:12 +00001526 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001527 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001528 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001529
Chris Lattnera71e9d62009-11-10 00:55:12 +00001530 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001531 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001532 return Op0;
1533
Duncan Sandsc89ac072010-11-17 18:52:15 +00001534 // X | 0 = X
1535 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001536 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001537
Duncan Sandsc89ac072010-11-17 18:52:15 +00001538 // X | -1 = -1
1539 if (match(Op1, m_AllOnes()))
1540 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001541
Chris Lattnera71e9d62009-11-10 00:55:12 +00001542 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001543 if (match(Op0, m_Not(m_Specific(Op1))) ||
1544 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001545 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001546
Chris Lattnera71e9d62009-11-10 00:55:12 +00001547 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001548 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001549 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001550 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001551 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001552
Chris Lattnera71e9d62009-11-10 00:55:12 +00001553 // A | (A & ?) = A
1554 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001555 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001556 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001557
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001558 // ~(A & ?) | A = -1
1559 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1560 (A == Op1 || B == Op1))
1561 return Constant::getAllOnesValue(Op1->getType());
1562
1563 // A | ~(A & ?) = -1
1564 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1565 (A == Op0 || B == Op0))
1566 return Constant::getAllOnesValue(Op0->getType());
1567
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001568 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001569 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1570 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001571 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001572
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001573 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001574 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1575 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001576 return V;
1577
Duncan Sandsb0579e92010-11-10 13:00:08 +00001578 // If the operation is with the result of a select instruction, check whether
1579 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001580 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001581 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001582 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001583 return V;
1584
Nick Lewycky8561a492014-06-19 03:51:46 +00001585 // (A & C)|(B & D)
1586 Value *C = nullptr, *D = nullptr;
1587 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1588 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1589 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1590 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1591 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1592 // (A & C1)|(B & C2)
1593 // If we have: ((V + N) & C1) | (V & C2)
1594 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1595 // replace with V+N.
1596 Value *V1, *V2;
1597 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1598 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1599 // Add commutes, try both ways.
Hal Finkel60db0582014-09-07 18:57:58 +00001600 if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
1601 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001602 return A;
Hal Finkel60db0582014-09-07 18:57:58 +00001603 if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
1604 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001605 return A;
1606 }
1607 // Or commutes, try both ways.
1608 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1609 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1610 // Add commutes, try both ways.
Hal Finkel60db0582014-09-07 18:57:58 +00001611 if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
1612 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001613 return B;
Hal Finkel60db0582014-09-07 18:57:58 +00001614 if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
1615 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001616 return B;
1617 }
1618 }
1619 }
1620
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001621 // If the operation is with the result of a phi instruction, check whether
1622 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001623 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001624 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001625 return V;
1626
Craig Topper9f008862014-04-15 04:59:12 +00001627 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001628}
1629
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001630Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001631 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001632 const DominatorTree *DT, AssumptionTracker *AT,
1633 const Instruction *CxtI) {
1634 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1635 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001636}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001637
Duncan Sandsc89ac072010-11-17 18:52:15 +00001638/// SimplifyXorInst - Given operands for a Xor, see if we can
1639/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001640static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1641 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001642 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1643 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1644 Constant *Ops[] = { CLHS, CRHS };
1645 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001646 Ops, Q.DL, Q.TLI);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001647 }
1648
1649 // Canonicalize the constant to the RHS.
1650 std::swap(Op0, Op1);
1651 }
1652
1653 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001654 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001655 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001656
1657 // A ^ 0 = A
1658 if (match(Op1, m_Zero()))
1659 return Op0;
1660
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001661 // A ^ A = 0
1662 if (Op0 == Op1)
1663 return Constant::getNullValue(Op0->getType());
1664
Duncan Sandsc89ac072010-11-17 18:52:15 +00001665 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001666 if (match(Op0, m_Not(m_Specific(Op1))) ||
1667 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001668 return Constant::getAllOnesValue(Op0->getType());
1669
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001670 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001671 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1672 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001673 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001674
Duncan Sandsb238de02010-11-19 09:20:39 +00001675 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1676 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1677 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1678 // only if B and C are equal. If B and C are equal then (since we assume
1679 // that operands have already been simplified) "select(cond, B, C)" should
1680 // have been simplified to the common value of B and C already. Analysing
1681 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1682 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001683
Craig Topper9f008862014-04-15 04:59:12 +00001684 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001685}
1686
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001687Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001688 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001689 const DominatorTree *DT, AssumptionTracker *AT,
1690 const Instruction *CxtI) {
1691 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1692 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001693}
1694
Chris Lattner229907c2011-07-18 04:54:35 +00001695static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001696 return CmpInst::makeCmpResultType(Op->getType());
1697}
1698
Duncan Sandsaf327282011-05-07 16:56:49 +00001699/// ExtractEquivalentCondition - Rummage around inside V looking for something
1700/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1701/// otherwise return null. Helper function for analyzing max/min idioms.
1702static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1703 Value *LHS, Value *RHS) {
1704 SelectInst *SI = dyn_cast<SelectInst>(V);
1705 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001706 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001707 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1708 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001709 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001710 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1711 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1712 return Cmp;
1713 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1714 LHS == CmpRHS && RHS == CmpLHS)
1715 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001716 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001717}
1718
Dan Gohman9631d902013-02-01 00:49:06 +00001719// A significant optimization not implemented here is assuming that alloca
1720// addresses are not equal to incoming argument values. They don't *alias*,
1721// as we say, but that doesn't mean they aren't equal, so we take a
1722// conservative approach.
1723//
1724// This is inspired in part by C++11 5.10p1:
1725// "Two pointers of the same type compare equal if and only if they are both
1726// null, both point to the same function, or both represent the same
1727// address."
1728//
1729// This is pretty permissive.
1730//
1731// It's also partly due to C11 6.5.9p6:
1732// "Two pointers compare equal if and only if both are null pointers, both are
1733// pointers to the same object (including a pointer to an object and a
1734// subobject at its beginning) or function, both are pointers to one past the
1735// last element of the same array object, or one is a pointer to one past the
1736// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001737// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001738// object in the address space.)
1739//
1740// C11's version is more restrictive, however there's no reason why an argument
1741// couldn't be a one-past-the-end value for a stack object in the caller and be
1742// equal to the beginning of a stack object in the callee.
1743//
1744// If the C and C++ standards are ever made sufficiently restrictive in this
1745// area, it may be possible to update LLVM's semantics accordingly and reinstate
1746// this optimization.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001747static Constant *computePointerICmp(const DataLayout *DL,
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001748 const TargetLibraryInfo *TLI,
Chandler Carruth8059c842012-03-25 21:28:14 +00001749 CmpInst::Predicate Pred,
1750 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001751 // First, skip past any trivial no-ops.
1752 LHS = LHS->stripPointerCasts();
1753 RHS = RHS->stripPointerCasts();
1754
1755 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001756 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001757 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1758 return ConstantInt::get(GetCompareTy(LHS),
1759 !CmpInst::isTrueWhenEqual(Pred));
1760
Chandler Carruth8059c842012-03-25 21:28:14 +00001761 // We can only fold certain predicates on pointer comparisons.
1762 switch (Pred) {
1763 default:
Craig Topper9f008862014-04-15 04:59:12 +00001764 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001765
1766 // Equality comaprisons are easy to fold.
1767 case CmpInst::ICMP_EQ:
1768 case CmpInst::ICMP_NE:
1769 break;
1770
1771 // We can only handle unsigned relational comparisons because 'inbounds' on
1772 // a GEP only protects against unsigned wrapping.
1773 case CmpInst::ICMP_UGT:
1774 case CmpInst::ICMP_UGE:
1775 case CmpInst::ICMP_ULT:
1776 case CmpInst::ICMP_ULE:
1777 // However, we have to switch them to their signed variants to handle
1778 // negative indices from the base pointer.
1779 Pred = ICmpInst::getSignedPredicate(Pred);
1780 break;
1781 }
1782
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001783 // Strip off any constant offsets so that we can reason about them.
1784 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1785 // here and compare base addresses like AliasAnalysis does, however there are
1786 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1787 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1788 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1790 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001791
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001792 // If LHS and RHS are related via constant offsets to the same base
1793 // value, we can replace it with an icmp which just compares the offsets.
1794 if (LHS == RHS)
1795 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001796
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001797 // Various optimizations for (in)equality comparisons.
1798 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1799 // Different non-empty allocations that exist at the same time have
1800 // different addresses (if the program can tell). Global variables always
1801 // exist, so they always exist during the lifetime of each other and all
1802 // allocas. Two different allocas usually have different addresses...
1803 //
1804 // However, if there's an @llvm.stackrestore dynamically in between two
1805 // allocas, they may have the same address. It's tempting to reduce the
1806 // scope of the problem by only looking at *static* allocas here. That would
1807 // cover the majority of allocas while significantly reducing the likelihood
1808 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1809 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1810 // an entry block. Also, if we have a block that's not attached to a
1811 // function, we can't tell if it's "static" under the current definition.
1812 // Theoretically, this problem could be fixed by creating a new kind of
1813 // instruction kind specifically for static allocas. Such a new instruction
1814 // could be required to be at the top of the entry block, thus preventing it
1815 // from being subject to a @llvm.stackrestore. Instcombine could even
1816 // convert regular allocas into these special allocas. It'd be nifty.
1817 // However, until then, this problem remains open.
1818 //
1819 // So, we'll assume that two non-empty allocas have different addresses
1820 // for now.
1821 //
1822 // With all that, if the offsets are within the bounds of their allocations
1823 // (and not one-past-the-end! so we can't use inbounds!), and their
1824 // allocations aren't the same, the pointers are not equal.
1825 //
1826 // Note that it's not necessary to check for LHS being a global variable
1827 // address, due to canonicalization and constant folding.
1828 if (isa<AllocaInst>(LHS) &&
1829 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001830 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1831 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001832 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001833 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001834 getObjectSize(LHS, LHSSize, DL, TLI) &&
1835 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001836 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1837 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001838 if (!LHSOffsetValue.isNegative() &&
1839 !RHSOffsetValue.isNegative() &&
1840 LHSOffsetValue.ult(LHSSize) &&
1841 RHSOffsetValue.ult(RHSSize)) {
1842 return ConstantInt::get(GetCompareTy(LHS),
1843 !CmpInst::isTrueWhenEqual(Pred));
1844 }
1845 }
1846
1847 // Repeat the above check but this time without depending on DataLayout
1848 // or being able to compute a precise size.
1849 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1850 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1851 LHSOffset->isNullValue() &&
1852 RHSOffset->isNullValue())
1853 return ConstantInt::get(GetCompareTy(LHS),
1854 !CmpInst::isTrueWhenEqual(Pred));
1855 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001856
1857 // Even if an non-inbounds GEP occurs along the path we can still optimize
1858 // equality comparisons concerning the result. We avoid walking the whole
1859 // chain again by starting where the last calls to
1860 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001861 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1862 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001863 if (LHS == RHS)
1864 return ConstantExpr::getICmp(Pred,
1865 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1866 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001867 }
1868
1869 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00001870 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001871}
Chris Lattner01990f02012-02-24 19:01:58 +00001872
Chris Lattnerc1f19072009-11-09 23:28:39 +00001873/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1874/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001875static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001876 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00001877 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00001878 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00001879
Chris Lattnera71e9d62009-11-10 00:55:12 +00001880 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001881 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001882 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001883
1884 // If we have a constant, make sure it is on the RHS.
1885 std::swap(LHS, RHS);
1886 Pred = CmpInst::getSwappedPredicate(Pred);
1887 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001888
Chris Lattner229907c2011-07-18 04:54:35 +00001889 Type *ITy = GetCompareTy(LHS); // The return type.
1890 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00001891
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001892 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00001893 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1894 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00001895 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001896 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00001897
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001898 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00001899 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001900 switch (Pred) {
1901 default: break;
1902 case ICmpInst::ICMP_EQ:
1903 // X == 1 -> X
1904 if (match(RHS, m_One()))
1905 return LHS;
1906 break;
1907 case ICmpInst::ICMP_NE:
1908 // X != 0 -> X
1909 if (match(RHS, m_Zero()))
1910 return LHS;
1911 break;
1912 case ICmpInst::ICMP_UGT:
1913 // X >u 0 -> X
1914 if (match(RHS, m_Zero()))
1915 return LHS;
1916 break;
1917 case ICmpInst::ICMP_UGE:
1918 // X >=u 1 -> X
1919 if (match(RHS, m_One()))
1920 return LHS;
1921 break;
1922 case ICmpInst::ICMP_SLT:
1923 // X <s 0 -> X
1924 if (match(RHS, m_Zero()))
1925 return LHS;
1926 break;
1927 case ICmpInst::ICMP_SLE:
1928 // X <=s -1 -> X
1929 if (match(RHS, m_One()))
1930 return LHS;
1931 break;
1932 }
1933 }
1934
Duncan Sandsd3951082011-01-25 09:38:29 +00001935 // If we are comparing with zero then try hard since this is a common case.
1936 if (match(RHS, m_Zero())) {
1937 bool LHSKnownNonNegative, LHSKnownNegative;
1938 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00001939 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00001940 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001941 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001942 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001943 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001944 case ICmpInst::ICMP_EQ:
1945 case ICmpInst::ICMP_ULE:
Hal Finkel60db0582014-09-07 18:57:58 +00001946 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001947 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001948 break;
1949 case ICmpInst::ICMP_NE:
1950 case ICmpInst::ICMP_UGT:
Hal Finkel60db0582014-09-07 18:57:58 +00001951 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001952 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001953 break;
1954 case ICmpInst::ICMP_SLT:
Hal Finkel60db0582014-09-07 18:57:58 +00001955 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1956 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00001957 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001958 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001959 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001960 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001961 break;
1962 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00001963 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1964 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00001965 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001966 return getTrue(ITy);
Hal Finkel60db0582014-09-07 18:57:58 +00001967 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
1968 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001969 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001970 break;
1971 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00001972 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1973 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00001974 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001975 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001976 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001977 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001978 break;
1979 case ICmpInst::ICMP_SGT:
Hal Finkel60db0582014-09-07 18:57:58 +00001980 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1981 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00001982 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001983 return getFalse(ITy);
Hal Finkel60db0582014-09-07 18:57:58 +00001984 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
1985 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001986 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001987 break;
1988 }
1989 }
1990
1991 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001992 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001993 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1994 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1995 if (RHS_CR.isEmptySet())
1996 return ConstantInt::getFalse(CI->getContext());
1997 if (RHS_CR.isFullSet())
1998 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00001999
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002000 // Many binary operators with constant RHS have easy to compute constant
2001 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002002 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002003 APInt Lower = APInt(Width, 0);
2004 APInt Upper = APInt(Width, 0);
2005 ConstantInt *CI2;
2006 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2007 // 'urem x, CI2' produces [0, CI2).
2008 Upper = CI2->getValue();
2009 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2010 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2011 Upper = CI2->getValue().abs();
2012 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002013 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2014 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002015 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002016 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2017 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2018 APInt NegOne = APInt::getAllOnesValue(Width);
2019 if (!CI2->isZero())
2020 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002021 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00002022 if (CI2->isMinSignedValue()) {
2023 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2024 Lower = CI2->getValue();
2025 Upper = Lower.lshr(1) + 1;
2026 } else {
2027 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2028 Upper = CI2->getValue().abs() + 1;
2029 Lower = (-Upper) + 1;
2030 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002031 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002032 APInt IntMin = APInt::getSignedMinValue(Width);
2033 APInt IntMax = APInt::getSignedMaxValue(Width);
David Majnemeraf9180f2014-07-14 20:38:45 +00002034 APInt Val = CI2->getValue();
2035 if (Val.isAllOnesValue()) {
2036 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2037 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2038 Lower = IntMin + 1;
2039 Upper = IntMax + 1;
2040 } else if (Val.countLeadingZeros() < Width - 1) {
2041 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2042 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002043 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00002044 Upper = IntMax.sdiv(Val);
2045 if (Lower.sgt(Upper))
2046 std::swap(Lower, Upper);
2047 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00002048 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002049 }
David Majnemerd6d16712014-08-27 18:03:46 +00002050 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2051 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2052 Lower = CI2->getValue();
2053 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2054 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2055 if (CI2->isNegative()) {
2056 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2057 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2058 Lower = CI2->getValue().shl(ShiftAmount);
2059 Upper = CI2->getValue() + 1;
2060 } else {
2061 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2062 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2063 Lower = CI2->getValue();
2064 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2065 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002066 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2067 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2068 APInt NegOne = APInt::getAllOnesValue(Width);
2069 if (CI2->getValue().ult(Width))
2070 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002071 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2072 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2073 unsigned ShiftAmount = Width - 1;
2074 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2075 ShiftAmount = CI2->getValue().countTrailingZeros();
2076 Lower = CI2->getValue().lshr(ShiftAmount);
2077 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002078 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2079 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2080 APInt IntMin = APInt::getSignedMinValue(Width);
2081 APInt IntMax = APInt::getSignedMaxValue(Width);
2082 if (CI2->getValue().ult(Width)) {
2083 Lower = IntMin.ashr(CI2->getValue());
2084 Upper = IntMax.ashr(CI2->getValue()) + 1;
2085 }
David Majnemer78910fc2014-05-16 17:14:03 +00002086 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2087 unsigned ShiftAmount = Width - 1;
2088 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2089 ShiftAmount = CI2->getValue().countTrailingZeros();
2090 if (CI2->isNegative()) {
2091 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2092 Lower = CI2->getValue();
2093 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2094 } else {
2095 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2096 Lower = CI2->getValue().ashr(ShiftAmount);
2097 Upper = CI2->getValue() + 1;
2098 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002099 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2100 // 'or x, CI2' produces [CI2, UINT_MAX].
2101 Lower = CI2->getValue();
2102 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2103 // 'and x, CI2' produces [0, CI2].
2104 Upper = CI2->getValue() + 1;
2105 }
2106 if (Lower != Upper) {
2107 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2108 if (RHS_CR.contains(LHS_CR))
2109 return ConstantInt::getTrue(RHS->getContext());
2110 if (RHS_CR.inverse().contains(LHS_CR))
2111 return ConstantInt::getFalse(RHS->getContext());
2112 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002113 }
2114
Duncan Sands8fb2c382011-01-20 13:21:55 +00002115 // Compare of cast, for example (zext X) != 0 -> X != 0
2116 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2117 Instruction *LI = cast<CastInst>(LHS);
2118 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002119 Type *SrcTy = SrcOp->getType();
2120 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002121
2122 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2123 // if the integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002124 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2125 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002126 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2127 // Transfer the cast to the constant.
2128 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2129 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002130 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002131 return V;
2132 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2133 if (RI->getOperand(0)->getType() == SrcTy)
2134 // Compare without the cast.
2135 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002136 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002137 return V;
2138 }
2139 }
2140
2141 if (isa<ZExtInst>(LHS)) {
2142 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2143 // same type.
2144 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2145 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2146 // Compare X and Y. Note that signed predicates become unsigned.
2147 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002148 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002149 MaxRecurse-1))
2150 return V;
2151 }
2152 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2153 // too. If not, then try to deduce the result of the comparison.
2154 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2155 // Compute the constant that would happen if we truncated to SrcTy then
2156 // reextended to DstTy.
2157 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2158 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2159
2160 // If the re-extended constant didn't change then this is effectively
2161 // also a case of comparing two zero-extended values.
2162 if (RExt == CI && MaxRecurse)
2163 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002164 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002165 return V;
2166
2167 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2168 // there. Use this to work out the result of the comparison.
2169 if (RExt != CI) {
2170 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002171 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002172 // LHS <u RHS.
2173 case ICmpInst::ICMP_EQ:
2174 case ICmpInst::ICMP_UGT:
2175 case ICmpInst::ICMP_UGE:
2176 return ConstantInt::getFalse(CI->getContext());
2177
2178 case ICmpInst::ICMP_NE:
2179 case ICmpInst::ICMP_ULT:
2180 case ICmpInst::ICMP_ULE:
2181 return ConstantInt::getTrue(CI->getContext());
2182
2183 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2184 // is non-negative then LHS <s RHS.
2185 case ICmpInst::ICMP_SGT:
2186 case ICmpInst::ICMP_SGE:
2187 return CI->getValue().isNegative() ?
2188 ConstantInt::getTrue(CI->getContext()) :
2189 ConstantInt::getFalse(CI->getContext());
2190
2191 case ICmpInst::ICMP_SLT:
2192 case ICmpInst::ICMP_SLE:
2193 return CI->getValue().isNegative() ?
2194 ConstantInt::getFalse(CI->getContext()) :
2195 ConstantInt::getTrue(CI->getContext());
2196 }
2197 }
2198 }
2199 }
2200
2201 if (isa<SExtInst>(LHS)) {
2202 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2203 // same type.
2204 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2205 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2206 // Compare X and Y. Note that the predicate does not change.
2207 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002208 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002209 return V;
2210 }
2211 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2212 // too. If not, then try to deduce the result of the comparison.
2213 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2214 // Compute the constant that would happen if we truncated to SrcTy then
2215 // reextended to DstTy.
2216 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2217 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2218
2219 // If the re-extended constant didn't change then this is effectively
2220 // also a case of comparing two sign-extended values.
2221 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002222 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002223 return V;
2224
2225 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2226 // bits there. Use this to work out the result of the comparison.
2227 if (RExt != CI) {
2228 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002229 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002230 case ICmpInst::ICMP_EQ:
2231 return ConstantInt::getFalse(CI->getContext());
2232 case ICmpInst::ICMP_NE:
2233 return ConstantInt::getTrue(CI->getContext());
2234
2235 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2236 // LHS >s RHS.
2237 case ICmpInst::ICMP_SGT:
2238 case ICmpInst::ICMP_SGE:
2239 return CI->getValue().isNegative() ?
2240 ConstantInt::getTrue(CI->getContext()) :
2241 ConstantInt::getFalse(CI->getContext());
2242 case ICmpInst::ICMP_SLT:
2243 case ICmpInst::ICMP_SLE:
2244 return CI->getValue().isNegative() ?
2245 ConstantInt::getFalse(CI->getContext()) :
2246 ConstantInt::getTrue(CI->getContext());
2247
2248 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2249 // LHS >u RHS.
2250 case ICmpInst::ICMP_UGT:
2251 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002252 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002253 if (MaxRecurse)
2254 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2255 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002256 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002257 return V;
2258 break;
2259 case ICmpInst::ICMP_ULT:
2260 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002261 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002262 if (MaxRecurse)
2263 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2264 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002265 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002266 return V;
2267 break;
2268 }
2269 }
2270 }
2271 }
2272 }
2273
Nick Lewyckyc9610302014-06-19 03:35:49 +00002274 // If a bit is known to be zero for A and known to be one for B,
2275 // then A and B cannot be equal.
2276 if (ICmpInst::isEquality(Pred)) {
2277 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2278 uint32_t BitWidth = CI->getBitWidth();
2279 APInt LHSKnownZero(BitWidth, 0);
2280 APInt LHSKnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00002281 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
2282 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewyckyc9610302014-06-19 03:35:49 +00002283 APInt RHSKnownZero(BitWidth, 0);
2284 APInt RHSKnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00002285 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
2286 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewyckyc9610302014-06-19 03:35:49 +00002287 if (((LHSKnownOne & RHSKnownZero) != 0) ||
2288 ((LHSKnownZero & RHSKnownOne) != 0))
2289 return (Pred == ICmpInst::ICMP_EQ)
2290 ? ConstantInt::getFalse(CI->getContext())
2291 : ConstantInt::getTrue(CI->getContext());
2292 }
2293 }
2294
Duncan Sandsd114ab32011-02-13 17:15:40 +00002295 // Special logic for binary operators.
2296 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2297 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2298 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002299 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002300 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002301 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2302 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2303 if (LBO && LBO->getOpcode() == Instruction::Add) {
2304 A = LBO->getOperand(0); B = LBO->getOperand(1);
2305 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2306 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2307 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2308 }
2309 if (RBO && RBO->getOpcode() == Instruction::Add) {
2310 C = RBO->getOperand(0); D = RBO->getOperand(1);
2311 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2312 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2313 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2314 }
2315
2316 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2317 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2318 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2319 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002320 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002321 return V;
2322
2323 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2324 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2325 if (Value *V = SimplifyICmpInst(Pred,
2326 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002327 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002328 return V;
2329
2330 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2331 if (A && C && (A == C || A == D || B == C || B == D) &&
2332 NoLHSWrapProblem && NoRHSWrapProblem) {
2333 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002334 Value *Y, *Z;
2335 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002336 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002337 Y = B;
2338 Z = D;
2339 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002340 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002341 Y = B;
2342 Z = C;
2343 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002344 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002345 Y = A;
2346 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002347 } else {
2348 assert(B == D);
2349 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002350 Y = A;
2351 Z = C;
2352 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002353 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002354 return V;
2355 }
2356 }
2357
David Majnemer2d6c0232014-05-14 20:16:28 +00002358 // 0 - (zext X) pred C
2359 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2360 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2361 if (RHSC->getValue().isStrictlyPositive()) {
2362 if (Pred == ICmpInst::ICMP_SLT)
2363 return ConstantInt::getTrue(RHSC->getContext());
2364 if (Pred == ICmpInst::ICMP_SGE)
2365 return ConstantInt::getFalse(RHSC->getContext());
2366 if (Pred == ICmpInst::ICMP_EQ)
2367 return ConstantInt::getFalse(RHSC->getContext());
2368 if (Pred == ICmpInst::ICMP_NE)
2369 return ConstantInt::getTrue(RHSC->getContext());
2370 }
2371 if (RHSC->getValue().isNonNegative()) {
2372 if (Pred == ICmpInst::ICMP_SLE)
2373 return ConstantInt::getTrue(RHSC->getContext());
2374 if (Pred == ICmpInst::ICMP_SGT)
2375 return ConstantInt::getFalse(RHSC->getContext());
2376 }
2377 }
2378 }
2379
Nick Lewycky35aeea92013-07-12 23:42:57 +00002380 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002381 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002382 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002383 switch (Pred) {
2384 default:
2385 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002386 case ICmpInst::ICMP_SGT:
2387 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00002388 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2389 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002390 if (!KnownNonNegative)
2391 break;
2392 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002393 case ICmpInst::ICMP_EQ:
2394 case ICmpInst::ICMP_UGT:
2395 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002396 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002397 case ICmpInst::ICMP_SLT:
2398 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00002399 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2400 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002401 if (!KnownNonNegative)
2402 break;
2403 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002404 case ICmpInst::ICMP_NE:
2405 case ICmpInst::ICMP_ULT:
2406 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002407 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002408 }
2409 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002410
2411 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002412 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2413 bool KnownNonNegative, KnownNegative;
2414 switch (Pred) {
2415 default:
2416 break;
2417 case ICmpInst::ICMP_SGT:
2418 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00002419 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2420 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002421 if (!KnownNonNegative)
2422 break;
2423 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002424 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002425 case ICmpInst::ICMP_UGT:
2426 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002427 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002428 case ICmpInst::ICMP_SLT:
2429 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00002430 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2431 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002432 if (!KnownNonNegative)
2433 break;
2434 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002435 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002436 case ICmpInst::ICMP_ULT:
2437 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002438 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002439 }
2440 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002441
Duncan Sands92af0a82011-10-28 18:17:44 +00002442 // x udiv y <=u x.
2443 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2444 // icmp pred (X /u Y), X
2445 if (Pred == ICmpInst::ICMP_UGT)
2446 return getFalse(ITy);
2447 if (Pred == ICmpInst::ICMP_ULE)
2448 return getTrue(ITy);
2449 }
2450
David Majnemer76d06bc2014-08-28 03:34:28 +00002451 // handle:
2452 // CI2 << X == CI
2453 // CI2 << X != CI
2454 //
2455 // where CI2 is a power of 2 and CI isn't
2456 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2457 const APInt *CI2Val, *CIVal = &CI->getValue();
2458 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2459 CI2Val->isPowerOf2()) {
2460 if (!CIVal->isPowerOf2()) {
2461 // CI2 << X can equal zero in some circumstances,
2462 // this simplification is unsafe if CI is zero.
2463 //
2464 // We know it is safe if:
2465 // - The shift is nsw, we can't shift out the one bit.
2466 // - The shift is nuw, we can't shift out the one bit.
2467 // - CI2 is one
2468 // - CI isn't zero
2469 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2470 *CI2Val == 1 || !CI->isZero()) {
2471 if (Pred == ICmpInst::ICMP_EQ)
2472 return ConstantInt::getFalse(RHS->getContext());
2473 if (Pred == ICmpInst::ICMP_NE)
2474 return ConstantInt::getTrue(RHS->getContext());
2475 }
2476 }
2477 if (CIVal->isSignBit() && *CI2Val == 1) {
2478 if (Pred == ICmpInst::ICMP_UGT)
2479 return ConstantInt::getFalse(RHS->getContext());
2480 if (Pred == ICmpInst::ICMP_ULE)
2481 return ConstantInt::getTrue(RHS->getContext());
2482 }
2483 }
2484 }
2485
Nick Lewycky9719a712011-03-05 05:19:11 +00002486 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2487 LBO->getOperand(1) == RBO->getOperand(1)) {
2488 switch (LBO->getOpcode()) {
2489 default: break;
2490 case Instruction::UDiv:
2491 case Instruction::LShr:
2492 if (ICmpInst::isSigned(Pred))
2493 break;
2494 // fall-through
2495 case Instruction::SDiv:
2496 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002497 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002498 break;
2499 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002500 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002501 return V;
2502 break;
2503 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002504 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002505 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2506 if (!NUW && !NSW)
2507 break;
2508 if (!NSW && ICmpInst::isSigned(Pred))
2509 break;
2510 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002511 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002512 return V;
2513 break;
2514 }
2515 }
2516 }
2517
Duncan Sands0a9c1242011-05-03 19:53:10 +00002518 // Simplify comparisons involving max/min.
2519 Value *A, *B;
2520 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002521 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002522
Duncan Sandsa2287852011-05-04 16:05:05 +00002523 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002524 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2525 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002526 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002527 // We analyze this as smax(A, B) pred A.
2528 P = Pred;
2529 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2530 (A == LHS || B == LHS)) {
2531 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002532 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002533 // We analyze this as smax(A, B) swapped-pred A.
2534 P = CmpInst::getSwappedPredicate(Pred);
2535 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2536 (A == RHS || B == RHS)) {
2537 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002538 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002539 // We analyze this as smax(-A, -B) swapped-pred -A.
2540 // Note that we do not need to actually form -A or -B thanks to EqP.
2541 P = CmpInst::getSwappedPredicate(Pred);
2542 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2543 (A == LHS || B == LHS)) {
2544 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002545 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002546 // We analyze this as smax(-A, -B) pred -A.
2547 // Note that we do not need to actually form -A or -B thanks to EqP.
2548 P = Pred;
2549 }
2550 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2551 // Cases correspond to "max(A, B) p A".
2552 switch (P) {
2553 default:
2554 break;
2555 case CmpInst::ICMP_EQ:
2556 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002557 // Equivalent to "A EqP B". This may be the same as the condition tested
2558 // in the max/min; if so, we can just return that.
2559 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2560 return V;
2561 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2562 return V;
2563 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002564 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002565 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002566 return V;
2567 break;
2568 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002569 case CmpInst::ICMP_SGT: {
2570 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2571 // Equivalent to "A InvEqP B". This may be the same as the condition
2572 // tested in the max/min; if so, we can just return that.
2573 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2574 return V;
2575 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2576 return V;
2577 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002578 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002579 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002580 return V;
2581 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002582 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002583 case CmpInst::ICMP_SGE:
2584 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002585 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002586 case CmpInst::ICMP_SLT:
2587 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002588 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002589 }
2590 }
2591
Duncan Sandsa2287852011-05-04 16:05:05 +00002592 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002593 P = CmpInst::BAD_ICMP_PREDICATE;
2594 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2595 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002596 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002597 // We analyze this as umax(A, B) pred A.
2598 P = Pred;
2599 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2600 (A == LHS || B == LHS)) {
2601 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002602 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002603 // We analyze this as umax(A, B) swapped-pred A.
2604 P = CmpInst::getSwappedPredicate(Pred);
2605 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2606 (A == RHS || B == RHS)) {
2607 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002608 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002609 // We analyze this as umax(-A, -B) swapped-pred -A.
2610 // Note that we do not need to actually form -A or -B thanks to EqP.
2611 P = CmpInst::getSwappedPredicate(Pred);
2612 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2613 (A == LHS || B == LHS)) {
2614 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002615 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002616 // We analyze this as umax(-A, -B) pred -A.
2617 // Note that we do not need to actually form -A or -B thanks to EqP.
2618 P = Pred;
2619 }
2620 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2621 // Cases correspond to "max(A, B) p A".
2622 switch (P) {
2623 default:
2624 break;
2625 case CmpInst::ICMP_EQ:
2626 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002627 // Equivalent to "A EqP B". This may be the same as the condition tested
2628 // in the max/min; if so, we can just return that.
2629 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2630 return V;
2631 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2632 return V;
2633 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002634 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002635 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002636 return V;
2637 break;
2638 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002639 case CmpInst::ICMP_UGT: {
2640 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2641 // Equivalent to "A InvEqP B". This may be the same as the condition
2642 // tested in the max/min; if so, we can just return that.
2643 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2644 return V;
2645 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2646 return V;
2647 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002648 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002649 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002650 return V;
2651 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002652 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002653 case CmpInst::ICMP_UGE:
2654 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002655 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002656 case CmpInst::ICMP_ULT:
2657 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002658 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002659 }
2660 }
2661
Duncan Sandsa2287852011-05-04 16:05:05 +00002662 // Variants on "max(x,y) >= min(x,z)".
2663 Value *C, *D;
2664 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2665 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2666 (A == C || A == D || B == C || B == D)) {
2667 // max(x, ?) pred min(x, ?).
2668 if (Pred == CmpInst::ICMP_SGE)
2669 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002670 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002671 if (Pred == CmpInst::ICMP_SLT)
2672 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002673 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002674 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2675 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2676 (A == C || A == D || B == C || B == D)) {
2677 // min(x, ?) pred max(x, ?).
2678 if (Pred == CmpInst::ICMP_SLE)
2679 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002680 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002681 if (Pred == CmpInst::ICMP_SGT)
2682 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002683 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002684 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2685 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2686 (A == C || A == D || B == C || B == D)) {
2687 // max(x, ?) pred min(x, ?).
2688 if (Pred == CmpInst::ICMP_UGE)
2689 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002690 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002691 if (Pred == CmpInst::ICMP_ULT)
2692 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002693 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002694 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2695 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2696 (A == C || A == D || B == C || B == D)) {
2697 // min(x, ?) pred max(x, ?).
2698 if (Pred == CmpInst::ICMP_ULE)
2699 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002700 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002701 if (Pred == CmpInst::ICMP_UGT)
2702 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002703 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002704 }
2705
Chandler Carruth8059c842012-03-25 21:28:14 +00002706 // Simplify comparisons of related pointers using a powerful, recursive
2707 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00002708 if (LHS->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002709 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00002710 return C;
2711
Nick Lewycky3db143e2012-02-26 02:09:49 +00002712 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2713 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2714 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2715 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2716 (ICmpInst::isEquality(Pred) ||
2717 (GLHS->isInBounds() && GRHS->isInBounds() &&
2718 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2719 // The bases are equal and the indices are constant. Build a constant
2720 // expression GEP with the same indices and a null base pointer to see
2721 // what constant folding can make out of it.
2722 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2723 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2724 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2725
2726 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2727 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2728 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2729 }
2730 }
2731 }
2732
Duncan Sandsf532d312010-11-07 16:12:23 +00002733 // If the comparison is with the result of a select instruction, check whether
2734 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002735 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002736 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002737 return V;
2738
2739 // If the comparison is with the result of a phi instruction, check whether
2740 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002741 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002742 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002743 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00002744
Craig Topper9f008862014-04-15 04:59:12 +00002745 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00002746}
2747
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002748Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002749 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002750 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002751 const DominatorTree *DT,
2752 AssumptionTracker *AT,
2753 Instruction *CxtI) {
2754 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002755 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002756}
2757
Chris Lattnerc1f19072009-11-09 23:28:39 +00002758/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2759/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002760static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002761 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002762 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2763 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2764
Chris Lattnera71e9d62009-11-10 00:55:12 +00002765 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002766 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002767 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00002768
Chris Lattnera71e9d62009-11-10 00:55:12 +00002769 // If we have a constant, make sure it is on the RHS.
2770 std::swap(LHS, RHS);
2771 Pred = CmpInst::getSwappedPredicate(Pred);
2772 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002773
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002774 // Fold trivial predicates.
2775 if (Pred == FCmpInst::FCMP_FALSE)
2776 return ConstantInt::get(GetCompareTy(LHS), 0);
2777 if (Pred == FCmpInst::FCMP_TRUE)
2778 return ConstantInt::get(GetCompareTy(LHS), 1);
2779
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002780 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2781 return UndefValue::get(GetCompareTy(LHS));
2782
2783 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00002784 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002785 if (CmpInst::isTrueWhenEqual(Pred))
2786 return ConstantInt::get(GetCompareTy(LHS), 1);
2787 if (CmpInst::isFalseWhenEqual(Pred))
2788 return ConstantInt::get(GetCompareTy(LHS), 0);
2789 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002790
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002791 // Handle fcmp with constant RHS
2792 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2793 // If the constant is a nan, see if we can fold the comparison based on it.
2794 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2795 if (CFP->getValueAPF().isNaN()) {
2796 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2797 return ConstantInt::getFalse(CFP->getContext());
2798 assert(FCmpInst::isUnordered(Pred) &&
2799 "Comparison must be either ordered or unordered!");
2800 // True if unordered.
2801 return ConstantInt::getTrue(CFP->getContext());
2802 }
Dan Gohman754e4a92010-02-22 04:06:03 +00002803 // Check whether the constant is an infinity.
2804 if (CFP->getValueAPF().isInfinity()) {
2805 if (CFP->getValueAPF().isNegative()) {
2806 switch (Pred) {
2807 case FCmpInst::FCMP_OLT:
2808 // No value is ordered and less than negative infinity.
2809 return ConstantInt::getFalse(CFP->getContext());
2810 case FCmpInst::FCMP_UGE:
2811 // All values are unordered with or at least negative infinity.
2812 return ConstantInt::getTrue(CFP->getContext());
2813 default:
2814 break;
2815 }
2816 } else {
2817 switch (Pred) {
2818 case FCmpInst::FCMP_OGT:
2819 // No value is ordered and greater than infinity.
2820 return ConstantInt::getFalse(CFP->getContext());
2821 case FCmpInst::FCMP_ULE:
2822 // All values are unordered with and at most infinity.
2823 return ConstantInt::getTrue(CFP->getContext());
2824 default:
2825 break;
2826 }
2827 }
2828 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002829 }
2830 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002831
Duncan Sandsa620bd12010-11-07 16:46:25 +00002832 // If the comparison is with the result of a select instruction, check whether
2833 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002834 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002835 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002836 return V;
2837
2838 // If the comparison is with the result of a phi instruction, check whether
2839 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002840 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002841 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002842 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00002843
Craig Topper9f008862014-04-15 04:59:12 +00002844 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002845}
2846
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002847Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002848 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002849 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002850 const DominatorTree *DT,
2851 AssumptionTracker *AT,
2852 const Instruction *CxtI) {
2853 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002854 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002855}
2856
Chris Lattnerc707fa92010-04-20 05:32:14 +00002857/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2858/// the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002859static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2860 Value *FalseVal, const Query &Q,
2861 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00002862 // select true, X, Y -> X
2863 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002864 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2865 if (CB->isAllOnesValue())
2866 return TrueVal;
2867 if (CB->isNullValue())
2868 return FalseVal;
2869 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002870
Chris Lattnerc707fa92010-04-20 05:32:14 +00002871 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00002872 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00002873 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002874
Chris Lattnerc707fa92010-04-20 05:32:14 +00002875 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2876 if (isa<Constant>(TrueVal))
2877 return TrueVal;
2878 return FalseVal;
2879 }
Dan Gohman54664ed2011-07-01 01:03:43 +00002880 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2881 return FalseVal;
2882 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2883 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002884
Craig Topper9f008862014-04-15 04:59:12 +00002885 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00002886}
2887
Duncan Sandsb8cee002012-03-13 11:42:19 +00002888Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002889 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002890 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002891 const DominatorTree *DT,
2892 AssumptionTracker *AT,
2893 const Instruction *CxtI) {
2894 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
2895 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002896}
2897
Chris Lattner8574aba2009-11-27 00:29:05 +00002898/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2899/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002900static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00002901 // The type of the GEP pointer operand.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002902 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
Nico Weber48c82402014-08-27 20:06:19 +00002903 unsigned AS = PtrTy->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00002904
Chris Lattner8574aba2009-11-27 00:29:05 +00002905 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00002906 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00002907 return Ops[0];
2908
Nico Weber48c82402014-08-27 20:06:19 +00002909 // Compute the (pointer) type returned by the GEP instruction.
2910 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2911 Type *GEPTy = PointerType::get(LastType, AS);
2912 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2913 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
2914
2915 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00002916 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00002917
Jay Foadb992a632011-07-19 15:07:52 +00002918 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002919 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002920 if (match(Ops[1], m_Zero()))
2921 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00002922
2923 Type *Ty = PtrTy->getElementType();
2924 if (Q.DL && Ty->isSized()) {
2925 Value *P;
2926 uint64_t C;
2927 uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
2928 // getelementptr P, N -> P if P points to a type of zero size.
2929 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002930 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00002931
2932 // The following transforms are only safe if the ptrtoint cast
2933 // doesn't truncate the pointers.
2934 if (Ops[1]->getType()->getScalarSizeInBits() ==
2935 Q.DL->getPointerSizeInBits(AS)) {
2936 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
2937 if (match(P, m_Zero()))
2938 return Constant::getNullValue(GEPTy);
2939 Value *Temp;
2940 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00002941 if (Temp->getType() == GEPTy)
2942 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00002943 return nullptr;
2944 };
2945
2946 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
2947 if (TyAllocSize == 1 &&
2948 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
2949 if (Value *R = PtrToIntOrZero(P))
2950 return R;
2951
2952 // getelementptr V, (ashr (sub P, V), C) -> Q
2953 // if P points to a type of size 1 << C.
2954 if (match(Ops[1],
2955 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
2956 m_ConstantInt(C))) &&
2957 TyAllocSize == 1ULL << C)
2958 if (Value *R = PtrToIntOrZero(P))
2959 return R;
2960
2961 // getelementptr V, (sdiv (sub P, V), C) -> Q
2962 // if P points to a type of size C.
2963 if (match(Ops[1],
2964 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
2965 m_SpecificInt(TyAllocSize))))
2966 if (Value *R = PtrToIntOrZero(P))
2967 return R;
2968 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002969 }
2970 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002971
Chris Lattner8574aba2009-11-27 00:29:05 +00002972 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00002973 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00002974 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00002975 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00002976
Jay Foaded8db7d2011-07-21 14:31:17 +00002977 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00002978}
2979
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002980Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002981 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002982 const DominatorTree *DT, AssumptionTracker *AT,
2983 const Instruction *CxtI) {
2984 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002985}
2986
Duncan Sandsfd26a952011-09-05 06:52:48 +00002987/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2988/// can fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002989static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2990 ArrayRef<unsigned> Idxs, const Query &Q,
2991 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002992 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2993 if (Constant *CVal = dyn_cast<Constant>(Val))
2994 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2995
2996 // insertvalue x, undef, n -> x
2997 if (match(Val, m_Undef()))
2998 return Agg;
2999
3000 // insertvalue x, (extractvalue y, n), n
3001 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003002 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3003 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003004 // insertvalue undef, (extractvalue y, n), n -> y
3005 if (match(Agg, m_Undef()))
3006 return EV->getAggregateOperand();
3007
3008 // insertvalue y, (extractvalue y, n), n -> y
3009 if (Agg == EV->getAggregateOperand())
3010 return Agg;
3011 }
3012
Craig Topper9f008862014-04-15 04:59:12 +00003013 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003014}
3015
Duncan Sandsb8cee002012-03-13 11:42:19 +00003016Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3017 ArrayRef<unsigned> Idxs,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003018 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003019 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003020 const DominatorTree *DT,
3021 AssumptionTracker *AT,
3022 const Instruction *CxtI) {
3023 return ::SimplifyInsertValueInst(Agg, Val, Idxs,
3024 Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003025 RecursionLimit);
3026}
3027
Duncan Sands7412f6e2010-11-17 04:30:22 +00003028/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003029static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003030 // If all of the PHI's incoming values are the same then replace the PHI node
3031 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003032 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003033 bool HasUndefInput = false;
3034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3035 Value *Incoming = PN->getIncomingValue(i);
3036 // If the incoming value is the phi node itself, it can safely be skipped.
3037 if (Incoming == PN) continue;
3038 if (isa<UndefValue>(Incoming)) {
3039 // Remember that we saw an undef value, but otherwise ignore them.
3040 HasUndefInput = true;
3041 continue;
3042 }
3043 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003044 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003045 CommonValue = Incoming;
3046 }
3047
3048 // If CommonValue is null then all of the incoming values were either undef or
3049 // equal to the phi node itself.
3050 if (!CommonValue)
3051 return UndefValue::get(PN->getType());
3052
3053 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3054 // instruction, we cannot return X as the result of the PHI node unless it
3055 // dominates the PHI block.
3056 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003057 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003058
3059 return CommonValue;
3060}
3061
Duncan Sands395ac42d2012-03-13 14:07:05 +00003062static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3063 if (Constant *C = dyn_cast<Constant>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003064 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003065
Craig Topper9f008862014-04-15 04:59:12 +00003066 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00003067}
3068
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003069Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00003070 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003071 const DominatorTree *DT,
3072 AssumptionTracker *AT,
3073 const Instruction *CxtI) {
3074 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
3075 RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003076}
3077
Chris Lattnera71e9d62009-11-10 00:55:12 +00003078//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003079
Chris Lattnera71e9d62009-11-10 00:55:12 +00003080/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
3081/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003082static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003083 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003084 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003085 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003086 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003087 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003088 case Instruction::FAdd:
3089 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3090
Chris Lattner9e4aa022011-02-09 17:15:04 +00003091 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003092 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003093 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003094 case Instruction::FSub:
3095 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3096
Duncan Sandsb8cee002012-03-13 11:42:19 +00003097 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003098 case Instruction::FMul:
3099 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003100 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3101 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3102 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
3103 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3104 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3105 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003106 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003107 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003108 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003109 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003110 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003111 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003112 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3113 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3114 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3115 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003116 default:
3117 if (Constant *CLHS = dyn_cast<Constant>(LHS))
3118 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3119 Constant *COps[] = {CLHS, CRHS};
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003120 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003121 Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003122 }
Duncan Sandsb0579e92010-11-10 13:00:08 +00003123
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003124 // If the operation is associative, try some generic simplifications.
3125 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003126 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003127 return V;
3128
Duncan Sandsb8cee002012-03-13 11:42:19 +00003129 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003130 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003131 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003132 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003133 return V;
3134
3135 // If the operation is with the result of a phi instruction, check whether
3136 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003137 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003138 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003139 return V;
3140
Craig Topper9f008862014-04-15 04:59:12 +00003141 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003142 }
3143}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003144
Duncan Sands7e800d62010-11-14 11:23:23 +00003145Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003146 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003147 const DominatorTree *DT, AssumptionTracker *AT,
3148 const Instruction *CxtI) {
3149 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3150 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003151}
3152
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003153/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3154/// fold the result.
3155static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003156 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003157 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003158 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3159 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003160}
3161
3162Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003163 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003164 const DominatorTree *DT, AssumptionTracker *AT,
3165 const Instruction *CxtI) {
3166 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003167 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003168}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003169
Michael Ilseman54857292013-02-07 19:26:05 +00003170static bool IsIdempotent(Intrinsic::ID ID) {
3171 switch (ID) {
3172 default: return false;
3173
3174 // Unary idempotent: f(f(x)) = f(x)
3175 case Intrinsic::fabs:
3176 case Intrinsic::floor:
3177 case Intrinsic::ceil:
3178 case Intrinsic::trunc:
3179 case Intrinsic::rint:
3180 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003181 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003182 return true;
3183 }
3184}
3185
3186template <typename IterTy>
3187static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3188 const Query &Q, unsigned MaxRecurse) {
3189 // Perform idempotent optimizations
3190 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003191 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003192
3193 // Unary Ops
3194 if (std::distance(ArgBegin, ArgEnd) == 1)
3195 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3196 if (II->getIntrinsicID() == IID)
3197 return II;
3198
Craig Topper9f008862014-04-15 04:59:12 +00003199 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003200}
3201
Chandler Carruth9dc35582012-12-28 11:30:55 +00003202template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003203static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003204 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003205 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003206 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3207 Ty = PTy->getElementType();
3208 FunctionType *FTy = cast<FunctionType>(Ty);
3209
Dan Gohman85977e62011-11-04 18:32:42 +00003210 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003211 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003212 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003213
Chandler Carruthf6182152012-12-28 14:23:29 +00003214 Function *F = dyn_cast<Function>(V);
3215 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00003216 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003217
Michael Ilseman54857292013-02-07 19:26:05 +00003218 if (unsigned IID = F->getIntrinsicID())
3219 if (Value *Ret =
3220 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3221 return Ret;
3222
Chandler Carruthf6182152012-12-28 14:23:29 +00003223 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00003224 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003225
3226 SmallVector<Constant *, 4> ConstantArgs;
3227 ConstantArgs.reserve(ArgEnd - ArgBegin);
3228 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3229 Constant *C = dyn_cast<Constant>(*I);
3230 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00003231 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003232 ConstantArgs.push_back(C);
3233 }
3234
3235 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00003236}
3237
Chandler Carruthf6182152012-12-28 14:23:29 +00003238Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003239 User::op_iterator ArgEnd, const DataLayout *DL,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003240 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003241 const DominatorTree *DT, AssumptionTracker *AT,
3242 const Instruction *CxtI) {
3243 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003244 RecursionLimit);
3245}
3246
Chandler Carruthf6182152012-12-28 14:23:29 +00003247Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003248 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003249 const DominatorTree *DT, AssumptionTracker *AT,
3250 const Instruction *CxtI) {
3251 return ::SimplifyCall(V, Args.begin(), Args.end(),
3252 Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00003253}
3254
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003255/// SimplifyInstruction - See if we can compute a simplified version of this
3256/// instruction. If not, this returns null.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003257Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003258 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003259 const DominatorTree *DT,
3260 AssumptionTracker *AT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00003261 Value *Result;
3262
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003263 switch (I->getOpcode()) {
3264 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003265 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003266 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003267 case Instruction::FAdd:
3268 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003269 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003270 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00003271 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003272 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3273 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3274 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003275 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003276 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003277 case Instruction::FSub:
3278 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003279 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003280 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00003281 case Instruction::Sub:
3282 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3283 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3284 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003285 DL, TLI, DT, AT, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00003286 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003287 case Instruction::FMul:
3288 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003289 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003290 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003291 case Instruction::Mul:
Hal Finkel60db0582014-09-07 18:57:58 +00003292 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
3293 DL, TLI, DT, AT, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003294 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00003295 case Instruction::SDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003296 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
3297 DL, TLI, DT, AT, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00003298 break;
3299 case Instruction::UDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003300 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
3301 DL, TLI, DT, AT, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00003302 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00003303 case Instruction::FDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003304 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3305 DL, TLI, DT, AT, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00003306 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00003307 case Instruction::SRem:
Hal Finkel60db0582014-09-07 18:57:58 +00003308 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
3309 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003310 break;
3311 case Instruction::URem:
Hal Finkel60db0582014-09-07 18:57:58 +00003312 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
3313 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003314 break;
3315 case Instruction::FRem:
Hal Finkel60db0582014-09-07 18:57:58 +00003316 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3317 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003318 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00003319 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003320 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3321 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3322 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003323 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003324 break;
3325 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003326 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3327 cast<BinaryOperator>(I)->isExact(),
Hal Finkel60db0582014-09-07 18:57:58 +00003328 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003329 break;
3330 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003331 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3332 cast<BinaryOperator>(I)->isExact(),
Hal Finkel60db0582014-09-07 18:57:58 +00003333 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003334 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003335 case Instruction::And:
Hal Finkel60db0582014-09-07 18:57:58 +00003336 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
3337 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003338 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003339 case Instruction::Or:
Hal Finkel60db0582014-09-07 18:57:58 +00003340 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3341 AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003342 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00003343 case Instruction::Xor:
Hal Finkel60db0582014-09-07 18:57:58 +00003344 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
3345 DL, TLI, DT, AT, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00003346 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003347 case Instruction::ICmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003348 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Hal Finkel60db0582014-09-07 18:57:58 +00003349 I->getOperand(0), I->getOperand(1),
3350 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003351 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003352 case Instruction::FCmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003353 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Hal Finkel60db0582014-09-07 18:57:58 +00003354 I->getOperand(0), I->getOperand(1),
3355 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003356 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003357 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003358 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003359 I->getOperand(2), DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003360 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003361 case Instruction::GetElementPtr: {
3362 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Hal Finkel60db0582014-09-07 18:57:58 +00003363 Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003364 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003365 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00003366 case Instruction::InsertValue: {
3367 InsertValueInst *IV = cast<InsertValueInst>(I);
3368 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3369 IV->getInsertedValueOperand(),
Hal Finkel60db0582014-09-07 18:57:58 +00003370 IV->getIndices(), DL, TLI, DT, AT, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00003371 break;
3372 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00003373 case Instruction::PHI:
Hal Finkel60db0582014-09-07 18:57:58 +00003374 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00003375 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003376 case Instruction::Call: {
3377 CallSite CS(cast<CallInst>(I));
3378 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
Hal Finkel60db0582014-09-07 18:57:58 +00003379 DL, TLI, DT, AT, I);
Dan Gohman85977e62011-11-04 18:32:42 +00003380 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003381 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00003382 case Instruction::Trunc:
Hal Finkel60db0582014-09-07 18:57:58 +00003383 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
3384 AT, I);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003385 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003386 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00003387
3388 /// If called on unreachable code, the above logic may report that the
3389 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00003390 /// detecting that case here, returning a safe value instead.
3391 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003392}
3393
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003394/// \brief Implementation of recursive simplification through an instructions
3395/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00003396///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003397/// This is the common implementation of the recursive simplification routines.
3398/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3399/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3400/// instructions to process and attempt to simplify it using
3401/// InstructionSimplify.
3402///
3403/// This routine returns 'true' only when *it* simplifies something. The passed
3404/// in simplified value does not count toward this.
3405static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003406 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003407 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003408 const DominatorTree *DT,
3409 AssumptionTracker *AT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003410 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003411 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands7e800d62010-11-14 11:23:23 +00003412
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003413 // If we have an explicit value to collapse to, do that round of the
3414 // simplification loop by hand initially.
3415 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003416 for (User *U : I->users())
3417 if (U != I)
3418 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00003419
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003420 // Replace the instruction with its simplified value.
3421 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00003422
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003423 // Gracefully handle edge cases where the instruction is not wired into any
3424 // parent block.
3425 if (I->getParent())
3426 I->eraseFromParent();
3427 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003428 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00003429 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003430
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003431 // Note that we must test the size on each iteration, the worklist can grow.
3432 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3433 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00003434
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003435 // See if this instruction simplifies.
Hal Finkel60db0582014-09-07 18:57:58 +00003436 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003437 if (!SimpleV)
3438 continue;
3439
3440 Simplified = true;
3441
3442 // Stash away all the uses of the old instruction so we can check them for
3443 // recursive simplifications after a RAUW. This is cheaper than checking all
3444 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003445 for (User *U : I->users())
3446 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003447
3448 // Replace the instruction with its simplified value.
3449 I->replaceAllUsesWith(SimpleV);
3450
3451 // Gracefully handle edge cases where the instruction is not wired into any
3452 // parent block.
3453 if (I->getParent())
3454 I->eraseFromParent();
3455 }
3456 return Simplified;
3457}
3458
3459bool llvm::recursivelySimplifyInstruction(Instruction *I,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003460 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003461 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003462 const DominatorTree *DT,
3463 AssumptionTracker *AT) {
3464 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003465}
3466
3467bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003468 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003469 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003470 const DominatorTree *DT,
3471 AssumptionTracker *AT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003472 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3473 assert(SimpleV && "Must provide a simplified value.");
Hal Finkel60db0582014-09-07 18:57:58 +00003474 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);
Chris Lattner852d6d62009-11-10 22:26:15 +00003475}