blob: a76e5ad1b8f88621c63a590687251bd7b7b4a0ec [file] [log] [blame]
Chris Lattner9f3c25a2009-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 Sands4cd2ad12010-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 Sandsee9a2e32010-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 Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000021#include "llvm/GlobalAlias.h"
Jay Foad562b84b2011-04-11 09:35:34 +000022#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruth6231d5b2012-03-24 22:34:26 +000024#include "llvm/ADT/SetVector.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000025#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000026#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000027#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000028#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000029#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000030#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000032#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000033#include "llvm/Support/ValueHandle.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000034#include "llvm/DataLayout.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000035using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000036using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000037
Chris Lattner81a0dc92011-02-09 17:15:04 +000038enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000039
Duncan Sandsa3c44a52010-12-22 09:40:51 +000040STATISTIC(NumExpand, "Number of expansions");
41STATISTIC(NumFactor , "Number of factorizations");
42STATISTIC(NumReassoc, "Number of reassociations");
43
Duncan Sands0aa85eb2012-03-13 11:42:19 +000044struct Query {
Micah Villmow3574eca2012-10-08 16:38:25 +000045 const DataLayout *TD;
Duncan Sands0aa85eb2012-03-13 11:42:19 +000046 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
48
Micah Villmow3574eca2012-10-08 16:38:25 +000049 Query(const DataLayout *td, const TargetLibraryInfo *tli,
Bill Wendling91337832012-05-17 20:27:58 +000050 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {}
Duncan Sands0aa85eb2012-03-13 11:42:19 +000051};
52
53static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000055 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000056static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000057 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000058static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sandsbd0fe562012-03-13 14:07:05 +000060static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000061
Duncan Sandsf56138d2011-07-26 15:03:53 +000062/// getFalse - For a boolean type, or a vector of boolean type, return false, or
63/// a vector with every element false, as appropriate for the type.
64static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000065 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000066 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
68}
69
70/// getTrue - For a boolean type, or a vector of boolean type, return true, or
71/// a vector with every element true, as appropriate for the type.
72static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000073 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000074 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
76}
77
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000078/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80 Value *RHS) {
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
82 if (!Cmp)
83 return false;
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87 return true;
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 CRHS == LHS;
90}
91
Duncan Sands18450092010-11-16 12:16:38 +000092/// ValueDominatesPHI - Does the given value dominate the specified phi node?
93static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
95 if (!I)
96 // Arguments and constants dominate all instructions.
97 return true;
98
Chandler Carruthff739c12012-03-21 10:58:47 +000099 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103 return false;
104
Duncan Sands18450092010-11-16 12:16:38 +0000105 // If we have a DominatorTree then do a precise test.
Eli Friedman5b8f0dd2012-03-13 01:06:07 +0000106 if (DT) {
107 if (!DT->isReachableFromEntry(P->getParent()))
108 return true;
109 if (!DT->isReachableFromEntry(I->getParent()))
110 return false;
111 return DT->dominates(I, P);
112 }
Duncan Sands18450092010-11-16 12:16:38 +0000113
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117 !isa<InvokeInst>(I))
118 return true;
119
120 return false;
121}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000122
Duncan Sands3421d902010-12-21 13:32:22 +0000123/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127/// Returns the simplified value, or null if no simplification was performed.
128static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000129 unsigned OpcToExpand, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000130 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000132 // Recursion is always used, so bail out at once if we already hit the limit.
133 if (!MaxRecurse--)
134 return 0;
135
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000148 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000149 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000150 }
Duncan Sands3421d902010-12-21 13:32:22 +0000151 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000153 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000154 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000155 }
Duncan Sands3421d902010-12-21 13:32:22 +0000156 }
157 }
158
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000172 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000173 }
Duncan Sands3421d902010-12-21 13:32:22 +0000174 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000176 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000177 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000178 }
Duncan Sands3421d902010-12-21 13:32:22 +0000179 }
180 }
181
182 return 0;
183}
184
185/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186/// using the operation OpCodeToExtract. For example, when Opcode is Add and
187/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188/// Returns the simplified value, or null if no simplification was performed.
189static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000190 unsigned OpcToExtract, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000191 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000193 // Recursion is always used, so bail out at once if we already hit the limit.
194 if (!MaxRecurse--)
195 return 0;
196
197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
199
200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201 !Op1 || Op1->getOpcode() != OpcodeToExtract)
202 return 0;
203
204 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000207
208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000213 // Form "A op' (B op DD)" if it simplifies completely.
214 // Does "B op DD" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000216 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000217 // If V equals B then "A op' V" is just the LHS. If V equals DD then
218 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000219 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000220 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000221 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000222 }
Duncan Sands3421d902010-12-21 13:32:22 +0000223 // Otherwise return "A op' V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000225 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000226 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000227 }
Duncan Sands3421d902010-12-21 13:32:22 +0000228 }
229 }
230
231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000236 // Form "(A op CC) op' B" if it simplifies completely..
237 // Does "A op CC" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000239 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000240 // If V equals A then "V op' B" is just the LHS. If V equals CC then
241 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000242 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000243 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000244 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000245 }
Duncan Sands3421d902010-12-21 13:32:22 +0000246 // Otherwise return "V op' B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000248 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000249 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000250 }
Duncan Sands3421d902010-12-21 13:32:22 +0000251 }
252 }
253
254 return 0;
255}
256
257/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000259static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000260 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
263
264 // Recursion is always used, so bail out at once if we already hit the limit.
265 if (!MaxRecurse--)
266 return 0;
267
268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
270
271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272 if (Op0 && Op0->getOpcode() == Opcode) {
273 Value *A = Op0->getOperand(0);
274 Value *B = Op0->getOperand(1);
275 Value *C = RHS;
276
277 // Does "B op C" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000279 // It does! Return "A op V" if it simplifies or is already available.
280 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000281 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000282 // Otherwise return "A op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000284 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000285 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000286 }
Duncan Sands566edb02010-12-21 08:49:00 +0000287 }
288 }
289
290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291 if (Op1 && Op1->getOpcode() == Opcode) {
292 Value *A = LHS;
293 Value *B = Op1->getOperand(0);
294 Value *C = Op1->getOperand(1);
295
296 // Does "A op B" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000298 // It does! Return "V op C" if it simplifies or is already available.
299 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000300 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000301 // Otherwise return "V op C" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000303 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000304 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000305 }
Duncan Sands566edb02010-12-21 08:49:00 +0000306 }
307 }
308
309 // The remaining transforms require commutativity as well as associativity.
310 if (!Instruction::isCommutative(Opcode))
311 return 0;
312
313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314 if (Op0 && Op0->getOpcode() == Opcode) {
315 Value *A = Op0->getOperand(0);
316 Value *B = Op0->getOperand(1);
317 Value *C = RHS;
318
319 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000321 // It does! Return "V op B" if it simplifies or is already available.
322 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000323 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000324 // Otherwise return "V op B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000326 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000327 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000328 }
Duncan Sands566edb02010-12-21 08:49:00 +0000329 }
330 }
331
332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333 if (Op1 && Op1->getOpcode() == Opcode) {
334 Value *A = LHS;
335 Value *B = Op1->getOperand(0);
336 Value *C = Op1->getOperand(1);
337
338 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000340 // It does! Return "B op V" if it simplifies or is already available.
341 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000342 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000343 // Otherwise return "B op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000345 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000346 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000347 }
Duncan Sands566edb02010-12-21 08:49:00 +0000348 }
349 }
350
351 return 0;
352}
353
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000354/// ThreadBinOpOverSelect - In the case of a binary operation with a select
355/// instruction as an operand, try to simplify the binop by seeing whether
356/// evaluating it on both branches of the select results in the same value.
357/// Returns the common value if so, otherwise returns null.
358static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000359 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000360 // Recursion is always used, so bail out at once if we already hit the limit.
361 if (!MaxRecurse--)
362 return 0;
363
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000364 SelectInst *SI;
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
367 } else {
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
370 }
371
372 // Evaluate the BinOp on the true and false branches of the select.
373 Value *TV;
374 Value *FV;
375 if (SI == LHS) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000378 } else {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000381 }
382
Duncan Sands7cf85e72011-01-01 16:12:09 +0000383 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000384 // If they both failed to simplify then return null.
385 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000386 return TV;
387
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
390 return FV;
391 if (FV && isa<UndefValue>(FV))
392 return TV;
393
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000397 return SI;
398
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000415 return Simplified;
416 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000419 return Simplified;
420 }
421 }
422
423 return 0;
424}
425
426/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427/// try to simplify the comparison by seeing whether both branches of the select
428/// result in the same value. Returns the common value if so, otherwise returns
429/// null.
430static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000431 Value *RHS, const Query &Q,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000432 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000433 // Recursion is always used, so bail out at once if we already hit the limit.
434 if (!MaxRecurse--)
435 return 0;
436
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
439 std::swap(LHS, RHS);
440 Pred = CmpInst::getSwappedPredicate(Pred);
441 }
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000447
Duncan Sands50ca4d32011-02-03 09:37:39 +0000448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000449 // Does "cmp TV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000451 if (TCmp == Cond) {
452 // It not only simplified, it simplified to the select condition. Replace
453 // it with 'true'.
454 TCmp = getTrue(Cond->getType());
455 } else if (!TCmp) {
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
459 return 0;
460 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000461 }
462
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000463 // Does "cmp FV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000465 if (FCmp == Cond) {
466 // It not only simplified, it simplified to the select condition. Replace
467 // it with 'false'.
468 FCmp = getFalse(Cond->getType());
469 } else if (!FCmp) {
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
473 return 0;
474 FCmp = getFalse(Cond->getType());
475 }
476
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
479 if (TCmp == FCmp)
480 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000481
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000491 return V;
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000496 return V;
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500 if (Value *V =
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000502 Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000503 return V;
504
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000505 return 0;
506}
507
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000508/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510/// it on the incoming phi values yields the same result for every value. If so
511/// returns the common value, otherwise returns null.
512static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000513 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000514 // Recursion is always used, so bail out at once if we already hit the limit.
515 if (!MaxRecurse--)
516 return 0;
517
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000518 PHINode *PI;
519 if (isa<PHINode>(LHS)) {
520 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000521 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000522 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000523 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000524 } else {
525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000527 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000528 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000529 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000530 }
531
532 // Evaluate the BinOp on the incoming phi values.
533 Value *CommonValue = 0;
534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000535 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000536 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000537 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000538 Value *V = PI == LHS ?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000541 // If the operation failed to simplify, or simplified to a different value
542 // to previously, then give up.
543 if (!V || (CommonValue && V != CommonValue))
544 return 0;
545 CommonValue = V;
546 }
547
548 return CommonValue;
549}
550
551/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552/// try to simplify the comparison by seeing whether comparing with all of the
553/// incoming phi values yields the same result every time. If so returns the
554/// common result, otherwise returns null.
555static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000556 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000557 // Recursion is always used, so bail out at once if we already hit the limit.
558 if (!MaxRecurse--)
559 return 0;
560
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000561 // Make sure the phi is on the LHS.
562 if (!isa<PHINode>(LHS)) {
563 std::swap(LHS, RHS);
564 Pred = CmpInst::getSwappedPredicate(Pred);
565 }
566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567 PHINode *PI = cast<PHINode>(LHS);
568
Duncan Sands18450092010-11-16 12:16:38 +0000569 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000570 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000571 return 0;
572
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000573 // Evaluate the BinOp on the incoming phi values.
574 Value *CommonValue = 0;
575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000576 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000577 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000578 if (Incoming == PI) continue;
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000580 // If the operation failed to simplify, or simplified to a different value
581 // to previously, then give up.
582 if (!V || (CommonValue && V != CommonValue))
583 return 0;
584 CommonValue = V;
585 }
586
587 return CommonValue;
588}
589
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000590/// SimplifyAddInst - Given operands for an Add, see if we can
591/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000592static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000593 const Query &Q, unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
598 Q.TD, Q.TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000599 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000600
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000601 // Canonicalize the constant to the RHS.
602 std::swap(Op0, Op1);
603 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000604
Duncan Sandsfea3b212010-12-15 14:07:39 +0000605 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000606 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000607 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000608
Duncan Sandsfea3b212010-12-15 14:07:39 +0000609 // X + 0 -> X
610 if (match(Op1, m_Zero()))
611 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000612
Duncan Sandsfea3b212010-12-15 14:07:39 +0000613 // X + (Y - X) -> Y
614 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000615 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000616 Value *Y = 0;
617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000619 return Y;
620
621 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000622 if (match(Op0, m_Not(m_Specific(Op1))) ||
623 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000624 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000625
Duncan Sands82fdab32010-12-21 14:00:22 +0000626 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000627 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000629 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000630
Duncan Sands566edb02010-12-21 08:49:00 +0000631 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands566edb02010-12-21 08:49:00 +0000633 MaxRecurse))
634 return V;
635
Duncan Sands3421d902010-12-21 13:32:22 +0000636 // Mul distributes over Add. Try some generic simplifications based on this.
637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000638 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000639 return V;
640
Duncan Sands87689cf2010-11-19 09:20:39 +0000641 // Threading Add over selects and phi nodes is pointless, so don't bother.
642 // Threading over the select in "A + select(cond, B, C)" means evaluating
643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644 // only if B and C are equal. If B and C are equal then (since we assume
645 // that operands have already been simplified) "select(cond, B, C)" should
646 // have been simplified to the common value of B and C already. Analysing
647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
648 // for threading over phi nodes.
649
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000650 return 0;
651}
652
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000653Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000654 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000655 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
657 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000658}
659
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000660/// \brief Accumulate the constant integer offset a GEP represents.
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000661///
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000662/// Given a getelementptr instruction/constantexpr, accumulate the constant
663/// offset from the base pointer into the provided APInt 'Offset'. Returns true
664/// if the GEP has all-constant indices. Returns false if any non-constant
665/// index is encountered leaving the 'Offset' in an undefined state. The
666/// 'Offset' APInt must be the bitwidth of the target's pointer size.
Micah Villmow3574eca2012-10-08 16:38:25 +0000667static bool accumulateGEPOffset(const DataLayout &TD, GEPOperator *GEP,
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000668 APInt &Offset) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000669 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000670 assert(IntPtrWidth == Offset.getBitWidth());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000671
672 gep_type_iterator GTI = gep_type_begin(GEP);
673 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
674 ++I, ++GTI) {
675 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000676 if (!OpC) return false;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000677 if (OpC->isZero()) continue;
678
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000679 // Handle a struct index, which adds its field offset to the pointer.
680 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000681 unsigned ElementIdx = OpC->getZExtValue();
682 const StructLayout *SL = TD.getStructLayout(STy);
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000683 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000684 continue;
685 }
686
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000687 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000688 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000689 }
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000690 return true;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000691}
692
693/// \brief Compute the base pointer and cumulative constant offsets for V.
694///
695/// This strips all constant offsets off of V, leaving it the base pointer, and
696/// accumulates the total constant offset applied in the returned constant. It
697/// returns 0 if V is not a pointer, and returns the constant '0' if there are
698/// no constant offsets applied.
Micah Villmow3574eca2012-10-08 16:38:25 +0000699static Constant *stripAndComputeConstantOffsets(const DataLayout &TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000700 Value *&V) {
701 if (!V->getType()->isPointerTy())
702 return 0;
703
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000704 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000705 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000706
707 // Even though we don't look through PHI nodes, we could be called on an
708 // instruction in an unreachable block, which may be on a cycle.
709 SmallPtrSet<Value *, 4> Visited;
710 Visited.insert(V);
711 do {
712 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth9d9e29b2012-03-25 20:43:07 +0000713 if (!GEP->isInBounds() || !accumulateGEPOffset(TD, GEP, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000714 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000715 V = GEP->getPointerOperand();
716 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
717 V = cast<Operator>(V)->getOperand(0);
718 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
719 if (GA->mayBeOverridden())
720 break;
721 V = GA->getAliasee();
722 } else {
723 break;
724 }
725 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
726 } while (Visited.insert(V));
727
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000728 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000729 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000730}
731
732/// \brief Compute the constant difference between two pointer values.
733/// If the difference is not a constant, returns zero.
Micah Villmow3574eca2012-10-08 16:38:25 +0000734static Constant *computePointerDifference(const DataLayout &TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000735 Value *LHS, Value *RHS) {
736 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
737 if (!LHSOffset)
738 return 0;
739 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
740 if (!RHSOffset)
741 return 0;
742
743 // If LHS and RHS are not related via constant offsets to the same base
744 // value, there is nothing we can do here.
745 if (LHS != RHS)
746 return 0;
747
748 // Otherwise, the difference of LHS - RHS can be computed as:
749 // LHS - RHS
750 // = (LHSOffset + Base) - (RHSOffset + Base)
751 // = LHSOffset - RHSOffset
752 return ConstantExpr::getSub(LHSOffset, RHSOffset);
753}
754
Duncan Sandsfea3b212010-12-15 14:07:39 +0000755/// SimplifySubInst - Given operands for a Sub, see if we can
756/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000757static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000758 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000759 if (Constant *CLHS = dyn_cast<Constant>(Op0))
760 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
761 Constant *Ops[] = { CLHS, CRHS };
762 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000763 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000764 }
765
766 // X - undef -> undef
767 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000768 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000769 return UndefValue::get(Op0->getType());
770
771 // X - 0 -> X
772 if (match(Op1, m_Zero()))
773 return Op0;
774
775 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000776 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000777 return Constant::getNullValue(Op0->getType());
778
Duncan Sandsfe02c692011-01-18 09:24:58 +0000779 // (X*2) - X -> X
780 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000781 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000782 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
783 match(Op0, m_Shl(m_Specific(Op1), m_One())))
784 return Op1;
785
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000786 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
787 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
788 Value *Y = 0, *Z = Op1;
789 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
790 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000791 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000792 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000793 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000794 // It does, we successfully reassociated!
795 ++NumReassoc;
796 return W;
797 }
798 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000799 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000800 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000801 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000802 // It does, we successfully reassociated!
803 ++NumReassoc;
804 return W;
805 }
806 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000807
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000808 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
809 // For example, X - (X + 1) -> -1
810 X = Op0;
811 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
812 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000813 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000814 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000815 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000816 // It does, we successfully reassociated!
817 ++NumReassoc;
818 return W;
819 }
820 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000821 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000822 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000823 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000824 // It does, we successfully reassociated!
825 ++NumReassoc;
826 return W;
827 }
828 }
829
830 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
831 // For example, X - (X - Y) -> Y.
832 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000833 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
834 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000835 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000836 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000837 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000838 // It does, we successfully reassociated!
839 ++NumReassoc;
840 return W;
841 }
842
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000843 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
844 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
845 match(Op1, m_Trunc(m_Value(Y))))
846 if (X->getType() == Y->getType())
847 // See if "V === X - Y" simplifies.
848 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
849 // It does! Now see if "trunc V" simplifies.
850 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
851 // It does, return the simplified "trunc V".
852 return W;
853
854 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
855 if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
856 match(Op1, m_PtrToInt(m_Value(Y))))
857 if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
858 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
859
Duncan Sands3421d902010-12-21 13:32:22 +0000860 // Mul distributes over Sub. Try some generic simplifications based on this.
861 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000862 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000863 return V;
864
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000865 // i1 sub -> xor.
866 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000867 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000868 return V;
869
Duncan Sandsfea3b212010-12-15 14:07:39 +0000870 // Threading Sub over selects and phi nodes is pointless, so don't bother.
871 // Threading over the select in "A - select(cond, B, C)" means evaluating
872 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
873 // only if B and C are equal. If B and C are equal then (since we assume
874 // that operands have already been simplified) "select(cond, B, C)" should
875 // have been simplified to the common value of B and C already. Analysing
876 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
877 // for threading over phi nodes.
878
879 return 0;
880}
881
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000882Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000883 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000884 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000885 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
886 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000887}
888
Duncan Sands82fdab32010-12-21 14:00:22 +0000889/// SimplifyMulInst - Given operands for a Mul, see if we can
890/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000891static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
892 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000893 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
894 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
895 Constant *Ops[] = { CLHS, CRHS };
896 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000897 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000898 }
899
900 // Canonicalize the constant to the RHS.
901 std::swap(Op0, Op1);
902 }
903
904 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000905 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000906 return Constant::getNullValue(Op0->getType());
907
908 // X * 0 -> 0
909 if (match(Op1, m_Zero()))
910 return Op1;
911
912 // X * 1 -> X
913 if (match(Op1, m_One()))
914 return Op0;
915
Duncan Sands1895e982011-01-30 18:03:50 +0000916 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000917 Value *X = 0;
918 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
919 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
920 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000921
Nick Lewycky54138802011-01-29 19:55:23 +0000922 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000923 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000924 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000925 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000926
927 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000928 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000929 MaxRecurse))
930 return V;
931
932 // Mul distributes over Add. Try some generic simplifications based on this.
933 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000934 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000935 return V;
936
937 // If the operation is with the result of a select instruction, check whether
938 // operating on either branch of the select always yields the same value.
939 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000940 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
944 // If the operation is with the result of a phi instruction, check whether
945 // operating on all incoming values of the phi always yields the same value.
946 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000947 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000948 MaxRecurse))
949 return V;
950
951 return 0;
952}
953
Micah Villmow3574eca2012-10-08 16:38:25 +0000954Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000955 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000956 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000957 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000958}
959
Duncan Sands593faa52011-01-28 16:51:11 +0000960/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
961/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000962static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000963 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000964 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
965 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
966 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000967 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000968 }
969 }
970
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000971 bool isSigned = Opcode == Instruction::SDiv;
972
Duncan Sands593faa52011-01-28 16:51:11 +0000973 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000974 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000975 return Op1;
976
977 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000978 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000979 return Constant::getNullValue(Op0->getType());
980
981 // 0 / X -> 0, we don't need to preserve faults!
982 if (match(Op0, m_Zero()))
983 return Op0;
984
985 // X / 1 -> X
986 if (match(Op1, m_One()))
987 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000988
989 if (Op0->getType()->isIntegerTy(1))
990 // It can't be division by zero, hence it must be division by one.
991 return Op0;
992
993 // X / X -> 1
994 if (Op0 == Op1)
995 return ConstantInt::get(Op0->getType(), 1);
996
997 // (X * Y) / Y -> X if the multiplication does not overflow.
998 Value *X = 0, *Y = 0;
999 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1000 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001001 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001002 // If the Mul knows it does not overflow, then we are good to go.
1003 if ((isSigned && Mul->hasNoSignedWrap()) ||
1004 (!isSigned && Mul->hasNoUnsignedWrap()))
1005 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001006 // If X has the form X = A / Y then X * Y cannot overflow.
1007 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1008 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1009 return X;
1010 }
1011
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001012 // (X rem Y) / Y -> 0
1013 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1014 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1015 return Constant::getNullValue(Op0->getType());
1016
1017 // If the operation is with the result of a select instruction, check whether
1018 // operating on either branch of the select always yields the same value.
1019 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001020 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001021 return V;
1022
1023 // If the operation is with the result of a phi instruction, check whether
1024 // operating on all incoming values of the phi always yields the same value.
1025 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001026 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001027 return V;
1028
Duncan Sands593faa52011-01-28 16:51:11 +00001029 return 0;
1030}
1031
1032/// SimplifySDivInst - Given operands for an SDiv, see if we can
1033/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001034static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1035 unsigned MaxRecurse) {
1036 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001037 return V;
1038
Duncan Sands593faa52011-01-28 16:51:11 +00001039 return 0;
1040}
1041
Micah Villmow3574eca2012-10-08 16:38:25 +00001042Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001043 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001044 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001045 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001046}
1047
1048/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1049/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001050static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1051 unsigned MaxRecurse) {
1052 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001053 return V;
1054
Duncan Sands593faa52011-01-28 16:51:11 +00001055 return 0;
1056}
1057
Micah Villmow3574eca2012-10-08 16:38:25 +00001058Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001059 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001060 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001061 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001062}
1063
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001064static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1065 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001066 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001067 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001068 return Op0;
1069
1070 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001071 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001072 return Op1;
1073
1074 return 0;
1075}
1076
Micah Villmow3574eca2012-10-08 16:38:25 +00001077Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001078 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001079 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001080 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001081}
1082
Duncan Sandsf24ed772011-05-02 16:27:02 +00001083/// SimplifyRem - Given operands for an SRem or URem, see if we can
1084/// fold the result. If not, this returns null.
1085static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001086 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001087 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1088 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1089 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001090 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001091 }
1092 }
1093
Duncan Sandsf24ed772011-05-02 16:27:02 +00001094 // X % undef -> undef
1095 if (match(Op1, m_Undef()))
1096 return Op1;
1097
1098 // undef % X -> 0
1099 if (match(Op0, m_Undef()))
1100 return Constant::getNullValue(Op0->getType());
1101
1102 // 0 % X -> 0, we don't need to preserve faults!
1103 if (match(Op0, m_Zero()))
1104 return Op0;
1105
1106 // X % 0 -> undef, we don't need to preserve faults!
1107 if (match(Op1, m_Zero()))
1108 return UndefValue::get(Op0->getType());
1109
1110 // X % 1 -> 0
1111 if (match(Op1, m_One()))
1112 return Constant::getNullValue(Op0->getType());
1113
1114 if (Op0->getType()->isIntegerTy(1))
1115 // It can't be remainder by zero, hence it must be remainder by one.
1116 return Constant::getNullValue(Op0->getType());
1117
1118 // X % X -> 0
1119 if (Op0 == Op1)
1120 return Constant::getNullValue(Op0->getType());
1121
1122 // If the operation is with the result of a select instruction, check whether
1123 // operating on either branch of the select always yields the same value.
1124 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001125 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001126 return V;
1127
1128 // If the operation is with the result of a phi instruction, check whether
1129 // operating on all incoming values of the phi always yields the same value.
1130 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001131 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001132 return V;
1133
1134 return 0;
1135}
1136
1137/// SimplifySRemInst - Given operands for an SRem, see if we can
1138/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001139static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1140 unsigned MaxRecurse) {
1141 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001142 return V;
1143
1144 return 0;
1145}
1146
Micah Villmow3574eca2012-10-08 16:38:25 +00001147Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001148 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001149 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001150 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001151}
1152
1153/// SimplifyURemInst - Given operands for a URem, see if we can
1154/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001155static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001156 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001157 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001158 return V;
1159
1160 return 0;
1161}
1162
Micah Villmow3574eca2012-10-08 16:38:25 +00001163Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001164 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001165 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001166 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001167}
1168
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001169static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001170 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001171 // undef % X -> undef (the undef could be a snan).
1172 if (match(Op0, m_Undef()))
1173 return Op0;
1174
1175 // X % undef -> undef
1176 if (match(Op1, m_Undef()))
1177 return Op1;
1178
1179 return 0;
1180}
1181
Micah Villmow3574eca2012-10-08 16:38:25 +00001182Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001183 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001184 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001185 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001186}
1187
Duncan Sandscf80bc12011-01-14 14:44:12 +00001188/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001189/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001190static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001191 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001192 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1193 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1194 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001195 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001196 }
1197 }
1198
Duncan Sandscf80bc12011-01-14 14:44:12 +00001199 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001200 if (match(Op0, m_Zero()))
1201 return Op0;
1202
Duncan Sandscf80bc12011-01-14 14:44:12 +00001203 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001204 if (match(Op1, m_Zero()))
1205 return Op0;
1206
Duncan Sandscf80bc12011-01-14 14:44:12 +00001207 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001208 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001209 return Op1;
1210
1211 // Shifting by the bitwidth or more is undefined.
1212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1213 if (CI->getValue().getLimitedValue() >=
1214 Op0->getType()->getScalarSizeInBits())
1215 return UndefValue::get(Op0->getType());
1216
Duncan Sandscf80bc12011-01-14 14:44:12 +00001217 // If the operation is with the result of a select instruction, check whether
1218 // operating on either branch of the select always yields the same value.
1219 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001220 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001221 return V;
1222
1223 // If the operation is with the result of a phi instruction, check whether
1224 // operating on all incoming values of the phi always yields the same value.
1225 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001226 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001227 return V;
1228
1229 return 0;
1230}
1231
1232/// SimplifyShlInst - Given operands for an Shl, see if we can
1233/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001234static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001235 const Query &Q, unsigned MaxRecurse) {
1236 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001237 return V;
1238
1239 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001240 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001241 return Constant::getNullValue(Op0->getType());
1242
Chris Lattner81a0dc92011-02-09 17:15:04 +00001243 // (X >> A) << A -> X
1244 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001245 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001246 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001247 return 0;
1248}
1249
Chris Lattner81a0dc92011-02-09 17:15:04 +00001250Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +00001251 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00001252 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001253 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1254 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001255}
1256
1257/// SimplifyLShrInst - Given operands for an LShr, see if we can
1258/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001259static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001260 const Query &Q, unsigned MaxRecurse) {
1261 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001262 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001263
1264 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001265 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001266 return Constant::getNullValue(Op0->getType());
1267
Chris Lattner81a0dc92011-02-09 17:15:04 +00001268 // (X << A) >> A -> X
1269 Value *X;
1270 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1271 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1272 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001273
Duncan Sandsc43cee32011-01-14 00:37:45 +00001274 return 0;
1275}
1276
Chris Lattner81a0dc92011-02-09 17:15:04 +00001277Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001278 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001279 const TargetLibraryInfo *TLI,
1280 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001281 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1282 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001283}
1284
1285/// SimplifyAShrInst - Given operands for an AShr, see if we can
1286/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001287static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001288 const Query &Q, unsigned MaxRecurse) {
1289 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001290 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001291
1292 // all ones >>a X -> all ones
1293 if (match(Op0, m_AllOnes()))
1294 return Op0;
1295
1296 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001297 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001298 return Constant::getAllOnesValue(Op0->getType());
1299
Chris Lattner81a0dc92011-02-09 17:15:04 +00001300 // (X << A) >> A -> X
1301 Value *X;
1302 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1303 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1304 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001305
Duncan Sandsc43cee32011-01-14 00:37:45 +00001306 return 0;
1307}
1308
Chris Lattner81a0dc92011-02-09 17:15:04 +00001309Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001310 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001311 const TargetLibraryInfo *TLI,
1312 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001313 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1314 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001315}
1316
Chris Lattnerd06094f2009-11-10 00:55:12 +00001317/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001318/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001319static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001320 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001321 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1322 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1323 Constant *Ops[] = { CLHS, CRHS };
1324 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001325 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001326 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001327
Chris Lattnerd06094f2009-11-10 00:55:12 +00001328 // Canonicalize the constant to the RHS.
1329 std::swap(Op0, Op1);
1330 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001331
Chris Lattnerd06094f2009-11-10 00:55:12 +00001332 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001333 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001334 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001335
Chris Lattnerd06094f2009-11-10 00:55:12 +00001336 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001337 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001338 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001339
Duncan Sands2b749872010-11-17 18:52:15 +00001340 // X & 0 = 0
1341 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001342 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001343
Duncan Sands2b749872010-11-17 18:52:15 +00001344 // X & -1 = X
1345 if (match(Op1, m_AllOnes()))
1346 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001347
Chris Lattnerd06094f2009-11-10 00:55:12 +00001348 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001349 if (match(Op0, m_Not(m_Specific(Op1))) ||
1350 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001351 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001352
Chris Lattnerd06094f2009-11-10 00:55:12 +00001353 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001354 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001355 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001356 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001357 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001358
Chris Lattnerd06094f2009-11-10 00:55:12 +00001359 // A & (A | ?) = A
1360 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001361 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001362 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001363
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001364 // A & (-A) = A if A is a power of two or zero.
1365 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1366 match(Op1, m_Neg(m_Specific(Op0)))) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001367 if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001368 return Op0;
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001369 if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001370 return Op1;
1371 }
1372
Duncan Sands566edb02010-12-21 08:49:00 +00001373 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001374 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1375 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001376 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001377
Duncan Sands3421d902010-12-21 13:32:22 +00001378 // And distributes over Or. Try some generic simplifications based on this.
1379 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001380 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001381 return V;
1382
1383 // And distributes over Xor. Try some generic simplifications based on this.
1384 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001385 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001386 return V;
1387
1388 // Or distributes over And. Try some generic simplifications based on this.
1389 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001390 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001391 return V;
1392
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001393 // If the operation is with the result of a select instruction, check whether
1394 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001395 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001396 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1397 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001398 return V;
1399
1400 // If the operation is with the result of a phi instruction, check whether
1401 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001402 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001403 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001404 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001405 return V;
1406
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001407 return 0;
1408}
1409
Micah Villmow3574eca2012-10-08 16:38:25 +00001410Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001411 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001412 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001413 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001414}
1415
Chris Lattnerd06094f2009-11-10 00:55:12 +00001416/// SimplifyOrInst - Given operands for an Or, see if we can
1417/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001418static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1419 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001420 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1421 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1422 Constant *Ops[] = { CLHS, CRHS };
1423 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001424 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001425 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001426
Chris Lattnerd06094f2009-11-10 00:55:12 +00001427 // Canonicalize the constant to the RHS.
1428 std::swap(Op0, Op1);
1429 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001430
Chris Lattnerd06094f2009-11-10 00:55:12 +00001431 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001432 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001433 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001434
Chris Lattnerd06094f2009-11-10 00:55:12 +00001435 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001436 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001437 return Op0;
1438
Duncan Sands2b749872010-11-17 18:52:15 +00001439 // X | 0 = X
1440 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001441 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001442
Duncan Sands2b749872010-11-17 18:52:15 +00001443 // X | -1 = -1
1444 if (match(Op1, m_AllOnes()))
1445 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001446
Chris Lattnerd06094f2009-11-10 00:55:12 +00001447 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001448 if (match(Op0, m_Not(m_Specific(Op1))) ||
1449 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001450 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001451
Chris Lattnerd06094f2009-11-10 00:55:12 +00001452 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001453 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001454 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001455 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001456 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001457
Chris Lattnerd06094f2009-11-10 00:55:12 +00001458 // A | (A & ?) = A
1459 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001460 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001461 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001462
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001463 // ~(A & ?) | A = -1
1464 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1465 (A == Op1 || B == Op1))
1466 return Constant::getAllOnesValue(Op1->getType());
1467
1468 // A | ~(A & ?) = -1
1469 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1470 (A == Op0 || B == Op0))
1471 return Constant::getAllOnesValue(Op0->getType());
1472
Duncan Sands566edb02010-12-21 08:49:00 +00001473 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001474 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1475 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001476 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001477
Duncan Sands3421d902010-12-21 13:32:22 +00001478 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001479 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1480 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001481 return V;
1482
1483 // And distributes over Or. Try some generic simplifications based on this.
1484 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001485 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001486 return V;
1487
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001488 // If the operation is with the result of a select instruction, check whether
1489 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001490 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001491 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001492 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001493 return V;
1494
1495 // If the operation is with the result of a phi instruction, check whether
1496 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001497 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001498 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001499 return V;
1500
Chris Lattnerd06094f2009-11-10 00:55:12 +00001501 return 0;
1502}
1503
Micah Villmow3574eca2012-10-08 16:38:25 +00001504Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001505 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001506 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001507 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001508}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001509
Duncan Sands2b749872010-11-17 18:52:15 +00001510/// SimplifyXorInst - Given operands for a Xor, see if we can
1511/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001512static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1513 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001514 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1515 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1516 Constant *Ops[] = { CLHS, CRHS };
1517 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001518 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001519 }
1520
1521 // Canonicalize the constant to the RHS.
1522 std::swap(Op0, Op1);
1523 }
1524
1525 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001526 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001527 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001528
1529 // A ^ 0 = A
1530 if (match(Op1, m_Zero()))
1531 return Op0;
1532
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001533 // A ^ A = 0
1534 if (Op0 == Op1)
1535 return Constant::getNullValue(Op0->getType());
1536
Duncan Sands2b749872010-11-17 18:52:15 +00001537 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001538 if (match(Op0, m_Not(m_Specific(Op1))) ||
1539 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001540 return Constant::getAllOnesValue(Op0->getType());
1541
Duncan Sands566edb02010-12-21 08:49:00 +00001542 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001543 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1544 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001545 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001546
Duncan Sands3421d902010-12-21 13:32:22 +00001547 // And distributes over Xor. Try some generic simplifications based on this.
1548 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001549 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001550 return V;
1551
Duncan Sands87689cf2010-11-19 09:20:39 +00001552 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1553 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1554 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1555 // only if B and C are equal. If B and C are equal then (since we assume
1556 // that operands have already been simplified) "select(cond, B, C)" should
1557 // have been simplified to the common value of B and C already. Analysing
1558 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1559 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001560
1561 return 0;
1562}
1563
Micah Villmow3574eca2012-10-08 16:38:25 +00001564Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001565 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001566 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001567 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001568}
1569
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001570static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001571 return CmpInst::makeCmpResultType(Op->getType());
1572}
1573
Duncan Sandse864b5b2011-05-07 16:56:49 +00001574/// ExtractEquivalentCondition - Rummage around inside V looking for something
1575/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1576/// otherwise return null. Helper function for analyzing max/min idioms.
1577static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1578 Value *LHS, Value *RHS) {
1579 SelectInst *SI = dyn_cast<SelectInst>(V);
1580 if (!SI)
1581 return 0;
1582 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1583 if (!Cmp)
1584 return 0;
1585 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1586 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1587 return Cmp;
1588 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1589 LHS == CmpRHS && RHS == CmpLHS)
1590 return Cmp;
1591 return 0;
1592}
1593
Micah Villmow3574eca2012-10-08 16:38:25 +00001594static Constant *computePointerICmp(const DataLayout &TD,
Chandler Carruth58725a62012-03-25 21:28:14 +00001595 CmpInst::Predicate Pred,
1596 Value *LHS, Value *RHS) {
1597 // We can only fold certain predicates on pointer comparisons.
1598 switch (Pred) {
1599 default:
1600 return 0;
1601
1602 // Equality comaprisons are easy to fold.
1603 case CmpInst::ICMP_EQ:
1604 case CmpInst::ICMP_NE:
1605 break;
1606
1607 // We can only handle unsigned relational comparisons because 'inbounds' on
1608 // a GEP only protects against unsigned wrapping.
1609 case CmpInst::ICMP_UGT:
1610 case CmpInst::ICMP_UGE:
1611 case CmpInst::ICMP_ULT:
1612 case CmpInst::ICMP_ULE:
1613 // However, we have to switch them to their signed variants to handle
1614 // negative indices from the base pointer.
1615 Pred = ICmpInst::getSignedPredicate(Pred);
1616 break;
1617 }
1618
1619 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1620 if (!LHSOffset)
1621 return 0;
1622 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1623 if (!RHSOffset)
1624 return 0;
1625
1626 // If LHS and RHS are not related via constant offsets to the same base
1627 // value, there is nothing we can do here.
1628 if (LHS != RHS)
1629 return 0;
1630
1631 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1632}
Chris Lattner009e2652012-02-24 19:01:58 +00001633
Chris Lattner9dbb4292009-11-09 23:28:39 +00001634/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1635/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001636static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001637 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001638 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001639 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001640
Chris Lattnerd06094f2009-11-10 00:55:12 +00001641 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001642 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001643 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001644
1645 // If we have a constant, make sure it is on the RHS.
1646 std::swap(LHS, RHS);
1647 Pred = CmpInst::getSwappedPredicate(Pred);
1648 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001649
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001650 Type *ITy = GetCompareTy(LHS); // The return type.
1651 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001652
Chris Lattner210c5d42009-11-09 23:55:12 +00001653 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001654 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1655 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001656 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001657 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001658
Duncan Sands6dc91252011-01-13 08:56:29 +00001659 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001660 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001661 switch (Pred) {
1662 default: break;
1663 case ICmpInst::ICMP_EQ:
1664 // X == 1 -> X
1665 if (match(RHS, m_One()))
1666 return LHS;
1667 break;
1668 case ICmpInst::ICMP_NE:
1669 // X != 0 -> X
1670 if (match(RHS, m_Zero()))
1671 return LHS;
1672 break;
1673 case ICmpInst::ICMP_UGT:
1674 // X >u 0 -> X
1675 if (match(RHS, m_Zero()))
1676 return LHS;
1677 break;
1678 case ICmpInst::ICMP_UGE:
1679 // X >=u 1 -> X
1680 if (match(RHS, m_One()))
1681 return LHS;
1682 break;
1683 case ICmpInst::ICMP_SLT:
1684 // X <s 0 -> X
1685 if (match(RHS, m_Zero()))
1686 return LHS;
1687 break;
1688 case ICmpInst::ICMP_SLE:
1689 // X <=s -1 -> X
1690 if (match(RHS, m_One()))
1691 return LHS;
1692 break;
1693 }
1694 }
1695
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001696 // icmp <object*>, <object*/null> - Different identified objects have
1697 // different addresses (unless null), and what's more the address of an
1698 // identified local is never equal to another argument (again, barring null).
1699 // Note that generalizing to the case where LHS is a global variable address
1700 // or null is pointless, since if both LHS and RHS are constants then we
1701 // already constant folded the compare, and if only one of them is then we
1702 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001703 Value *LHSPtr = LHS->stripPointerCasts();
1704 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001705 if (LHSPtr == RHSPtr)
1706 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001707
Chris Lattnerb053fc12012-02-20 00:42:49 +00001708 // Be more aggressive about stripping pointer adjustments when checking a
1709 // comparison of an alloca address to another object. We can rip off all
1710 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001711 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001712 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001713 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001714 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1715 // If both sides are different identified objects, they aren't equal
1716 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001717 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001718 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001719 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001720
1721 // A local identified object (alloca or noalias call) can't equal any
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001722 // incoming argument, unless they're both null or they belong to
1723 // different functions. The latter happens during inlining.
1724 if (Instruction *LHSInst = dyn_cast<Instruction>(LHSPtr))
1725 if (Argument *RHSArg = dyn_cast<Argument>(RHSPtr))
1726 if (LHSInst->getParent()->getParent() == RHSArg->getParent() &&
1727 Pred == CmpInst::ICMP_EQ)
1728 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001729 }
1730
1731 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001732 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001733 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001734 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001735 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001736 return ConstantInt::get(ITy, true);
1737 }
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001738 } else if (Argument *LHSArg = dyn_cast<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001739 RHSPtr = RHSPtr->stripInBoundsOffsets();
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001740 // An alloca can't be equal to an argument unless they come from separate
1741 // functions via inlining.
1742 if (AllocaInst *RHSInst = dyn_cast<AllocaInst>(RHSPtr)) {
1743 if (LHSArg->getParent() == RHSInst->getParent()->getParent()) {
1744 if (Pred == CmpInst::ICMP_EQ)
1745 return ConstantInt::get(ITy, false);
1746 else if (Pred == CmpInst::ICMP_NE)
1747 return ConstantInt::get(ITy, true);
1748 }
Bill Wendlingc17731d652012-03-10 17:56:03 +00001749 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001750 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001751
1752 // If we are comparing with zero then try hard since this is a common case.
1753 if (match(RHS, m_Zero())) {
1754 bool LHSKnownNonNegative, LHSKnownNegative;
1755 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001756 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001757 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001758 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001759 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001760 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001761 case ICmpInst::ICMP_EQ:
1762 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001763 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001764 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001765 break;
1766 case ICmpInst::ICMP_NE:
1767 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001768 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001769 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001770 break;
1771 case ICmpInst::ICMP_SLT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001772 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001773 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001774 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001775 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001776 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001777 break;
1778 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001779 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001780 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001781 return getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001782 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001783 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001784 break;
1785 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001786 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001787 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001788 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001789 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001790 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001791 break;
1792 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001793 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001794 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001795 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001796 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001797 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001798 break;
1799 }
1800 }
1801
1802 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001803 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001804 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1805 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1806 if (RHS_CR.isEmptySet())
1807 return ConstantInt::getFalse(CI->getContext());
1808 if (RHS_CR.isFullSet())
1809 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001810
Nick Lewycky3a73e342011-03-04 07:00:57 +00001811 // Many binary operators with constant RHS have easy to compute constant
1812 // range. Use them to check whether the comparison is a tautology.
1813 uint32_t Width = CI->getBitWidth();
1814 APInt Lower = APInt(Width, 0);
1815 APInt Upper = APInt(Width, 0);
1816 ConstantInt *CI2;
1817 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1818 // 'urem x, CI2' produces [0, CI2).
1819 Upper = CI2->getValue();
1820 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1821 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1822 Upper = CI2->getValue().abs();
1823 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001824 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1825 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001826 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001827 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1828 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1829 APInt NegOne = APInt::getAllOnesValue(Width);
1830 if (!CI2->isZero())
1831 Upper = NegOne.udiv(CI2->getValue()) + 1;
1832 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1833 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1834 APInt IntMin = APInt::getSignedMinValue(Width);
1835 APInt IntMax = APInt::getSignedMaxValue(Width);
1836 APInt Val = CI2->getValue().abs();
1837 if (!Val.isMinValue()) {
1838 Lower = IntMin.sdiv(Val);
1839 Upper = IntMax.sdiv(Val) + 1;
1840 }
1841 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1842 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1843 APInt NegOne = APInt::getAllOnesValue(Width);
1844 if (CI2->getValue().ult(Width))
1845 Upper = NegOne.lshr(CI2->getValue()) + 1;
1846 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1847 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1848 APInt IntMin = APInt::getSignedMinValue(Width);
1849 APInt IntMax = APInt::getSignedMaxValue(Width);
1850 if (CI2->getValue().ult(Width)) {
1851 Lower = IntMin.ashr(CI2->getValue());
1852 Upper = IntMax.ashr(CI2->getValue()) + 1;
1853 }
1854 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1855 // 'or x, CI2' produces [CI2, UINT_MAX].
1856 Lower = CI2->getValue();
1857 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1858 // 'and x, CI2' produces [0, CI2].
1859 Upper = CI2->getValue() + 1;
1860 }
1861 if (Lower != Upper) {
1862 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1863 if (RHS_CR.contains(LHS_CR))
1864 return ConstantInt::getTrue(RHS->getContext());
1865 if (RHS_CR.inverse().contains(LHS_CR))
1866 return ConstantInt::getFalse(RHS->getContext());
1867 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001868 }
1869
Duncan Sands9d32f602011-01-20 13:21:55 +00001870 // Compare of cast, for example (zext X) != 0 -> X != 0
1871 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1872 Instruction *LI = cast<CastInst>(LHS);
1873 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001874 Type *SrcTy = SrcOp->getType();
1875 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001876
1877 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1878 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001879 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001880 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00001881 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1882 // Transfer the cast to the constant.
1883 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1884 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001885 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001886 return V;
1887 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1888 if (RI->getOperand(0)->getType() == SrcTy)
1889 // Compare without the cast.
1890 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001891 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001892 return V;
1893 }
1894 }
1895
1896 if (isa<ZExtInst>(LHS)) {
1897 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1898 // same type.
1899 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1900 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1901 // Compare X and Y. Note that signed predicates become unsigned.
1902 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001903 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00001904 MaxRecurse-1))
1905 return V;
1906 }
1907 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1908 // too. If not, then try to deduce the result of the comparison.
1909 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1910 // Compute the constant that would happen if we truncated to SrcTy then
1911 // reextended to DstTy.
1912 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1913 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1914
1915 // If the re-extended constant didn't change then this is effectively
1916 // also a case of comparing two zero-extended values.
1917 if (RExt == CI && MaxRecurse)
1918 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001919 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001920 return V;
1921
1922 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1923 // there. Use this to work out the result of the comparison.
1924 if (RExt != CI) {
1925 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001926 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001927 // LHS <u RHS.
1928 case ICmpInst::ICMP_EQ:
1929 case ICmpInst::ICMP_UGT:
1930 case ICmpInst::ICMP_UGE:
1931 return ConstantInt::getFalse(CI->getContext());
1932
1933 case ICmpInst::ICMP_NE:
1934 case ICmpInst::ICMP_ULT:
1935 case ICmpInst::ICMP_ULE:
1936 return ConstantInt::getTrue(CI->getContext());
1937
1938 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1939 // is non-negative then LHS <s RHS.
1940 case ICmpInst::ICMP_SGT:
1941 case ICmpInst::ICMP_SGE:
1942 return CI->getValue().isNegative() ?
1943 ConstantInt::getTrue(CI->getContext()) :
1944 ConstantInt::getFalse(CI->getContext());
1945
1946 case ICmpInst::ICMP_SLT:
1947 case ICmpInst::ICMP_SLE:
1948 return CI->getValue().isNegative() ?
1949 ConstantInt::getFalse(CI->getContext()) :
1950 ConstantInt::getTrue(CI->getContext());
1951 }
1952 }
1953 }
1954 }
1955
1956 if (isa<SExtInst>(LHS)) {
1957 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1958 // same type.
1959 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1960 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1961 // Compare X and Y. Note that the predicate does not change.
1962 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001963 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001964 return V;
1965 }
1966 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1967 // too. If not, then try to deduce the result of the comparison.
1968 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1969 // Compute the constant that would happen if we truncated to SrcTy then
1970 // reextended to DstTy.
1971 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1972 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1973
1974 // If the re-extended constant didn't change then this is effectively
1975 // also a case of comparing two sign-extended values.
1976 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001977 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001978 return V;
1979
1980 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1981 // bits there. Use this to work out the result of the comparison.
1982 if (RExt != CI) {
1983 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001984 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001985 case ICmpInst::ICMP_EQ:
1986 return ConstantInt::getFalse(CI->getContext());
1987 case ICmpInst::ICMP_NE:
1988 return ConstantInt::getTrue(CI->getContext());
1989
1990 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1991 // LHS >s RHS.
1992 case ICmpInst::ICMP_SGT:
1993 case ICmpInst::ICMP_SGE:
1994 return CI->getValue().isNegative() ?
1995 ConstantInt::getTrue(CI->getContext()) :
1996 ConstantInt::getFalse(CI->getContext());
1997 case ICmpInst::ICMP_SLT:
1998 case ICmpInst::ICMP_SLE:
1999 return CI->getValue().isNegative() ?
2000 ConstantInt::getFalse(CI->getContext()) :
2001 ConstantInt::getTrue(CI->getContext());
2002
2003 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2004 // LHS >u RHS.
2005 case ICmpInst::ICMP_UGT:
2006 case ICmpInst::ICMP_UGE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002007 // Comparison is true iff the LHS <s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002008 if (MaxRecurse)
2009 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2010 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002011 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002012 return V;
2013 break;
2014 case ICmpInst::ICMP_ULT:
2015 case ICmpInst::ICMP_ULE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002016 // Comparison is true iff the LHS >=s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002017 if (MaxRecurse)
2018 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2019 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002020 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002021 return V;
2022 break;
2023 }
2024 }
2025 }
2026 }
2027 }
2028
Duncan Sands52fb8462011-02-13 17:15:40 +00002029 // Special logic for binary operators.
2030 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2031 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2032 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002033 // Analyze the case when either LHS or RHS is an add instruction.
2034 Value *A = 0, *B = 0, *C = 0, *D = 0;
2035 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2036 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2037 if (LBO && LBO->getOpcode() == Instruction::Add) {
2038 A = LBO->getOperand(0); B = LBO->getOperand(1);
2039 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2040 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2041 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2042 }
2043 if (RBO && RBO->getOpcode() == Instruction::Add) {
2044 C = RBO->getOperand(0); D = RBO->getOperand(1);
2045 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2046 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2047 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2048 }
2049
2050 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2051 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2052 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2053 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002054 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002055 return V;
2056
2057 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2058 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2059 if (Value *V = SimplifyICmpInst(Pred,
2060 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002061 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002062 return V;
2063
2064 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2065 if (A && C && (A == C || A == D || B == C || B == D) &&
2066 NoLHSWrapProblem && NoRHSWrapProblem) {
2067 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002068 Value *Y, *Z;
2069 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002070 // C + B == C + D -> B == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002071 Y = B;
2072 Z = D;
2073 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002074 // D + B == C + D -> B == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002075 Y = B;
2076 Z = C;
2077 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002078 // A + C == C + D -> A == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002079 Y = A;
2080 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002081 } else {
2082 assert(B == D);
2083 // A + D == C + D -> A == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002084 Y = A;
2085 Z = C;
2086 }
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002087 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002088 return V;
2089 }
2090 }
2091
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002092 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002093 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002094 switch (Pred) {
2095 default:
2096 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002097 case ICmpInst::ICMP_SGT:
2098 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002099 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002100 if (!KnownNonNegative)
2101 break;
2102 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002103 case ICmpInst::ICMP_EQ:
2104 case ICmpInst::ICMP_UGT:
2105 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002106 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002107 case ICmpInst::ICMP_SLT:
2108 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002109 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002110 if (!KnownNonNegative)
2111 break;
2112 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002113 case ICmpInst::ICMP_NE:
2114 case ICmpInst::ICMP_ULT:
2115 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002116 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002117 }
2118 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002119 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2120 bool KnownNonNegative, KnownNegative;
2121 switch (Pred) {
2122 default:
2123 break;
2124 case ICmpInst::ICMP_SGT:
2125 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002126 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002127 if (!KnownNonNegative)
2128 break;
2129 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002130 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002131 case ICmpInst::ICMP_UGT:
2132 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002133 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002134 case ICmpInst::ICMP_SLT:
2135 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002136 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002137 if (!KnownNonNegative)
2138 break;
2139 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002140 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002141 case ICmpInst::ICMP_ULT:
2142 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002143 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002144 }
2145 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002146
Duncan Sandsc65c7472011-10-28 18:17:44 +00002147 // x udiv y <=u x.
2148 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2149 // icmp pred (X /u Y), X
2150 if (Pred == ICmpInst::ICMP_UGT)
2151 return getFalse(ITy);
2152 if (Pred == ICmpInst::ICMP_ULE)
2153 return getTrue(ITy);
2154 }
2155
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002156 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2157 LBO->getOperand(1) == RBO->getOperand(1)) {
2158 switch (LBO->getOpcode()) {
2159 default: break;
2160 case Instruction::UDiv:
2161 case Instruction::LShr:
2162 if (ICmpInst::isSigned(Pred))
2163 break;
2164 // fall-through
2165 case Instruction::SDiv:
2166 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002167 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002168 break;
2169 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002170 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002171 return V;
2172 break;
2173 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002174 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002175 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2176 if (!NUW && !NSW)
2177 break;
2178 if (!NSW && ICmpInst::isSigned(Pred))
2179 break;
2180 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002181 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002182 return V;
2183 break;
2184 }
2185 }
2186 }
2187
Duncan Sandsad206812011-05-03 19:53:10 +00002188 // Simplify comparisons involving max/min.
2189 Value *A, *B;
2190 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002191 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sandsad206812011-05-03 19:53:10 +00002192
Duncan Sands8140ad32011-05-04 16:05:05 +00002193 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002194 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2195 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002196 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002197 // We analyze this as smax(A, B) pred A.
2198 P = Pred;
2199 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2200 (A == LHS || B == LHS)) {
2201 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002202 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002203 // We analyze this as smax(A, B) swapped-pred A.
2204 P = CmpInst::getSwappedPredicate(Pred);
2205 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2206 (A == RHS || B == RHS)) {
2207 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002208 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002209 // We analyze this as smax(-A, -B) swapped-pred -A.
2210 // Note that we do not need to actually form -A or -B thanks to EqP.
2211 P = CmpInst::getSwappedPredicate(Pred);
2212 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2213 (A == LHS || B == LHS)) {
2214 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002215 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002216 // We analyze this as smax(-A, -B) pred -A.
2217 // Note that we do not need to actually form -A or -B thanks to EqP.
2218 P = Pred;
2219 }
2220 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2221 // Cases correspond to "max(A, B) p A".
2222 switch (P) {
2223 default:
2224 break;
2225 case CmpInst::ICMP_EQ:
2226 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002227 // Equivalent to "A EqP B". This may be the same as the condition tested
2228 // in the max/min; if so, we can just return that.
2229 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2230 return V;
2231 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2232 return V;
2233 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002234 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002235 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002236 return V;
2237 break;
2238 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002239 case CmpInst::ICMP_SGT: {
2240 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2241 // Equivalent to "A InvEqP B". This may be the same as the condition
2242 // tested in the max/min; if so, we can just return that.
2243 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2244 return V;
2245 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2246 return V;
2247 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002248 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002249 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002250 return V;
2251 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002252 }
Duncan Sandsad206812011-05-03 19:53:10 +00002253 case CmpInst::ICMP_SGE:
2254 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002255 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002256 case CmpInst::ICMP_SLT:
2257 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002258 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002259 }
2260 }
2261
Duncan Sands8140ad32011-05-04 16:05:05 +00002262 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002263 P = CmpInst::BAD_ICMP_PREDICATE;
2264 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2265 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002266 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002267 // We analyze this as umax(A, B) pred A.
2268 P = Pred;
2269 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2270 (A == LHS || B == LHS)) {
2271 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002272 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002273 // We analyze this as umax(A, B) swapped-pred A.
2274 P = CmpInst::getSwappedPredicate(Pred);
2275 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2276 (A == RHS || B == RHS)) {
2277 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002278 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002279 // We analyze this as umax(-A, -B) swapped-pred -A.
2280 // Note that we do not need to actually form -A or -B thanks to EqP.
2281 P = CmpInst::getSwappedPredicate(Pred);
2282 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2283 (A == LHS || B == LHS)) {
2284 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002285 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002286 // We analyze this as umax(-A, -B) pred -A.
2287 // Note that we do not need to actually form -A or -B thanks to EqP.
2288 P = Pred;
2289 }
2290 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2291 // Cases correspond to "max(A, B) p A".
2292 switch (P) {
2293 default:
2294 break;
2295 case CmpInst::ICMP_EQ:
2296 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002297 // Equivalent to "A EqP B". This may be the same as the condition tested
2298 // in the max/min; if so, we can just return that.
2299 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2300 return V;
2301 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2302 return V;
2303 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002304 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002305 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002306 return V;
2307 break;
2308 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002309 case CmpInst::ICMP_UGT: {
2310 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2311 // Equivalent to "A InvEqP B". This may be the same as the condition
2312 // tested in the max/min; if so, we can just return that.
2313 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2314 return V;
2315 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2316 return V;
2317 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002318 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002319 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002320 return V;
2321 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002322 }
Duncan Sandsad206812011-05-03 19:53:10 +00002323 case CmpInst::ICMP_UGE:
2324 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002325 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002326 case CmpInst::ICMP_ULT:
2327 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002328 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002329 }
2330 }
2331
Duncan Sands8140ad32011-05-04 16:05:05 +00002332 // Variants on "max(x,y) >= min(x,z)".
2333 Value *C, *D;
2334 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2335 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2336 (A == C || A == D || B == C || B == D)) {
2337 // max(x, ?) pred min(x, ?).
2338 if (Pred == CmpInst::ICMP_SGE)
2339 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002340 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002341 if (Pred == CmpInst::ICMP_SLT)
2342 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002343 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002344 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2345 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2346 (A == C || A == D || B == C || B == D)) {
2347 // min(x, ?) pred max(x, ?).
2348 if (Pred == CmpInst::ICMP_SLE)
2349 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002350 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002351 if (Pred == CmpInst::ICMP_SGT)
2352 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002353 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002354 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2355 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2356 (A == C || A == D || B == C || B == D)) {
2357 // max(x, ?) pred min(x, ?).
2358 if (Pred == CmpInst::ICMP_UGE)
2359 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002360 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002361 if (Pred == CmpInst::ICMP_ULT)
2362 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002363 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002364 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2365 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2366 (A == C || A == D || B == C || B == D)) {
2367 // min(x, ?) pred max(x, ?).
2368 if (Pred == CmpInst::ICMP_ULE)
2369 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002370 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002371 if (Pred == CmpInst::ICMP_UGT)
2372 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002373 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002374 }
2375
Chandler Carruth58725a62012-03-25 21:28:14 +00002376 // Simplify comparisons of related pointers using a powerful, recursive
2377 // GEP-walk when we have target data available..
2378 if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy())
2379 if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2380 return C;
2381
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002382 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2383 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2384 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2385 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2386 (ICmpInst::isEquality(Pred) ||
2387 (GLHS->isInBounds() && GRHS->isInBounds() &&
2388 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2389 // The bases are equal and the indices are constant. Build a constant
2390 // expression GEP with the same indices and a null base pointer to see
2391 // what constant folding can make out of it.
2392 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2393 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2394 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2395
2396 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2397 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2398 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2399 }
2400 }
2401 }
2402
Duncan Sands1ac7c992010-11-07 16:12:23 +00002403 // If the comparison is with the result of a select instruction, check whether
2404 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002405 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002406 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002407 return V;
2408
2409 // If the comparison is with the result of a phi instruction, check whether
2410 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002411 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002412 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002413 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002414
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002415 return 0;
2416}
2417
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002418Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002419 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002420 const TargetLibraryInfo *TLI,
2421 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002422 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2423 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002424}
2425
Chris Lattner9dbb4292009-11-09 23:28:39 +00002426/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2427/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002428static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002429 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002430 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2431 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2432
Chris Lattnerd06094f2009-11-10 00:55:12 +00002433 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002434 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002435 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002436
Chris Lattnerd06094f2009-11-10 00:55:12 +00002437 // If we have a constant, make sure it is on the RHS.
2438 std::swap(LHS, RHS);
2439 Pred = CmpInst::getSwappedPredicate(Pred);
2440 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002441
Chris Lattner210c5d42009-11-09 23:55:12 +00002442 // Fold trivial predicates.
2443 if (Pred == FCmpInst::FCMP_FALSE)
2444 return ConstantInt::get(GetCompareTy(LHS), 0);
2445 if (Pred == FCmpInst::FCMP_TRUE)
2446 return ConstantInt::get(GetCompareTy(LHS), 1);
2447
Chris Lattner210c5d42009-11-09 23:55:12 +00002448 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2449 return UndefValue::get(GetCompareTy(LHS));
2450
2451 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002452 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002453 if (CmpInst::isTrueWhenEqual(Pred))
2454 return ConstantInt::get(GetCompareTy(LHS), 1);
2455 if (CmpInst::isFalseWhenEqual(Pred))
2456 return ConstantInt::get(GetCompareTy(LHS), 0);
2457 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002458
Chris Lattner210c5d42009-11-09 23:55:12 +00002459 // Handle fcmp with constant RHS
2460 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2461 // If the constant is a nan, see if we can fold the comparison based on it.
2462 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2463 if (CFP->getValueAPF().isNaN()) {
2464 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2465 return ConstantInt::getFalse(CFP->getContext());
2466 assert(FCmpInst::isUnordered(Pred) &&
2467 "Comparison must be either ordered or unordered!");
2468 // True if unordered.
2469 return ConstantInt::getTrue(CFP->getContext());
2470 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002471 // Check whether the constant is an infinity.
2472 if (CFP->getValueAPF().isInfinity()) {
2473 if (CFP->getValueAPF().isNegative()) {
2474 switch (Pred) {
2475 case FCmpInst::FCMP_OLT:
2476 // No value is ordered and less than negative infinity.
2477 return ConstantInt::getFalse(CFP->getContext());
2478 case FCmpInst::FCMP_UGE:
2479 // All values are unordered with or at least negative infinity.
2480 return ConstantInt::getTrue(CFP->getContext());
2481 default:
2482 break;
2483 }
2484 } else {
2485 switch (Pred) {
2486 case FCmpInst::FCMP_OGT:
2487 // No value is ordered and greater than infinity.
2488 return ConstantInt::getFalse(CFP->getContext());
2489 case FCmpInst::FCMP_ULE:
2490 // All values are unordered with and at most infinity.
2491 return ConstantInt::getTrue(CFP->getContext());
2492 default:
2493 break;
2494 }
2495 }
2496 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002497 }
2498 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002499
Duncan Sands92826de2010-11-07 16:46:25 +00002500 // If the comparison is with the result of a select instruction, check whether
2501 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002502 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002503 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002504 return V;
2505
2506 // If the comparison is with the result of a phi instruction, check whether
2507 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002508 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002509 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002510 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002511
Chris Lattner9dbb4292009-11-09 23:28:39 +00002512 return 0;
2513}
2514
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002515Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002516 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002517 const TargetLibraryInfo *TLI,
2518 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002519 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2520 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002521}
2522
Chris Lattner04754262010-04-20 05:32:14 +00002523/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2524/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002525static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2526 Value *FalseVal, const Query &Q,
2527 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002528 // select true, X, Y -> X
2529 // select false, X, Y -> Y
2530 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2531 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002532
Chris Lattner04754262010-04-20 05:32:14 +00002533 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002534 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002535 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002536
Chris Lattner04754262010-04-20 05:32:14 +00002537 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2538 if (isa<Constant>(TrueVal))
2539 return TrueVal;
2540 return FalseVal;
2541 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002542 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2543 return FalseVal;
2544 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2545 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002546
Chris Lattner04754262010-04-20 05:32:14 +00002547 return 0;
2548}
2549
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002550Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Micah Villmow3574eca2012-10-08 16:38:25 +00002551 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002552 const TargetLibraryInfo *TLI,
2553 const DominatorTree *DT) {
2554 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2555 RecursionLimit);
2556}
2557
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002558/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2559/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002560static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002561 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002562 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2563 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2564 if (!PtrTy)
2565 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002566
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002567 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002568 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002569 return Ops[0];
2570
Duncan Sands85bbff62010-11-22 13:42:49 +00002571 if (isa<UndefValue>(Ops[0])) {
2572 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002573 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002574 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002575 return UndefValue::get(GEPTy);
2576 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002577
Jay Foadb9b54eb2011-07-19 15:07:52 +00002578 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002579 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002580 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2581 if (C->isZero())
2582 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002583 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002584 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002585 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002586 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002587 return Ops[0];
2588 }
2589 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002590
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002591 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002592 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002593 if (!isa<Constant>(Ops[i]))
2594 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002595
Jay Foaddab3d292011-07-21 14:31:17 +00002596 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002597}
2598
Micah Villmow3574eca2012-10-08 16:38:25 +00002599Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002600 const TargetLibraryInfo *TLI,
2601 const DominatorTree *DT) {
2602 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2603}
2604
Duncan Sandsdabc2802011-09-05 06:52:48 +00002605/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2606/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002607static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2608 ArrayRef<unsigned> Idxs, const Query &Q,
2609 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002610 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2611 if (Constant *CVal = dyn_cast<Constant>(Val))
2612 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2613
2614 // insertvalue x, undef, n -> x
2615 if (match(Val, m_Undef()))
2616 return Agg;
2617
2618 // insertvalue x, (extractvalue y, n), n
2619 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002620 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2621 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002622 // insertvalue undef, (extractvalue y, n), n -> y
2623 if (match(Agg, m_Undef()))
2624 return EV->getAggregateOperand();
2625
2626 // insertvalue y, (extractvalue y, n), n -> y
2627 if (Agg == EV->getAggregateOperand())
2628 return Agg;
2629 }
2630
2631 return 0;
2632}
2633
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002634Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2635 ArrayRef<unsigned> Idxs,
Micah Villmow3574eca2012-10-08 16:38:25 +00002636 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002637 const TargetLibraryInfo *TLI,
2638 const DominatorTree *DT) {
2639 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2640 RecursionLimit);
2641}
2642
Duncan Sandsff103412010-11-17 04:30:22 +00002643/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002644static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002645 // If all of the PHI's incoming values are the same then replace the PHI node
2646 // with the common value.
2647 Value *CommonValue = 0;
2648 bool HasUndefInput = false;
2649 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2650 Value *Incoming = PN->getIncomingValue(i);
2651 // If the incoming value is the phi node itself, it can safely be skipped.
2652 if (Incoming == PN) continue;
2653 if (isa<UndefValue>(Incoming)) {
2654 // Remember that we saw an undef value, but otherwise ignore them.
2655 HasUndefInput = true;
2656 continue;
2657 }
2658 if (CommonValue && Incoming != CommonValue)
2659 return 0; // Not the same, bail out.
2660 CommonValue = Incoming;
2661 }
2662
2663 // If CommonValue is null then all of the incoming values were either undef or
2664 // equal to the phi node itself.
2665 if (!CommonValue)
2666 return UndefValue::get(PN->getType());
2667
2668 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2669 // instruction, we cannot return X as the result of the PHI node unless it
2670 // dominates the PHI block.
2671 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002672 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002673
2674 return CommonValue;
2675}
2676
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002677static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2678 if (Constant *C = dyn_cast<Constant>(Op))
2679 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2680
2681 return 0;
2682}
2683
Micah Villmow3574eca2012-10-08 16:38:25 +00002684Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002685 const TargetLibraryInfo *TLI,
2686 const DominatorTree *DT) {
2687 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2688}
2689
Chris Lattnerd06094f2009-11-10 00:55:12 +00002690//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002691
Chris Lattnerd06094f2009-11-10 00:55:12 +00002692/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2693/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002694static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002695 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002696 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002697 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002698 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002699 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002700 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002701 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002702 Q, MaxRecurse);
2703 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2704 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2705 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2706 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2707 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2708 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2709 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002710 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002711 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002712 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002713 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002714 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002715 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002716 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2717 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2718 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2719 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002720 default:
2721 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2722 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2723 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002724 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2725 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002726 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002727
Duncan Sands566edb02010-12-21 08:49:00 +00002728 // If the operation is associative, try some generic simplifications.
2729 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002730 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002731 return V;
2732
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002733 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002734 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002735 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002736 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002737 return V;
2738
2739 // If the operation is with the result of a phi instruction, check whether
2740 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002741 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002742 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002743 return V;
2744
Chris Lattnerd06094f2009-11-10 00:55:12 +00002745 return 0;
2746 }
2747}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002748
Duncan Sands12a86f52010-11-14 11:23:23 +00002749Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002750 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002751 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002752 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002753}
2754
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002755/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2756/// fold the result.
2757static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002758 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002759 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002760 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2761 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002762}
2763
2764Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002765 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002766 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002767 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2768 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002769}
Chris Lattnere3453782009-11-10 01:08:51 +00002770
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002771static Value *SimplifyCallInst(CallInst *CI, const Query &) {
Dan Gohman71d05032011-11-04 18:32:42 +00002772 // call undef -> undef
2773 if (isa<UndefValue>(CI->getCalledValue()))
2774 return UndefValue::get(CI->getType());
2775
2776 return 0;
2777}
2778
Chris Lattnere3453782009-11-10 01:08:51 +00002779/// SimplifyInstruction - See if we can compute a simplified version of this
2780/// instruction. If not, this returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00002781Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002782 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002783 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002784 Value *Result;
2785
Chris Lattnere3453782009-11-10 01:08:51 +00002786 switch (I->getOpcode()) {
2787 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002788 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002789 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002790 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002791 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2792 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2793 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002794 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002795 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002796 case Instruction::Sub:
2797 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2798 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2799 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002800 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002801 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002802 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002803 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002804 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002805 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002806 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002807 break;
2808 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002809 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002810 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002811 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002812 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002813 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002814 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002815 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002816 break;
2817 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002818 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002819 break;
2820 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002821 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002822 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002823 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002824 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2825 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2826 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002827 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002828 break;
2829 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002830 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2831 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002832 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002833 break;
2834 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002835 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2836 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002837 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002838 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002839 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002840 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002841 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002842 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002843 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002844 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002845 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002846 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002847 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002848 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002849 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002850 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002851 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002852 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002853 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002854 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002855 break;
Chris Lattner04754262010-04-20 05:32:14 +00002856 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002857 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002858 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002859 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002860 case Instruction::GetElementPtr: {
2861 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002862 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002863 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002864 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002865 case Instruction::InsertValue: {
2866 InsertValueInst *IV = cast<InsertValueInst>(I);
2867 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2868 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002869 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00002870 break;
2871 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002872 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002873 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00002874 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002875 case Instruction::Call:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002876 Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
Dan Gohman71d05032011-11-04 18:32:42 +00002877 break;
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002878 case Instruction::Trunc:
2879 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2880 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002881 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002882
2883 /// If called on unreachable code, the above logic may report that the
2884 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002885 /// detecting that case here, returning a safe value instead.
2886 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002887}
2888
Chandler Carruth6b980542012-03-24 21:11:24 +00002889/// \brief Implementation of recursive simplification through an instructions
2890/// uses.
Chris Lattner40d8c282009-11-10 22:26:15 +00002891///
Chandler Carruth6b980542012-03-24 21:11:24 +00002892/// This is the common implementation of the recursive simplification routines.
2893/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
2894/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
2895/// instructions to process and attempt to simplify it using
2896/// InstructionSimplify.
2897///
2898/// This routine returns 'true' only when *it* simplifies something. The passed
2899/// in simplified value does not count toward this.
2900static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00002901 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00002902 const TargetLibraryInfo *TLI,
2903 const DominatorTree *DT) {
2904 bool Simplified = false;
Chandler Carruth6231d5b2012-03-24 22:34:26 +00002905 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands12a86f52010-11-14 11:23:23 +00002906
Chandler Carruth6b980542012-03-24 21:11:24 +00002907 // If we have an explicit value to collapse to, do that round of the
2908 // simplification loop by hand initially.
2909 if (SimpleV) {
2910 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2911 ++UI)
Chandler Carruthc5b785b2012-03-24 22:34:23 +00002912 if (*UI != I)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00002913 Worklist.insert(cast<Instruction>(*UI));
Duncan Sands12a86f52010-11-14 11:23:23 +00002914
Chandler Carruth6b980542012-03-24 21:11:24 +00002915 // Replace the instruction with its simplified value.
2916 I->replaceAllUsesWith(SimpleV);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002917
Chandler Carruth6b980542012-03-24 21:11:24 +00002918 // Gracefully handle edge cases where the instruction is not wired into any
2919 // parent block.
2920 if (I->getParent())
2921 I->eraseFromParent();
2922 } else {
Chandler Carruth6231d5b2012-03-24 22:34:26 +00002923 Worklist.insert(I);
Chris Lattner40d8c282009-11-10 22:26:15 +00002924 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002925
Chandler Carruth6231d5b2012-03-24 22:34:26 +00002926 // Note that we must test the size on each iteration, the worklist can grow.
2927 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
2928 I = Worklist[Idx];
Duncan Sands12a86f52010-11-14 11:23:23 +00002929
Chandler Carruth6b980542012-03-24 21:11:24 +00002930 // See if this instruction simplifies.
2931 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
2932 if (!SimpleV)
2933 continue;
2934
2935 Simplified = true;
2936
2937 // Stash away all the uses of the old instruction so we can check them for
2938 // recursive simplifications after a RAUW. This is cheaper than checking all
2939 // uses of To on the recursive step in most cases.
2940 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2941 ++UI)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00002942 Worklist.insert(cast<Instruction>(*UI));
Chandler Carruth6b980542012-03-24 21:11:24 +00002943
2944 // Replace the instruction with its simplified value.
2945 I->replaceAllUsesWith(SimpleV);
2946
2947 // Gracefully handle edge cases where the instruction is not wired into any
2948 // parent block.
2949 if (I->getParent())
2950 I->eraseFromParent();
2951 }
2952 return Simplified;
2953}
2954
2955bool llvm::recursivelySimplifyInstruction(Instruction *I,
Micah Villmow3574eca2012-10-08 16:38:25 +00002956 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00002957 const TargetLibraryInfo *TLI,
2958 const DominatorTree *DT) {
2959 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
2960}
2961
2962bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00002963 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00002964 const TargetLibraryInfo *TLI,
2965 const DominatorTree *DT) {
2966 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
2967 assert(SimpleV && "Must provide a simplified value.");
2968 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
Chris Lattner40d8c282009-11-10 22:26:15 +00002969}